Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

refactor(cloudformation): move the ElasticLoadBalancingV2 types into ElbV2CfnProvisioner (#3115)

Hector Ventura2541f1b68d56
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index 886030ad54..6767c55b27 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -58,13 +58,6 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
-import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
-import io.github.hectorvent.floci.services.elbv2.model.Action;
-import io.github.hectorvent.floci.services.elbv2.model.Listener;
-import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
-import io.github.hectorvent.floci.services.elbv2.model.Rule;
-import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
-import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.kms.KmsService;
@@ -223,10 +216,6 @@ public class CloudFormationResourceProvisioner {
"AWS::EC2::SubnetRouteTableAssociation",
"AWS::EKS::Cluster",
"AWS::EKS::Nodegroup",
- "AWS::ElasticLoadBalancingV2::Listener",
- "AWS::ElasticLoadBalancingV2::ListenerRule",
- "AWS::ElasticLoadBalancingV2::LoadBalancer",
- "AWS::ElasticLoadBalancingV2::TargetGroup",
"AWS::Events::EventBus",
"AWS::Events::EventBusPolicy",
"AWS::Events::Rule",
@@ -271,7 +260,6 @@ public class CloudFormationResourceProvisioner {
private final ObjectMapper objectMapper;
private final CustomResourceResponseStore customResourceResponseStore;
private final ContainerReachableEndpoint reachableEndpoint;
- private final ElbV2Service elbV2Service;
private final StepFunctionsService stepFunctionsService;
private final BatchService batchService;
private final Ec2Service ec2Service;
@@ -302,7 +290,6 @@ public class CloudFormationResourceProvisioner {
ObjectMapper objectMapper,
CustomResourceResponseStore customResourceResponseStore,
ContainerReachableEndpoint reachableEndpoint,
- ElbV2Service elbV2Service,
StepFunctionsService stepFunctionsService,
BatchService batchService,
Ec2Service ec2Service,
@@ -331,7 +318,6 @@ public class CloudFormationResourceProvisioner {
this.objectMapper = objectMapper;
this.customResourceResponseStore = customResourceResponseStore;
this.reachableEndpoint = reachableEndpoint;
- this.elbV2Service = elbV2Service;
this.stepFunctionsService = stepFunctionsService;
this.batchService = batchService;
this.ec2Service = ec2Service;
@@ -425,14 +411,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::CloudFormation::CustomResource" ->
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
case "Custom::DynamoDBReplica" -> provisionDynamoDbReplica(resource, properties, engine, region);
- case "AWS::ElasticLoadBalancingV2::LoadBalancer" ->
- provisionLoadBalancer(resource, properties, engine, region, stackName);
- case "AWS::ElasticLoadBalancingV2::TargetGroup" ->
- provisionTargetGroup(resource, properties, engine, region, stackName);
- case "AWS::ElasticLoadBalancingV2::Listener" ->
- provisionListener(resource, properties, engine, region);
- case "AWS::ElasticLoadBalancingV2::ListenerRule" ->
- provisionListenerRule(resource, properties, engine, region);
case "AWS::Batch::ComputeEnvironment" ->
provisionBatchComputeEnvironment(resource, properties, engine, region, stackName);
case "AWS::Batch::JobQueue" ->
@@ -706,10 +684,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
- case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
- case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
- case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
- case "AWS::ElasticLoadBalancingV2::ListenerRule" -> elbV2Service.deleteRule(region, physicalId);
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region);
@@ -6102,300 +6076,6 @@ public class CloudFormationResourceProvisioner {
return result;
}
- // ── ELBv2 ────────────────────────────────────────────────────────────────
-
- private void provisionLoadBalancer(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String name = resolveOptional(props, "Name", engine);
- if (name == null || name.isBlank()) {
- name = generateElbName(stackName, r.getLogicalId());
- }
- String scheme = resolveOptional(props, "Scheme", engine);
- String type = resolveOptional(props, "Type", engine);
- String ipAddressType = resolveOptional(props, "IpAddressType", engine);
- List<String> subnets = resolveStringListOrEmpty(props, "Subnets", engine);
- List<String> securityGroups = resolveStringListOrEmpty(props, "SecurityGroups", engine);
- Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
-
- LoadBalancer lb;
- try {
- lb = elbV2Service.createLoadBalancer(region, name, scheme, type, ipAddressType,
- subnets, securityGroups, tags);
- } catch (AwsException e) {
- if ("DuplicateLoadBalancerName".equals(e.getErrorCode())) {
- lb = elbV2Service.describeLoadBalancers(region, null, List.of(name), null, null).get(0);
- } else {
- throw e;
- }
- }
-
- r.setPhysicalId(lb.getLoadBalancerArn());
- r.getAttributes().put("LoadBalancerArn", lb.getLoadBalancerArn());
- r.getAttributes().put("DNSName", lb.getDnsName());
- r.getAttributes().put("CanonicalHostedZoneID", lb.getCanonicalHostedZoneId());
- r.getAttributes().put("LoadBalancerName", lb.getLoadBalancerName());
- r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));
- }
-
- private void provisionTargetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String name = resolveOptional(props, "Name", engine);
- if (name == null || name.isBlank()) {
- name = generateElbName(stackName, r.getLogicalId());
- }
- String protocol = resolveOptional(props, "Protocol", engine);
- String protocolVersion = resolveOptional(props, "ProtocolVersion", engine);
- Integer port = parseIntOrNull(resolveOptional(props, "Port", engine));
- String vpcId = resolveOptional(props, "VpcId", engine);
- String targetType = resolveOptional(props, "TargetType", engine);
- String hcProtocol = resolveOptional(props, "HealthCheckProtocol", engine);
- String hcPort = resolveOptional(props, "HealthCheckPort", engine);
- Boolean hcEnabled = parseBooleanOrNull(resolveOptional(props, "HealthCheckEnabled", engine));
- String hcPath = resolveOptional(props, "HealthCheckPath", engine);
- Integer hcInterval = parseIntOrNull(resolveOptional(props, "HealthCheckIntervalSeconds", engine));
- Integer hcTimeout = parseIntOrNull(resolveOptional(props, "HealthCheckTimeoutSeconds", engine));
- Integer healthyThreshold = parseIntOrNull(resolveOptional(props, "HealthyThresholdCount", engine));
- Integer unhealthyThreshold = parseIntOrNull(resolveOptional(props, "UnhealthyThresholdCount", engine));
- String matcher = parseMatcher(props, engine);
- String ipAddressType = resolveOptional(props, "IpAddressType", engine);
- Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
-
- TargetGroup tg;
- try {
- tg = elbV2Service.createTargetGroup(region, name, protocol, protocolVersion, port, vpcId, targetType,
- hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
- healthyThreshold, unhealthyThreshold, matcher, ipAddressType, tags);
- } catch (AwsException e) {
- if ("DuplicateTargetGroupName".equals(e.getErrorCode())) {
- tg = elbV2Service.describeTargetGroups(region, null, null, List.of(name)).get(0);
- } else {
- throw e;
- }
- }
-
- r.setPhysicalId(tg.getTargetGroupArn());
- r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
- r.getAttributes().put("TargetGroupName", tg.getTargetGroupName());
- r.getAttributes().put("TargetGroupFullName", targetGroupFullName(tg.getTargetGroupArn()));
- }
-
- private void provisionListener(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String lbArn = resolveOptional(props, "LoadBalancerArn", engine);
- String protocol = resolveOrDefault(props, "Protocol", engine, "HTTP");
- int port = intOrDefault(resolveOptional(props, "Port", engine), 80);
- String sslPolicy = resolveOptional(props, "SslPolicy", engine);
- List<String> certificates = parseCertificates(props, engine);
- List<Action> defaultActions = parseCfnActions(props != null ? props.get("DefaultActions") : null, engine);
-
- Listener listener;
- if (r.getPhysicalId() == null) {
- listener = elbV2Service.createListener(region, lbArn, protocol, port, sslPolicy, certificates,
- defaultActions, null, Map.of());
- } else {
- listener = elbV2Service.modifyListener(region, r.getPhysicalId(), protocol, port, sslPolicy,
- certificates, defaultActions, null);
- }
-
- r.setPhysicalId(listener.getListenerArn());
- r.getAttributes().put("ListenerArn", listener.getListenerArn());
- }
-
- private void provisionListenerRule(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region) {
- String listenerArn = resolveOptional(props, "ListenerArn", engine);
- int priority = intOrDefault(resolveOptional(props, "Priority", engine), 1);
- List<RuleCondition> conditions =
- parseCfnRuleConditions(props != null ? props.get("Conditions") : null, engine);
- List<Action> actions = parseCfnActions(props != null ? props.get("Actions") : null, engine);
-
- Rule rule;
- if (r.getPhysicalId() == null) {
- rule = elbV2Service.createRule(region, listenerArn, conditions, priority, actions, Map.of());
- } else {
- rule = elbV2Service.modifyRule(region, r.getPhysicalId(), conditions, actions);
- }
-
- r.setPhysicalId(rule.getRuleArn());
- r.getAttributes().put("RuleArn", rule.getRuleArn());
- r.getAttributes().put("IsDefault", String.valueOf(rule.isDefault()));
- }
-
- private List<Action> parseCfnActions(JsonNode node, CloudFormationTemplateEngine engine) {
- List<Action> result = new ArrayList<>();
- if (node == null || node.isNull()) {
- return result;
- }
- JsonNode resolved = engine.resolveNode(node);
- if (!resolved.isArray()) {
- return result;
- }
- for (JsonNode item : resolved) {
- Action action = new Action();
- action.setType(textOrNull(item, "Type"));
- if (item.hasNonNull("Order")) {
- action.setOrder(item.path("Order").asInt());
- }
- if (item.hasNonNull("TargetGroupArn")) {
- action.setTargetGroupArn(item.path("TargetGroupArn").asText());
- }
- JsonNode forward = item.path("ForwardConfig");
- if (forward.isObject()) {
- JsonNode tgs = forward.path("TargetGroups");
- if (tgs.isArray()) {
- List<Action.TargetGroupTuple> tuples = new ArrayList<>();
- for (JsonNode t : tgs) {
- Action.TargetGroupTuple tuple = new Action.TargetGroupTuple();
- if (t.hasNonNull("TargetGroupArn")) {
- tuple.setTargetGroupArn(t.path("TargetGroupArn").asText());
- }
- if (t.hasNonNull("Weight")) {
- tuple.setWeight(t.path("Weight").asInt());
- }
- tuples.add(tuple);
- }
- action.setTargetGroups(tuples);
- }
- JsonNode stickiness = forward.path("TargetGroupStickinessConfig");
- if (stickiness.isObject()) {
- if (stickiness.hasNonNull("Enabled")) {
- action.setStickinessEnabled(stickiness.path("Enabled").asBoolean());
- }
- if (stickiness.hasNonNull("DurationSeconds")) {
- action.setStickinessDurationSeconds(stickiness.path("DurationSeconds").asInt());
- }
- }
- }
- JsonNode redirect = item.path("RedirectConfig");
- if (redirect.isObject()) {
- action.setRedirectProtocol(textOrNull(redirect, "Protocol"));
- action.setRedirectPort(textOrNull(redirect, "Port"));
- action.setRedirectHost(textOrNull(redirect, "Host"));
- action.setRedirectPath(textOrNull(redirect, "Path"));
- action.setRedirectQuery(textOrNull(redirect, "Query"));
- action.setRedirectStatusCode(textOrNull(redirect, "StatusCode"));
- }
- JsonNode fixed = item.path("FixedResponseConfig");
- if (fixed.isObject()) {
- action.setFixedResponseStatusCode(textOrNull(fixed, "StatusCode"));
- action.setFixedResponseContentType(textOrNull(fixed, "ContentType"));
- action.setFixedResponseMessageBody(textOrNull(fixed, "MessageBody"));
- }
- result.add(action);
- }
- return result;
- }
-
- private List<RuleCondition> parseCfnRuleConditions(JsonNode node, CloudFormationTemplateEngine engine) {
- List<RuleCondition> result = new ArrayList<>();
- if (node == null || node.isNull()) {
- return result;
- }
- JsonNode resolved = engine.resolveNode(node);
- if (!resolved.isArray()) {
- return result;
- }
- for (JsonNode item : resolved) {
- RuleCondition condition = new RuleCondition();
- condition.setField(textOrNull(item, "Field"));
- if (item.path("Values").isArray()) {
- condition.setValues(jsonArrayToStringList(item.path("Values")));
- }
- JsonNode pathCfg = item.path("PathPatternConfig");
- if (pathCfg.path("Values").isArray()) {
- condition.setPathPatternValues(jsonArrayToStringList(pathCfg.path("Values")));
- }
- JsonNode hostCfg = item.path("HostHeaderConfig");
- if (hostCfg.path("Values").isArray()) {
- condition.setHostHeaderValues(jsonArrayToStringList(hostCfg.path("Values")));
- }
- JsonNode httpHeaderCfg = item.path("HttpHeaderConfig");
- if (httpHeaderCfg.isObject()) {
- condition.setHttpHeaderName(textOrNull(httpHeaderCfg, "HttpHeaderName"));
- if (httpHeaderCfg.path("Values").isArray()) {
- condition.setHttpHeaderValues(jsonArrayToStringList(httpHeaderCfg.path("Values")));
- }
- }
- JsonNode methodCfg = item.path("HttpRequestMethodConfig");
- if (methodCfg.path("Values").isArray()) {
- condition.setHttpMethodValues(jsonArrayToStringList(methodCfg.path("Values")));
- }
- JsonNode sourceIpCfg = item.path("SourceIpConfig");
- if (sourceIpCfg.path("Values").isArray()) {
- condition.setSourceIpValues(jsonArrayToStringList(sourceIpCfg.path("Values")));
- }
- JsonNode queryCfg = item.path("QueryStringConfig");
- if (queryCfg.path("Values").isArray()) {
- List<RuleCondition.QueryStringPair> pairs = new ArrayList<>();
- for (JsonNode q : queryCfg.path("Values")) {
- RuleCondition.QueryStringPair pair = new RuleCondition.QueryStringPair();
- pair.setKey(textOrNull(q, "Key"));
- pair.setValue(textOrNull(q, "Value"));
- pairs.add(pair);
- }
- condition.setQueryStringValues(pairs);
- }
- result.add(condition);
- }
- return result;
- }
-
- private List<String> parseCertificates(JsonNode props, CloudFormationTemplateEngine engine) {
- List<String> result = new ArrayList<>();
- if (props == null || !props.has("Certificates") || props.get("Certificates").isNull()) {
- return result;
- }
- JsonNode resolved = engine.resolveNode(props.get("Certificates"));
- if (resolved.isArray()) {
- for (JsonNode c : resolved) {
- if (c.hasNonNull("CertificateArn")) {
- result.add(c.path("CertificateArn").asText());
- }
- }
- }
- return result;
- }
-
- private String parseMatcher(JsonNode props, CloudFormationTemplateEngine engine) {
- if (props == null || !props.has("Matcher") || props.get("Matcher").isNull()) {
- return null;
- }
- JsonNode m = engine.resolveNode(props.get("Matcher"));
- if (m.hasNonNull("HttpCode")) {
- return m.path("HttpCode").asText();
- }
- if (m.hasNonNull("GrpcCode")) {
- return m.path("GrpcCode").asText();
- }
- return null;
- }
-
- private String loadBalancerFullName(String lbArn) {
- // LB ARN resource: loadbalancer/<type>/<name>/<id> → full name drops the "loadbalancer/" prefix.
- String resource = AwsArnUtils.parse(lbArn).resource();
- String prefix = "loadbalancer/";
- return resource.startsWith(prefix) ? resource.substring(prefix.length()) : resource;
- }
-
- private String targetGroupFullName(String tgArn) {
- // TG full name keeps the "targetgroup/" prefix, e.g. targetgroup/<name>/<id>.
- return AwsArnUtils.parse(tgArn).resource();
- }
-
- private static String generateElbName(String stackName, String logicalId) {
- // ELBv2 names: ≤32 chars, [A-Za-z0-9-], no leading/trailing hyphen.
- String base = (stackName + "-" + logicalId).replaceAll("[^A-Za-z0-9-]", "");
- String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
- int maxBase = 32 - 1 - suffix.length();
- if (base.length() > maxBase) {
- base = base.substring(0, maxBase);
- }
- base = base.replaceAll("-+$", "");
- if (base.isEmpty()) {
- base = "elb";
- }
- return base + "-" + suffix;
- }
private static Integer parseIntOrNull(String value) {
if (value == null || value.isBlank()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java
new file mode 100644
index 0000000000..d7b1cde1b8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisioner.java
@@ -0,0 +1,511 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
+import io.github.hectorvent.floci.services.elbv2.model.Action;
+import io.github.hectorvent.floci.services.elbv2.model.Listener;
+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
+import io.github.hectorvent.floci.services.elbv2.model.Rule;
+import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
+import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * CloudFormation provisioning for the Elastic Load Balancing v2 types,
+ * {@code AWS::ElasticLoadBalancingV2::LoadBalancer}, {@code TargetGroup}, {@code Listener} and
+ * {@code ListenerRule}, moved out of the {@code CloudFormationResourceProvisioner} switch.
+ */
+@ApplicationScoped
+public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(ElbV2CfnProvisioner.class);
+
+ private static final String LOAD_BALANCER = "AWS::ElasticLoadBalancingV2::LoadBalancer";
+ private static final String TARGET_GROUP = "AWS::ElasticLoadBalancingV2::TargetGroup";
+ private static final String LISTENER = "AWS::ElasticLoadBalancingV2::Listener";
+ private static final String LISTENER_RULE = "AWS::ElasticLoadBalancingV2::ListenerRule";
+
+ private final ElbV2Service elbV2Service;
+
+ @Inject
+ public ElbV2CfnProvisioner(ElbV2Service elbV2Service) {
+ this.elbV2Service = elbV2Service;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(LOAD_BALANCER, TARGET_GROUP, LISTENER, LISTENER_RULE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
+ switch (r.getResourceType()) {
+ case LOAD_BALANCER -> provisionLoadBalancer(r, props, ctx);
+ case TARGET_GROUP -> provisionTargetGroup(r, props, ctx);
+ case LISTENER -> provisionListener(r, props, ctx);
+ case LISTENER_RULE -> provisionListenerRule(r, props, ctx);
+ default -> throw new IllegalStateException("ElbV2CfnProvisioner cannot handle " + r.getResourceType());
+ }
+ // A provision that left the resource with a new physical id replaced the entity: the
+ // displaced one is deleted once the update commits, or restored if the update rolls back.
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ /**
+ * Each delete tolerates only the not-found code ElbV2Service defines for that type, so an
+ * entity already gone is delete-complete, while the service's refusals (ResourceInUse on a
+ * target group a listener still forwards to, OperationNotPermitted on a listener's default
+ * rule) keep failing the stack delete.
+ */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ switch (resourceType) {
+ case LOAD_BALANCER -> CfnDeletes.safeDelete("load balancer", physicalId,
+ () -> elbV2Service.deleteLoadBalancer(region, physicalId), "LoadBalancerNotFound");
+ case TARGET_GROUP -> CfnDeletes.safeDelete("target group", physicalId,
+ () -> elbV2Service.deleteTargetGroup(region, physicalId), "TargetGroupNotFound");
+ case LISTENER -> CfnDeletes.safeDelete("listener", physicalId,
+ () -> elbV2Service.deleteListener(region, physicalId), "ListenerNotFound");
+ case LISTENER_RULE -> CfnDeletes.safeDelete("listener rule", physicalId,
+ () -> elbV2Service.deleteRule(region, physicalId), "RuleNotFound");
+ default -> { }
+ }
+ }
+
+ @Override
+ public boolean hasReplacementUpdate(StackResource resource) {
+ return ReplacementCleanup.hasReplacement(resource);
+ }
+
+ @Override
+ public String updateCleanupPhysicalId(StackResource resource) {
+ return ReplacementCleanup.cleanupPhysicalId(resource);
+ }
+
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ return ReplacementCleanup.complete(resource, this::delete);
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ ReplacementCleanup.clear(resource);
+ }
+
+ /**
+ * A replacement is undone through the cleanup record. Without one, a load balancer or target
+ * group has nothing to put back: this provisioner never modifies an existing one (an update that
+ * kept the name only described it, the way the switch did), so nothing changed. A listener or
+ * rule without a record was modified in place, and putting that back needs a snapshot this
+ * provisioner does not keep, so the engine reports it as not rolled back, as it did for the switch.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ if (ReplacementCleanup.rollback(resource, this::delete)) {
+ return true;
+ }
+ return LOAD_BALANCER.equals(resource.getResourceType()) || TARGET_GROUP.equals(resource.getResourceType());
+ }
+
+ /**
+ * The physical id is the ARN, so the name an unnamed load balancer got at create time is read
+ * back from the {@code LoadBalancerName} attribute before a new one is generated; the switch
+ * generated afresh on every pass and left the previous balancer behind. A name that already
+ * exists is reused, which is what makes an unchanged update a no-op. A changed name (create-only)
+ * creates the replacement and hands the displaced balancer to the replacement cleanup.
+ */
+ private void provisionLoadBalancer(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = nameOrPrior(ctx.resolveOptional(props, "Name"), r.getAttributes().get("LoadBalancerName"),
+ ctx, r.getLogicalId());
+ String scheme = ctx.resolveOptional(props, "Scheme");
+ String type = ctx.resolveOptional(props, "Type");
+ String ipAddressType = ctx.resolveOptional(props, "IpAddressType");
+ List<String> subnets = ctx.resolveStringList(props, "Subnets");
+ List<String> securityGroups = ctx.resolveStringList(props, "SecurityGroups");
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+
+ LoadBalancer lb;
+ try {
+ lb = elbV2Service.createLoadBalancer(ctx.region(), name, scheme, type, ipAddressType,
+ subnets, securityGroups, tags);
+ } catch (AwsException e) {
+ if (!"DuplicateLoadBalancerName".equals(e.getErrorCode())) {
+ throw e;
+ }
+ lb = elbV2Service.describeLoadBalancers(ctx.region(), null, List.of(name), null, null).get(0);
+ }
+
+ r.setPhysicalId(lb.getLoadBalancerArn());
+ r.getAttributes().put("LoadBalancerArn", lb.getLoadBalancerArn());
+ r.getAttributes().put("DNSName", lb.getDnsName());
+ r.getAttributes().put("CanonicalHostedZoneID", lb.getCanonicalHostedZoneId());
+ r.getAttributes().put("LoadBalancerName", lb.getLoadBalancerName());
+ r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));
+ }
+
+ private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String name = nameOrPrior(ctx.resolveOptional(props, "Name"), r.getAttributes().get("TargetGroupName"),
+ ctx, r.getLogicalId());
+ String protocol = ctx.resolveOptional(props, "Protocol");
+ String protocolVersion = ctx.resolveOptional(props, "ProtocolVersion");
+ Integer port = parseIntOrNull(ctx.resolveOptional(props, "Port"));
+ String vpcId = ctx.resolveOptional(props, "VpcId");
+ String targetType = ctx.resolveOptional(props, "TargetType");
+ String hcProtocol = ctx.resolveOptional(props, "HealthCheckProtocol");
+ String hcPort = ctx.resolveOptional(props, "HealthCheckPort");
+ Boolean hcEnabled = parseBooleanOrNull(ctx.resolveOptional(props, "HealthCheckEnabled"));
+ String hcPath = ctx.resolveOptional(props, "HealthCheckPath");
+ Integer hcInterval = parseIntOrNull(ctx.resolveOptional(props, "HealthCheckIntervalSeconds"));
+ Integer hcTimeout = parseIntOrNull(ctx.resolveOptional(props, "HealthCheckTimeoutSeconds"));
+ Integer healthyThreshold = parseIntOrNull(ctx.resolveOptional(props, "HealthyThresholdCount"));
+ Integer unhealthyThreshold = parseIntOrNull(ctx.resolveOptional(props, "UnhealthyThresholdCount"));
+ String matcher = parseMatcher(props, ctx);
+ String ipAddressType = ctx.resolveOptional(props, "IpAddressType");
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+
+ TargetGroup tg;
+ try {
+ tg = elbV2Service.createTargetGroup(ctx.region(), name, protocol, protocolVersion, port, vpcId, targetType,
+ hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
+ healthyThreshold, unhealthyThreshold, matcher, ipAddressType, tags);
+ } catch (AwsException e) {
+ if (!"DuplicateTargetGroupName".equals(e.getErrorCode())) {
+ throw e;
+ }
+ tg = elbV2Service.describeTargetGroups(ctx.region(), null, null, List.of(name)).get(0);
+ }
+
+ r.setPhysicalId(tg.getTargetGroupArn());
+ r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
+ r.getAttributes().put("TargetGroupName", tg.getTargetGroupName());
+ r.getAttributes().put("TargetGroupFullName", targetGroupFullName(tg.getTargetGroupArn()));
+ // A list-valued attribute, joined the way Route53's NameServers is. Empty until a listener
+ // forwards to the group, as on AWS.
+ r.getAttributes().put("LoadBalancerArns", String.join(",", tg.getLoadBalancerArns()));
+ }
+
+ /**
+ * LoadBalancerArn is create-only: an update that keeps it modifies the listener the stack
+ * already owns, one that moves the listener to another balancer creates a replacement and the
+ * displaced listener is deleted once the stack update commits.
+ */
+ private void provisionListener(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String lbArn = ctx.resolveOptional(props, "LoadBalancerArn");
+ String protocol = resolveOrDefault(props, "Protocol", ctx, "HTTP");
+ int port = parseInt(ctx.resolveOptional(props, "Port"), "Port", 80);
+ String sslPolicy = ctx.resolveOptional(props, "SslPolicy");
+ List<String> certificates = parseCertificates(props, ctx);
+ List<Action> defaultActions = parseActions(props != null ? props.get("DefaultActions") : null, ctx);
+
+ Listener listener;
+ Listener prior = ctx.isUpdate() ? priorListener(ctx) : null;
+ if (prior != null && (lbArn == null || lbArn.equals(prior.getLoadBalancerArn()))) {
+ listener = elbV2Service.modifyListener(ctx.region(), ctx.priorPhysicalId(), protocol, port, sslPolicy,
+ certificates, defaultActions, null);
+ } else {
+ listener = elbV2Service.createListener(ctx.region(), lbArn, protocol, port, sslPolicy, certificates,
+ defaultActions, null, Map.of());
+ }
+
+ r.setPhysicalId(listener.getListenerArn());
+ r.getAttributes().put("ListenerArn", listener.getListenerArn());
+ }
+
+ /**
+ * ListenerArn is create-only: an update that keeps it modifies the rule the stack already owns,
+ * one that moves the rule to another listener creates a replacement and the displaced rule is
+ * deleted once the stack update commits.
+ */
+ private void provisionListenerRule(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String listenerArn = ctx.resolveOptional(props, "ListenerArn");
+ int priority = parseInt(ctx.resolveOptional(props, "Priority"), "Priority", 1);
+ List<RuleCondition> conditions = parseRuleConditions(props != null ? props.get("Conditions") : null, ctx);
+ List<Action> actions = parseActions(props != null ? props.get("Actions") : null, ctx);
+
+ Rule rule;
+ Rule prior = ctx.isUpdate() ? priorRule(ctx) : null;
+ if (prior != null && (listenerArn == null || listenerArn.equals(prior.getListenerArn()))) {
+ rule = elbV2Service.modifyRule(ctx.region(), ctx.priorPhysicalId(), conditions, actions);
+ } else {
+ rule = elbV2Service.createRule(ctx.region(), listenerArn, conditions, priority, actions, Map.of());
+ }
+
+ r.setPhysicalId(rule.getRuleArn());
+ r.getAttributes().put("RuleArn", rule.getRuleArn());
+ r.getAttributes().put("IsDefault", String.valueOf(rule.isDefault()));
+ }
+
+ /** The listener the stack points at, or null when it was removed out of band (then create). */
+ private Listener priorListener(ProvisionContext ctx) {
+ try {
+ return elbV2Service.describeListeners(ctx.region(), null, List.of(ctx.priorPhysicalId()))
+ .stream().findFirst().orElse(null);
+ } catch (AwsException e) {
+ if (!"ListenerNotFound".equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("Listener {0} no longer exists, creating it again", ctx.priorPhysicalId());
+ return null;
+ }
+ }
+
+ private Rule priorRule(ProvisionContext ctx) {
+ try {
+ return elbV2Service.describeRules(ctx.region(), null, List.of(ctx.priorPhysicalId()))
+ .stream().findFirst().orElse(null);
+ } catch (AwsException e) {
+ if (!"RuleNotFound".equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("Rule {0} no longer exists, creating it again", ctx.priorPhysicalId());
+ return null;
+ }
+ }
+
+ private static String nameOrPrior(String declared, String prior, ProvisionContext ctx, String logicalId) {
+ if (declared != null && !declared.isBlank()) {
+ return declared;
+ }
+ if (prior != null && !prior.isBlank()) {
+ return prior;
+ }
+ return generateElbName(ctx.stackName(), logicalId);
+ }
+
+ /** ELBv2 names: at most 32 characters of {@code [A-Za-z0-9-]}, no leading or trailing hyphen. */
+ private static String generateElbName(String stackName, String logicalId) {
+ String base = (stackName + "-" + logicalId).replaceAll("[^A-Za-z0-9-]", "");
+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
+ int maxBase = 32 - 1 - suffix.length();
+ if (base.length() > maxBase) {
+ base = base.substring(0, maxBase);
+ }
+ base = base.replaceAll("-+$", "");
+ if (base.isEmpty()) {
+ base = "elb";
+ }
+ return base + "-" + suffix;
+ }
+
+ /** The ARN resource is {@code loadbalancer/<type>/<name>/<id>}; the full name drops the prefix. */
+ private static String loadBalancerFullName(String lbArn) {
+ String resource = AwsArnUtils.parse(lbArn).resource();
+ String prefix = "loadbalancer/";
+ return resource.startsWith(prefix) ? resource.substring(prefix.length()) : resource;
+ }
+
+ /** The target group full name keeps its prefix: {@code targetgroup/<name>/<id>}. */
+ private static String targetGroupFullName(String tgArn) {
+ return AwsArnUtils.parse(tgArn).resource();
+ }
+
+ private static String parseMatcher(JsonNode props, ProvisionContext ctx) {
+ if (props == null || !props.has("Matcher") || props.get("Matcher").isNull()) {
+ return null;
+ }
+ JsonNode m = ctx.engine().resolveNode(props.get("Matcher"));
+ if (m.hasNonNull("HttpCode")) {
+ return m.path("HttpCode").asText();
+ }
+ if (m.hasNonNull("GrpcCode")) {
+ return m.path("GrpcCode").asText();
+ }
+ return null;
+ }
+
+ private static List<String> parseCertificates(JsonNode props, ProvisionContext ctx) {
+ List<String> result = new ArrayList<>();
+ if (props == null || !props.has("Certificates") || props.get("Certificates").isNull()) {
+ return result;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props.get("Certificates"));
+ if (resolved.isArray()) {
+ for (JsonNode c : resolved) {
+ if (c.hasNonNull("CertificateArn")) {
+ result.add(c.path("CertificateArn").asText());
+ }
+ }
+ }
+ return result;
+ }
+
+ private static List<Action> parseActions(JsonNode node, ProvisionContext ctx) {
+ List<Action> result = new ArrayList<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(node);
+ if (!resolved.isArray()) {
+ return result;
+ }
+ for (JsonNode item : resolved) {
+ Action action = new Action();
+ action.setType(textOrNull(item, "Type"));
+ if (item.hasNonNull("Order")) {
+ action.setOrder(item.path("Order").asInt());
+ }
+ if (item.hasNonNull("TargetGroupArn")) {
+ action.setTargetGroupArn(item.path("TargetGroupArn").asText());
+ }
+ JsonNode forward = item.path("ForwardConfig");
+ if (forward.isObject()) {
+ JsonNode tgs = forward.path("TargetGroups");
+ if (tgs.isArray()) {
+ List<Action.TargetGroupTuple> tuples = new ArrayList<>();
+ for (JsonNode t : tgs) {
+ Action.TargetGroupTuple tuple = new Action.TargetGroupTuple();
+ if (t.hasNonNull("TargetGroupArn")) {
+ tuple.setTargetGroupArn(t.path("TargetGroupArn").asText());
+ }
+ if (t.hasNonNull("Weight")) {
+ tuple.setWeight(t.path("Weight").asInt());
+ }
+ tuples.add(tuple);
+ }
+ action.setTargetGroups(tuples);
+ }
+ JsonNode stickiness = forward.path("TargetGroupStickinessConfig");
+ if (stickiness.isObject()) {
+ if (stickiness.hasNonNull("Enabled")) {
+ action.setStickinessEnabled(stickiness.path("Enabled").asBoolean());
+ }
+ if (stickiness.hasNonNull("DurationSeconds")) {
+ action.setStickinessDurationSeconds(stickiness.path("DurationSeconds").asInt());
+ }
+ }
+ }
+ JsonNode redirect = item.path("RedirectConfig");
+ if (redirect.isObject()) {
+ action.setRedirectProtocol(textOrNull(redirect, "Protocol"));
+ action.setRedirectPort(textOrNull(redirect, "Port"));
+ action.setRedirectHost(textOrNull(redirect, "Host"));
+ action.setRedirectPath(textOrNull(redirect, "Path"));
+ action.setRedirectQuery(textOrNull(redirect, "Query"));
+ action.setRedirectStatusCode(textOrNull(redirect, "StatusCode"));
+ }
+ JsonNode fixed = item.path("FixedResponseConfig");
+ if (fixed.isObject()) {
+ action.setFixedResponseStatusCode(textOrNull(fixed, "StatusCode"));
+ action.setFixedResponseContentType(textOrNull(fixed, "ContentType"));
+ action.setFixedResponseMessageBody(textOrNull(fixed, "MessageBody"));
+ }
+ result.add(action);
+ }
+ return result;
+ }
+
+ private static List<RuleCondition> parseRuleConditions(JsonNode node, ProvisionContext ctx) {
+ List<RuleCondition> result = new ArrayList<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ JsonNode resolved = ctx.engine().resolveNode(node);
+ if (!resolved.isArray()) {
+ return result;
+ }
+ for (JsonNode item : resolved) {
+ RuleCondition condition = new RuleCondition();
+ condition.setField(textOrNull(item, "Field"));
+ if (item.path("Values").isArray()) {
+ condition.setValues(toStringList(item.path("Values")));
+ }
+ JsonNode pathCfg = item.path("PathPatternConfig");
+ if (pathCfg.path("Values").isArray()) {
+ condition.setPathPatternValues(toStringList(pathCfg.path("Values")));
+ }
+ JsonNode hostCfg = item.path("HostHeaderConfig");
+ if (hostCfg.path("Values").isArray()) {
+ condition.setHostHeaderValues(toStringList(hostCfg.path("Values")));
+ }
+ JsonNode httpHeaderCfg = item.path("HttpHeaderConfig");
+ if (httpHeaderCfg.isObject()) {
+ condition.setHttpHeaderName(textOrNull(httpHeaderCfg, "HttpHeaderName"));
+ if (httpHeaderCfg.path("Values").isArray()) {
+ condition.setHttpHeaderValues(toStringList(httpHeaderCfg.path("Values")));
+ }
+ }
+ JsonNode methodCfg = item.path("HttpRequestMethodConfig");
+ if (methodCfg.path("Values").isArray()) {
+ condition.setHttpMethodValues(toStringList(methodCfg.path("Values")));
+ }
+ JsonNode sourceIpCfg = item.path("SourceIpConfig");
+ if (sourceIpCfg.path("Values").isArray()) {
+ condition.setSourceIpValues(toStringList(sourceIpCfg.path("Values")));
+ }
+ JsonNode queryCfg = item.path("QueryStringConfig");
+ if (queryCfg.path("Values").isArray()) {
+ List<RuleCondition.QueryStringPair> pairs = new ArrayList<>();
+ for (JsonNode q : queryCfg.path("Values")) {
+ RuleCondition.QueryStringPair pair = new RuleCondition.QueryStringPair();
+ pair.setKey(textOrNull(q, "Key"));
+ pair.setValue(textOrNull(q, "Value"));
+ pairs.add(pair);
+ }
+ condition.setQueryStringValues(pairs);
+ }
+ result.add(condition);
+ }
+ return result;
+ }
+
+ private static String resolveOrDefault(JsonNode props, String name, ProvisionContext ctx, String fallback) {
+ String value = ctx.resolveOptional(props, name);
+ return value != null && !value.isBlank() ? value : fallback;
+ }
+
+ /** An absent value takes the default; anything present has to be an integer. */
+ private static int parseInt(String value, String property, int fallback) {
+ if (value == null || value.isBlank()) {
+ return fallback;
+ }
+ try {
+ return Integer.parseInt(value.trim());
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError", "Value of property " + property + " must be an integer.", 400);
+ }
+ }
+
+ /** The switch treated an unparsable optional integer as unset; kept so a stray value does not fail a stack. */
+ private static Integer parseIntOrNull(String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ try {
+ return Integer.valueOf(value.trim());
+ } catch (NumberFormatException e) {
+ LOG.debugv("Ignoring non-integer value {0}", value);
+ return null;
+ }
+ }
+
+ private static Boolean parseBooleanOrNull(String value) {
+ return value == null || value.isBlank() ? null : Boolean.valueOf(value);
+ }
+
+ private static String textOrNull(JsonNode node, String field) {
+ return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
+ }
+
+ private static List<String> toStringList(JsonNode node) {
+ List<String> result = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(v -> result.add(v.asText()));
+ }
+ return result;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java
index 21f24df487..8b1258c529 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ReplacementCleanup.java
@@ -107,9 +107,9 @@ final class ReplacementCleanup {
return true;
}
try {
- deleter.delete(r.getResourceType(), replacement, region(cleanup, r));
+ deleter.delete(r.getResourceType(), replacement, region(cleanup));
} catch (RuntimeException deleteFailure) {
- addDisplaced(cleanup, replacement, r.getResourceType(), region(cleanup, r), false);
+ addDisplaced(cleanup, replacement, r.getResourceType(), region(cleanup), false);
write(r, cleanup);
throw deleteFailure;
}
@@ -122,22 +122,38 @@ final class ReplacementCleanup {
}
/**
- * The first entity still owed a delete, or null when none is or {@code UpdateReplacePolicy:
- * Retain} keeps it. The engine announces one physical id per resource, so a resource owing
- * more than one names the first; the rest are deleted in the same cleanup.
+ * The entity the cleanup is working on, or null when none is owed or {@code UpdateReplacePolicy:
+ * Retain} keeps it. The engine announces one physical id per resource, so a resource owing more
+ * than one names the one with the fewest attempts, the same entity {@link #complete} reports,
+ * so the progress and failure events of one cleanup name the same thing.
*/
static String cleanupPhysicalId(StackResource r) {
ObjectNode cleanup = read(r);
if (cleanup == null) {
return null;
}
- boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
- for (JsonNode entry : cleanup.path("displaced")) {
- if (!(retain && entry.path("retainable").asBoolean(false))) {
- return entry.path("physicalId").asText(null);
+ JsonNode next = nextOwed(cleanup.path("displaced"), r.getPhysicalId(), "Retain".equals(r.getUpdateReplacePolicy()));
+ return next == null ? null : next.path("physicalId").asText(null);
+ }
+
+ /**
+ * The owed entry with the fewest attempts, ties by list order: the one the engine's retries are
+ * still for. Skips the resource's own entity and, under Retain, the entities a committed
+ * replacement displaced.
+ */
+ private static JsonNode nextOwed(JsonNode displaced, String currentPhysicalId, boolean retain) {
+ JsonNode next = null;
+ for (JsonNode entry : displaced) {
+ String physicalId = entry.path("physicalId").asText(null);
+ if (physicalId == null || physicalId.equals(currentPhysicalId)
+ || (retain && entry.path("retainable").asBoolean(false))) {
+ continue;
+ }
+ if (next == null || entry.path("cleanupAttempts").asInt(0) < next.path("cleanupAttempts").asInt(0)) {
+ next = entry;
}
}
- return null;
+ return next;
}
/**
@@ -186,9 +202,6 @@ final class ReplacementCleanup {
boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
ArrayNode displaced = cleanup.withArray("displaced");
ArrayNode remaining = MAPPER.createArrayNode();
- int attempts = Integer.MAX_VALUE;
- String failureReason = null;
- String firstRemaining = null;
for (JsonNode node : displaced) {
ObjectNode entry = (ObjectNode) node;
String physicalId = entry.path("physicalId").asText(null);
@@ -209,20 +222,17 @@ final class ReplacementCleanup {
}
}
remaining.add(entry);
- // The result names the entity with the fewest attempts, the one the engine's retries
- // are still for, so its DELETE_FAILED event points at what is actually still owed.
- if (entryAttempts < attempts) {
- attempts = entryAttempts;
- failureReason = entry.path("cleanupFailureReason").asText(null);
- firstRemaining = physicalId;
- }
}
cleanup.set("displaced", remaining);
write(r, cleanup);
if (remaining.isEmpty()) {
return new UpdateCleanupResult(true, true, firstDisplaced(displaced), 0, null);
}
- return new UpdateCleanupResult(true, false, firstRemaining, attempts, failureReason);
+ // The result names the entity with the fewest attempts, the one the engine's retries are
+ // still for and the one cleanupPhysicalId announced, so both events point at the same thing.
+ JsonNode next = nextOwed(remaining, r.getPhysicalId(), retain);
+ return new UpdateCleanupResult(true, false, next.path("physicalId").asText(null),
+ next.path("cleanupAttempts").asInt(0), next.path("cleanupFailureReason").asText(null));
}
private static String firstDisplaced(ArrayNode displaced) {
@@ -257,7 +267,7 @@ final class ReplacementCleanup {
kept.forEach(displaced::add);
}
- private static String region(ObjectNode cleanup, StackResource r) {
+ private static String region(ObjectNode cleanup) {
return cleanup.path("region").asText(null);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 6dc6b26153..fdbc9c7001 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -42,6 +42,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2VpcGat
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcrCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapacityCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.ElbV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner;
@@ -242,6 +243,9 @@ final class CfnProvisionerFixture {
discovered.add(new IamRoleCfnProvisioner(iamService));
discovered.add(new IamUserCfnProvisioner(iamService));
}
+ if (elbV2Service != null) {
+ discovered.add(new ElbV2CfnProvisioner(elbV2Service));
+ }
if (ecsService != null) {
discovered.add(new EcsCapacityCfnProvisioner(ecsService));
discovered.add(new EcsCfnProvisioner(ecsService));
@@ -580,7 +584,6 @@ final class CfnProvisionerFixture {
objectMapper,
customResourceResponseStore,
reachableEndpoint,
- elbV2Service,
stepFunctionsService,
batchService,
ec2Service,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.java
new file mode 100644
index 0000000000..0a2737ae5f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2ReplacementIntegrationTest.java
@@ -0,0 +1,291 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+/**
+ * Replacing updates of ELBv2 resources through the whole engine: the displaced listener and target
+ * group are deleted after the update commits, dependents first, and a replacement is rolled back
+ * when a later resource fails the update.
+ */
+@QuarkusTest
+class CloudFormationElbV2ReplacementIntegrationTest {
+
+ private static final String REGION = "us-east-1";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ /**
+ * One update renames the target group and moves the listener to the second load balancer. The
+ * old listener still forwards to the old target group, so the group can only go once the
+ * listener is gone: the cleanup walks dependents first, and both displaced entities end up
+ * deleted with DELETE_COMPLETE events on their prior ARNs.
+ */
+ @Test
+ void aRenamedTargetGroupAndAMovedListenerAreBothCleanedUpAfterTheUpdateCommits() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "elb-replace-" + suffix;
+
+ createStack(stackName, template(suffix, "AlbA", "tg-a-" + suffix, ""));
+ String describeBefore = describeStack(stackName);
+ String oldListener = output(describeBefore, "ListenerRef");
+ String oldTg = output(describeBefore, "TgRef");
+
+ updateStack(stackName, template(suffix, "AlbB", "tg-b-" + suffix, ""));
+ String describeAfter = describeStack(stackName);
+ assertStatus(describeAfter, "UPDATE_COMPLETE");
+ String newListener = output(describeAfter, "ListenerRef");
+ String newTg = output(describeAfter, "TgRef");
+ assertNotEquals(oldListener, newListener);
+ assertNotEquals(oldTg, newTg);
+
+ assertListenerMissing(oldListener);
+ assertTargetGroupMissing(oldTg);
+ assertListenerPresent(newListener);
+
+ String events = describeEvents(stackName);
+ assertEvent(events, "DELETE_COMPLETE", oldListener);
+ assertEvent(events, "DELETE_COMPLETE", oldTg);
+
+ deleteStack(stackName);
+ }
+
+ /**
+ * The listener is moved, then a later resource fails, so the update rolls back: the listener
+ * resource names the prior listener again and the replacement is gone.
+ */
+ @Test
+ void aFailedUpdateRollsAMovedListenerBackAndDeletesTheReplacement() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "elb-rollback-" + suffix;
+
+ createStack(stackName, template(suffix, "AlbA", "tg-" + suffix, ""));
+ String oldListener = output(describeStack(stackName), "ListenerRef");
+
+ String failingSecret = """
+ ,
+ "BadSecret": {
+ "Type": "AWS::SecretsManager::Secret",
+ "DependsOn": "Listener",
+ "Properties": {
+ "Name": "elb-rollback-secret-%s",
+ "SecretString": "explicit",
+ "GenerateSecretString": {"PasswordLength": 32}
+ }
+ }""".formatted(suffix);
+ updateStack(stackName, template(suffix, "AlbB", "tg-" + suffix, failingSecret));
+
+ String describe = describeStack(stackName);
+ assertStatus(describe, "UPDATE_ROLLBACK_COMPLETE");
+ assertEquals(oldListener, output(describe, "ListenerRef"));
+ assertListenerPresent(oldListener);
+
+ String listeners = given()
+ .formParam("Action", "DescribeListeners")
+ .formParam("Version", "2015-12-01")
+ .formParam("LoadBalancerArn", output(describe, "AlbBRef"))
+ .when().post("/")
+ .then().statusCode(200).extract().asString();
+ assertEquals(false, listeners.contains("<ListenerArn>"),
+ "the replacement listener on the second balancer is gone: " + listeners);
+
+ deleteStack(stackName);
+ }
+
+ /**
+ * The target group arrives in a later update than the listener, so it sits after the listener
+ * in the stack's resource map while the listener depends on it. Cleanup has to follow the
+ * template's dependency order, not the map's: reversing the map would delete the old target
+ * group first, while the old listener still forwards to it.
+ */
+ @Test
+ void aDependencyAddedByALaterUpdateIsStillCleanedUpAfterItsDependent() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "elb-appended-" + suffix;
+
+ createStack(stackName, fixedResponseTemplate(suffix));
+ updateStack(stackName, template(suffix, "AlbA", "tg-a-" + suffix, ""));
+ String describeBefore = describeStack(stackName);
+ assertStatus(describeBefore, "UPDATE_COMPLETE");
+ String oldListener = output(describeBefore, "ListenerRef");
+ String oldTg = output(describeBefore, "TgRef");
+
+ updateStack(stackName, template(suffix, "AlbB", "tg-b-" + suffix, ""));
+ String describeAfter = describeStack(stackName);
+ assertStatus(describeAfter, "UPDATE_COMPLETE");
+ assertNotEquals(oldListener, output(describeAfter, "ListenerRef"));
+ assertNotEquals(oldTg, output(describeAfter, "TgRef"));
+
+ assertListenerMissing(oldListener);
+ assertTargetGroupMissing(oldTg);
+ String events = describeEvents(stackName);
+ assertEvent(events, "DELETE_COMPLETE", oldListener);
+ assertEvent(events, "DELETE_COMPLETE", oldTg);
+
+ deleteStack(stackName);
+ }
+
+ /** The same two balancers with a listener that needs no target group. */
+ private static String fixedResponseTemplate(String suffix) {
+ return """
+ {
+ "Resources": {
+ "AlbA": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Name": "alb-a-%1$s", "Type": "application", "Subnets": ["%2$s", "%3$s"]}
+ },
+ "AlbB": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Name": "alb-b-%1$s", "Type": "application", "Subnets": ["%2$s", "%3$s"]}
+ },
+ "Listener": {
+ "Type": "AWS::ElasticLoadBalancingV2::Listener",
+ "Properties": {
+ "LoadBalancerArn": {"Ref": "AlbA"},
+ "Protocol": "HTTP",
+ "Port": 80,
+ "DefaultActions": [{"Type": "fixed-response", "FixedResponseConfig": {"StatusCode": "404"}}]
+ }
+ }
+ },
+ "Outputs": {
+ "AlbARef": {"Value": {"Ref": "AlbA"}},
+ "AlbBRef": {"Value": {"Ref": "AlbB"}},
+ "ListenerRef": {"Value": {"Ref": "Listener"}}
+ }
+ }
+ """.formatted(suffix, Ec2Service.defaultSubnetId(REGION, "a"), Ec2Service.defaultSubnetId(REGION, "b"));
+ }
+
+ private static String template(String suffix, String listenerLb, String tgName, String extraResources) {
+ return """
+ {
+ "Resources": {
+ "AlbA": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Name": "alb-a-%1$s", "Type": "application", "Subnets": ["%2$s", "%3$s"]}
+ },
+ "AlbB": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {"Name": "alb-b-%1$s", "Type": "application", "Subnets": ["%2$s", "%3$s"]}
+ },
+ "Tg": {
+ "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "Properties": {"Name": "%4$s", "Protocol": "HTTP", "Port": 80, "VpcId": "%5$s", "TargetType": "ip"}
+ },
+ "Listener": {
+ "Type": "AWS::ElasticLoadBalancingV2::Listener",
+ "Properties": {
+ "LoadBalancerArn": {"Ref": "%6$s"},
+ "Protocol": "HTTP",
+ "Port": 80,
+ "DefaultActions": [{"Type": "forward", "TargetGroupArn": {"Ref": "Tg"}}]
+ }
+ }%7$s
+ },
+ "Outputs": {
+ "AlbARef": {"Value": {"Ref": "AlbA"}},
+ "AlbBRef": {"Value": {"Ref": "AlbB"}},
+ "TgRef": {"Value": {"Ref": "Tg"}},
+ "ListenerRef": {"Value": {"Ref": "Listener"}}
+ }
+ }
+ """.formatted(suffix, Ec2Service.defaultSubnetId(REGION, "a"), Ec2Service.defaultSubnetId(REGION, "b"),
+ tgName, Ec2Service.defaultVpcId(REGION), listenerLb, extraResources);
+ }
+
+ private static void createStack(String stackName, String body) {
+ given().formParam("Action", "CreateStack").formParam("Version", "2010-05-15")
+ .formParam("StackName", stackName).formParam("TemplateBody", body)
+ .when().post("/").then().statusCode(200);
+ assertStatus(describeStack(stackName), "CREATE_COMPLETE");
+ }
+
+ private static void updateStack(String stackName, String body) {
+ given().formParam("Action", "UpdateStack").formParam("Version", "2010-05-15")
+ .formParam("StackName", stackName).formParam("TemplateBody", body)
+ .when().post("/").then().statusCode(200);
+ }
+
+ private static void deleteStack(String stackName) {
+ given().formParam("Action", "DeleteStack").formParam("Version", "2010-05-15")
+ .formParam("StackName", stackName)
+ .when().post("/").then().statusCode(200);
+ }
+
+ private static String describeStack(String stackName) {
+ return given().formParam("Action", "DescribeStacks").formParam("Version", "2010-05-15")
+ .formParam("StackName", stackName)
+ .when().post("/").then().statusCode(200).extract().asString();
+ }
+
+ private static String describeEvents(String stackName) {
+ return given().formParam("Action", "DescribeStackEvents").formParam("Version", "2010-05-15")
+ .formParam("StackName", stackName)
+ .when().post("/").then().statusCode(200).extract().asString();
+ }
+
+ private static void assertStatus(String describeXml, String status) {
+ assertEquals(true, describeXml.contains("<StackStatus>" + status + "</StackStatus>"),
+ "expected " + status + " in " + describeXml);
+ }
+
+ private static void assertEvent(String eventsXml, String status, String physicalId) {
+ Pattern p = Pattern.compile("<member>(.*?)</member>", Pattern.DOTALL);
+ Matcher m = p.matcher(eventsXml);
+ while (m.find()) {
+ String member = m.group(1);
+ if (member.contains("<ResourceStatus>" + status + "</ResourceStatus>")
+ && member.contains("<PhysicalResourceId>" + physicalId + "</PhysicalResourceId>")) {
+ return;
+ }
+ }
+ throw new AssertionError("no " + status + " event for " + physicalId + " in " + eventsXml);
+ }
+
+ private static String output(String describeXml, String key) {
+ Matcher m = Pattern.compile("<OutputKey>" + key + "</OutputKey>\\s*<OutputValue>(.*?)</OutputValue>", Pattern.DOTALL)
+ .matcher(describeXml);
+ if (!m.find()) {
+ m = Pattern.compile("<OutputValue>(.*?)</OutputValue>\\s*<OutputKey>" + key + "</OutputKey>", Pattern.DOTALL)
+ .matcher(describeXml);
+ assertNotNull(m.find() ? m : null, "output " + key + " missing in " + describeXml);
+ }
+ return m.group(1);
+ }
+
+ /** DescribeListeners filters by ARN and answers an empty list for one that is gone. */
+ private static void assertListenerMissing(String listenerArn) {
+ given().formParam("Action", "DescribeListeners").formParam("Version", "2015-12-01")
+ .formParam("ListenerArns.member.1", listenerArn)
+ .when().post("/").then().statusCode(200).body(not(containsString(listenerArn)));
+ }
+
+ private static void assertListenerPresent(String listenerArn) {
+ given().formParam("Action", "DescribeListeners").formParam("Version", "2015-12-01")
+ .formParam("ListenerArns.member.1", listenerArn)
+ .when().post("/").then().statusCode(200).body(containsString(listenerArn));
+ }
+
+ private static void assertTargetGroupMissing(String tgArn) {
+ given().formParam("Action", "DescribeTargetGroups").formParam("Version", "2015-12-01")
+ .formParam("TargetGroupArns.member.1", tgArn)
+ .when().post("/").then().statusCode(400).body(containsString("TargetGroupNotFound")).body(not(containsString("<TargetGroupArn>" + tgArn)));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java
new file mode 100644
index 0000000000..b3d8578190
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java
@@ -0,0 +1,631 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
+import io.github.hectorvent.floci.services.elbv2.model.Action;
+import io.github.hectorvent.floci.services.elbv2.model.Listener;
+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
+import io.github.hectorvent.floci.services.elbv2.model.Rule;
+import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
+import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InOrder;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The ELBv2 CFN provisioner in isolation: one mocked service, no Quarkus boot.
+ * {@code CloudFormationIntegrationTest} covers the four types end to end.
+ */
+class ElbV2CfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String LB_ARN =
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/web/50dc6c495c0c9188";
+ private static final String TG_ARN =
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web-tg/73e2d6bc24d8a067";
+ private static final String LISTENER_ARN =
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/web/50dc6c495c0c9188/f2f7dc8efc522ab2";
+ private static final String RULE_ARN = LISTENER_ARN.replace(":listener/", ":listener-rule/") + "/9683b2d02a6cabee";
+
+ private final ElbV2Service elb = mock(ElbV2Service.class);
+ private final ElbV2CfnProvisioner provisioner = new ElbV2CfnProvisioner(elb);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(null);
+ }
+
+ private ProvisionContext ctx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ // resolveStringList delegates to the real engine method; for the literal arrays these
+ // tests use it just walks the array and calls resolve(...) per element, stubbed above.
+ when(engine.resolveStringList(any())).thenCallRealMethod();
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private StackResource resource(String type, String logicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private LoadBalancer loadBalancer(String name) {
+ LoadBalancer lb = new LoadBalancer();
+ lb.setLoadBalancerName(name);
+ lb.setLoadBalancerArn(LB_ARN);
+ lb.setDnsName(name + "-123.us-east-1.elb.amazonaws.com");
+ lb.setCanonicalHostedZoneId("Z35SXDOTRQ7X7K");
+ return lb;
+ }
+
+ private TargetGroup targetGroup(String name) {
+ TargetGroup tg = new TargetGroup();
+ tg.setTargetGroupName(name);
+ tg.setTargetGroupArn(TG_ARN);
+ return tg;
+ }
+
+ private Listener listener(String lbArn) {
+ Listener l = new Listener();
+ // A listener under another balancer is a different listener with its own ARN.
+ l.setListenerArn(lbArn.equals(LB_ARN) ? LISTENER_ARN : LISTENER_ARN.replace("/web/", "/other/"));
+ l.setLoadBalancerArn(lbArn);
+ return l;
+ }
+
+ private Rule rule(String listenerArn) {
+ Rule rule = new Rule();
+ rule.setRuleArn(listenerArn.equals(LISTENER_ARN) ? RULE_ARN : RULE_ARN.replace("/web/", "/other/"));
+ rule.setListenerArn(listenerArn);
+ rule.setDefault(false);
+ return rule;
+ }
+
+ @Test
+ void declaresTheFourTypes() {
+ assertEquals(Set.of("AWS::ElasticLoadBalancingV2::LoadBalancer", "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "AWS::ElasticLoadBalancingV2::Listener", "AWS::ElasticLoadBalancingV2::ListenerRule"),
+ provisioner.resourceTypes());
+ }
+
+ @Test
+ void loadBalancerExposesExactlyTheSchemaAttributes() {
+ when(elb.createLoadBalancer(eq(REGION), eq("web"), eq("internet-facing"), eq("application"), isNull(),
+ eq(List.of("subnet-1", "subnet-2")), eq(List.of("sg-1")), eq(Map.of("env", "test"))))
+ .thenReturn(loadBalancer("web"));
+ ObjectNode props = mapper.createObjectNode().put("Name", "web").put("Scheme", "internet-facing")
+ .put("Type", "application");
+ props.putArray("Subnets").add("subnet-1").add("subnet-2");
+ props.putArray("SecurityGroups").add("sg-1");
+ props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(LB_ARN, r.getPhysicalId());
+ assertEquals(Set.of("LoadBalancerArn", "DNSName", "CanonicalHostedZoneID", "LoadBalancerName",
+ "LoadBalancerFullName"), r.getAttributes().keySet());
+ assertEquals("app/web/50dc6c495c0c9188", r.getAttributes().get("LoadBalancerFullName"));
+ assertEquals("web", r.getAttributes().get("LoadBalancerName"));
+ assertEquals("Z35SXDOTRQ7X7K", r.getAttributes().get("CanonicalHostedZoneID"));
+ }
+
+ @Test
+ void anUnnamedLoadBalancerGetsAnElbSafeNameAndKeepsItOnUpdate() {
+ when(elb.createLoadBalancer(eq(REGION), anyString(), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenAnswer(inv -> loadBalancer(inv.getArgument(1)));
+ StackResource created = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb_With_Underscores");
+ provisioner.provision(created, mapper.createObjectNode(), ctx());
+ String generated = created.getAttributes().get("LoadBalancerName");
+ // 32 characters at most, [A-Za-z0-9-] only, so the underscores are stripped and the
+ // descriptive part is cut to make room for the 8-character suffix.
+ assertTrue(generated.matches("[A-Za-z0-9-]{1,32}"), generated);
+ assertTrue(generated.startsWith("my-stack-AlbWithUndersc-"), generated);
+
+ StackResource updated = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb_With_Underscores");
+ updated.getAttributes().put("LoadBalancerName", generated);
+ provisioner.provision(updated, mapper.createObjectNode(), ctx(LB_ARN));
+
+ verify(elb, org.mockito.Mockito.times(2)).createLoadBalancer(eq(REGION), eq(generated), isNull(), isNull(),
+ isNull(), anyList(), anyList(), any());
+ }
+
+ @Test
+ void aDuplicateLoadBalancerNameIsReusedNotFailed() {
+ when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
+ when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null)).thenReturn(List.of(loadBalancer("web")));
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web"), ctx(LB_ARN));
+
+ assertEquals(LB_ARN, r.getPhysicalId());
+ }
+
+ @Test
+ void targetGroupParsesHealthCheckAndMatcherAndExposesLoadBalancerArns() {
+ TargetGroup tg = targetGroup("web-tg");
+ tg.setLoadBalancerArns(List.of(LB_ARN));
+ when(elb.createTargetGroup(eq(REGION), eq("web-tg"), eq("HTTP"), eq("HTTP1"), eq(8080), eq("vpc-1"), eq("ip"),
+ eq("HTTP"), eq("traffic-port"), eq(true), eq("/health"), eq(15), eq(5), eq(2), eq(3), eq("200-299"),
+ isNull(), eq(Map.of()))).thenReturn(tg);
+ ObjectNode props = mapper.createObjectNode().put("Name", "web-tg").put("Protocol", "HTTP")
+ .put("ProtocolVersion", "HTTP1").put("Port", "8080").put("VpcId", "vpc-1").put("TargetType", "ip")
+ .put("HealthCheckProtocol", "HTTP").put("HealthCheckPort", "traffic-port").put("HealthCheckEnabled", "true")
+ .put("HealthCheckPath", "/health").put("HealthCheckIntervalSeconds", "15")
+ .put("HealthCheckTimeoutSeconds", "5").put("HealthyThresholdCount", "2").put("UnhealthyThresholdCount", "3");
+ props.putObject("Matcher").put("HttpCode", "200-299");
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::TargetGroup", "Tg");
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(TG_ARN, r.getPhysicalId());
+ assertEquals(Set.of("TargetGroupArn", "TargetGroupName", "TargetGroupFullName", "LoadBalancerArns"),
+ r.getAttributes().keySet());
+ assertEquals("targetgroup/web-tg/73e2d6bc24d8a067", r.getAttributes().get("TargetGroupFullName"));
+ assertEquals(LB_ARN, r.getAttributes().get("LoadBalancerArns"));
+ }
+
+ @Test
+ void listenerDefaultsToHttp80AndParsesCertificatesAndForwardAction() {
+ when(elb.createListener(eq(REGION), eq(LB_ARN), eq("HTTP"), eq(80), isNull(), eq(List.of("arn:aws:acm:cert")),
+ anyList(), isNull(), eq(Map.of()))).thenReturn(listener(LB_ARN));
+ ObjectNode props = mapper.createObjectNode().put("LoadBalancerArn", LB_ARN);
+ props.putArray("Certificates").addObject().put("CertificateArn", "arn:aws:acm:cert");
+ ObjectNode action = props.putArray("DefaultActions").addObject().put("Type", "forward").put("Order", 1);
+ action.putObject("ForwardConfig").putArray("TargetGroups").addObject().put("TargetGroupArn", TG_ARN).put("Weight", 7);
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(LISTENER_ARN, r.getPhysicalId());
+ assertEquals(Set.of("ListenerArn"), r.getAttributes().keySet());
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<Action>> actions = ArgumentCaptor.forClass(List.class);
+ verify(elb).createListener(eq(REGION), eq(LB_ARN), eq("HTTP"), eq(80), isNull(), anyList(), actions.capture(),
+ isNull(), eq(Map.of()));
+ Action parsed = actions.getValue().get(0);
+ assertEquals("forward", parsed.getType());
+ assertEquals(TG_ARN, parsed.getTargetGroups().get(0).getTargetGroupArn());
+ assertEquals(7, parsed.getTargetGroups().get(0).getWeight());
+ }
+
+ @Test
+ void anUnchangedListenerIsModifiedInPlace() {
+ when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));
+ when(elb.modifyListener(eq(REGION), eq(LISTENER_ARN), eq("HTTPS"), eq(443), eq("ELBSecurityPolicy-2016-08"),
+ anyList(), anyList(), isNull())).thenReturn(listener(LB_ARN));
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ provisioner.provision(r, mapper.createObjectNode().put("LoadBalancerArn", LB_ARN).put("Protocol", "HTTPS")
+ .put("Port", "443").put("SslPolicy", "ELBSecurityPolicy-2016-08"), ctx(LISTENER_ARN));
+
+ assertEquals(LISTENER_ARN, r.getPhysicalId());
+ verify(elb, never()).createListener(anyString(), anyString(), anyString(), anyInt(), any(), anyList(), anyList(),
+ any(), any());
+ }
+
+ @Test
+ void aListenerMovedToAnotherLoadBalancerIsCreatedAsAReplacement() {
+ String otherLb = LB_ARN.replace("/web/", "/other/");
+ when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));
+ when(elb.createListener(eq(REGION), eq(otherLb), eq("HTTP"), eq(80), isNull(), anyList(), anyList(), isNull(),
+ eq(Map.of()))).thenReturn(listener(otherLb));
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ provisioner.provision(r, mapper.createObjectNode().put("LoadBalancerArn", otherLb), ctx(LISTENER_ARN));
+
+ verify(elb, never()).modifyListener(anyString(), anyString(), anyString(), anyInt(), any(), anyList(), anyList(),
+ any());
+ // The displaced listener outlives provision and is deleted by the committed-update cleanup.
+ verify(elb, never()).deleteListener(anyString(), anyString());
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(LISTENER_ARN, provisioner.updateCleanupPhysicalId(r));
+
+ UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
+
+ InOrder order = inOrder(elb);
+ order.verify(elb).createListener(eq(REGION), eq(otherLb), eq("HTTP"), eq(80), isNull(), anyList(), anyList(),
+ isNull(), eq(Map.of()));
+ order.verify(elb).deleteListener(REGION, LISTENER_ARN);
+ assertEquals(new UpdateCleanupResult(true, true, LISTENER_ARN, 0, null), cleanup);
+ provisioner.clearUpdate(r);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void aListenerRemovedOutOfBandIsCreatedAgain() {
+ when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN)))
+ .thenThrow(new AwsException("ListenerNotFound", "gone", 400));
+ when(elb.createListener(eq(REGION), eq(LB_ARN), eq("HTTP"), eq(80), isNull(), anyList(), anyList(), isNull(),
+ eq(Map.of()))).thenReturn(listener(LB_ARN));
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ provisioner.provision(r, mapper.createObjectNode().put("LoadBalancerArn", LB_ARN), ctx(LISTENER_ARN));
+
+ assertEquals(LISTENER_ARN, r.getPhysicalId());
+ }
+
+ @Test
+ void ruleParsesConditionsAndExposesRuleArnAndIsDefault() {
+ when(elb.createRule(eq(REGION), eq(LISTENER_ARN), anyList(), eq(10), anyList(), eq(Map.of())))
+ .thenReturn(rule(LISTENER_ARN));
+ ObjectNode props = mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "10");
+ var conditions = props.putArray("Conditions");
+ conditions.addObject().put("Field", "path-pattern").putObject("PathPatternConfig").putArray("Values").add("/api/*");
+ ObjectNode header = conditions.addObject().put("Field", "http-header");
+ header.putObject("HttpHeaderConfig").put("HttpHeaderName", "X-Env").putArray("Values").add("prod");
+ conditions.addObject().put("Field", "query-string").putObject("QueryStringConfig").putArray("Values")
+ .addObject().put("Key", "v").put("Value", "2");
+ props.putArray("Actions").addObject().put("Type", "forward").put("TargetGroupArn", TG_ARN);
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule");
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(RULE_ARN, r.getPhysicalId());
+ assertEquals(Set.of("RuleArn", "IsDefault"), r.getAttributes().keySet());
+ assertEquals("false", r.getAttributes().get("IsDefault"));
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<List<RuleCondition>> conds = ArgumentCaptor.forClass(List.class);
+ verify(elb).createRule(eq(REGION), eq(LISTENER_ARN), conds.capture(), eq(10), anyList(), eq(Map.of()));
+ assertEquals(List.of("/api/*"), conds.getValue().get(0).getPathPatternValues());
+ assertEquals("X-Env", conds.getValue().get(1).getHttpHeaderName());
+ assertEquals("v", conds.getValue().get(2).getQueryStringValues().get(0).getKey());
+ }
+
+ @Test
+ void anUnchangedRuleIsModifiedInPlaceAndAMovedRuleIsReplaced() {
+ when(elb.describeRules(REGION, null, List.of(RULE_ARN))).thenReturn(List.of(rule(LISTENER_ARN)));
+ when(elb.modifyRule(eq(REGION), eq(RULE_ARN), anyList(), anyList())).thenReturn(rule(LISTENER_ARN));
+ StackResource same = resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule");
+ provisioner.provision(same, mapper.createObjectNode().put("ListenerArn", LISTENER_ARN), ctx(RULE_ARN));
+ verify(elb).modifyRule(eq(REGION), eq(RULE_ARN), anyList(), anyList());
+
+ String otherListener = LISTENER_ARN.replace("/web/", "/other/");
+ when(elb.createRule(eq(REGION), eq(otherListener), anyList(), eq(1), anyList(), eq(Map.of())))
+ .thenReturn(rule(otherListener));
+ StackResource moved = resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule");
+ provisioner.provision(moved, mapper.createObjectNode().put("ListenerArn", otherListener), ctx(RULE_ARN));
+ verify(elb).createRule(eq(REGION), eq(otherListener), anyList(), eq(1), anyList(), eq(Map.of()));
+ assertFalse(provisioner.hasReplacementUpdate(same), "an in-place update owes no cleanup");
+ assertEquals(RULE_ARN, provisioner.updateCleanupPhysicalId(moved));
+ assertEquals(new UpdateCleanupResult(true, true, RULE_ARN, 0, null), provisioner.completeUpdate(moved));
+ verify(elb).deleteRule(REGION, RULE_ARN);
+ }
+
+ @Test
+ void aRenamedLoadBalancerIsReplacedAndTheOldOneCleanedUpUnlessRetained() {
+ LoadBalancer renamed = loadBalancer("web-v2");
+ renamed.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v2/"));
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(renamed);
+
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ r.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+ assertEquals(renamed.getLoadBalancerArn(), r.getPhysicalId());
+ assertEquals(LB_ARN, provisioner.updateCleanupPhysicalId(r));
+ assertEquals(new UpdateCleanupResult(true, true, LB_ARN, 0, null), provisioner.completeUpdate(r));
+ verify(elb).deleteLoadBalancer(REGION, LB_ARN);
+
+ StackResource retained = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ retained.setUpdateReplacePolicy("Retain");
+ retained.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(retained, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+ assertNull(provisioner.updateCleanupPhysicalId(retained));
+ assertEquals(new UpdateCleanupResult(true, true, LB_ARN, 0, null), provisioner.completeUpdate(retained));
+ verify(elb, org.mockito.Mockito.times(1)).deleteLoadBalancer(REGION, LB_ARN);
+ }
+
+ @Test
+ void aFailingCleanupDeleteIsRetriedThreeTimesThenReported() {
+ String otherLb = LB_ARN.replace("/web/", "/other/");
+ when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));
+ when(elb.createListener(eq(REGION), eq(otherLb), eq("HTTP"), eq(80), isNull(), anyList(), anyList(), isNull(),
+ eq(Map.of()))).thenReturn(listener(otherLb));
+ doThrow(new AwsException("ResourceInUse", "still forwarding", 400)).when(elb).deleteListener(REGION, LISTENER_ARN);
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ provisioner.provision(r, mapper.createObjectNode().put("LoadBalancerArn", otherLb), ctx(LISTENER_ARN));
+
+ UpdateCleanupResult first = provisioner.completeUpdate(r);
+ assertFalse(first.complete());
+ assertEquals(1, first.attempts());
+ assertEquals("still forwarding", first.failureReason());
+ provisioner.completeUpdate(r);
+ UpdateCleanupResult third = provisioner.completeUpdate(r);
+ assertEquals(3, third.attempts());
+ assertEquals(3, provisioner.completeUpdate(r).attempts(), "no fourth attempt");
+ verify(elb, org.mockito.Mockito.times(3)).deleteListener(REGION, LISTENER_ARN);
+ }
+
+ @Test
+ void aFailedStackUpdateRollsAListenerMoveBackAndDeletesTheReplacement() {
+ String otherLb = LB_ARN.replace("/web/", "/other/");
+ when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));
+ when(elb.createListener(eq(REGION), eq(otherLb), eq("HTTP"), eq(80), isNull(), anyList(), anyList(), isNull(),
+ eq(Map.of()))).thenReturn(listener(otherLb));
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ r.getAttributes().put("ListenerArn", LISTENER_ARN);
+ provisioner.provision(r, mapper.createObjectNode().put("LoadBalancerArn", otherLb), ctx(LISTENER_ARN));
+ String replacementArn = r.getPhysicalId();
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ assertEquals(LISTENER_ARN, r.getPhysicalId());
+ assertEquals(LISTENER_ARN, r.getAttributes().get("ListenerArn"));
+ verify(elb).deleteListener(REGION, replacementArn);
+ verify(elb, never()).deleteListener(REGION, LISTENER_ARN);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void anUnchangedLoadBalancerOrTargetGroupHasNothingToRollBack() {
+ when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
+ when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null)).thenReturn(List.of(loadBalancer("web")));
+ StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ lb.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(lb, mapper.createObjectNode().put("Name", "web"), ctx(LB_ARN));
+
+ // Every property is create-only and the update only described the existing balancer, so a
+ // rollback is complete with nothing to do; the engine must not report it as unimplemented.
+ assertTrue(provisioner.rollbackUpdate(lb));
+ assertEquals(LB_ARN, lb.getPhysicalId());
+ verify(elb, never()).deleteLoadBalancer(anyString(), anyString());
+ }
+
+ @Test
+ void anInPlaceListenerUpdateIsNotRolledBackHere() {
+ when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));
+ when(elb.modifyListener(eq(REGION), eq(LISTENER_ARN), eq("HTTP"), eq(8080), isNull(), anyList(), anyList(), isNull()))
+ .thenReturn(listener(LB_ARN));
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ provisioner.provision(r, mapper.createObjectNode().put("LoadBalancerArn", LB_ARN).put("Port", "8080"), ctx(LISTENER_ARN));
+
+ assertFalse(provisioner.rollbackUpdate(r), "no replacement means nothing this helper can undo");
+ verify(elb, never()).deleteListener(anyString(), anyString());
+ }
+
+ @Test
+ void aRollbackWhoseDeleteFailsStillPointsTheResourceAtThePriorAndPropagates() {
+ LoadBalancer renamed = loadBalancer("web-v2");
+ renamed.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v2/"));
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(renamed);
+ doThrow(new AwsException("ResourceInUse", "listeners attached", 400))
+ .when(elb).deleteLoadBalancer(REGION, renamed.getLoadBalancerArn());
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ r.getAttributes().put("LoadBalancerName", "web");
+ r.getAttributes().put("DNSName", "web-123.us-east-1.elb.amazonaws.com");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ assertEquals("ResourceInUse", e.getErrorCode());
+ assertEquals(LB_ARN, r.getPhysicalId());
+ assertEquals("web", r.getAttributes().get("LoadBalancerName"));
+ assertEquals("web-123.us-east-1.elb.amazonaws.com", r.getAttributes().get("DNSName"));
+
+ // The replacement the failed update created stays owed a delete; the restored prior does not.
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(renamed.getLoadBalancerArn(), provisioner.updateCleanupPhysicalId(r));
+ org.mockito.Mockito.reset(elb);
+ // A second rollback has no replacement of this update to undo: it deletes nothing and keeps
+ // the orphan owed (the load balancer itself rolls back as complete, nothing being modified).
+ provisioner.rollbackUpdate(r);
+ verify(elb, never()).deleteLoadBalancer(anyString(), anyString());
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(new UpdateCleanupResult(true, true, renamed.getLoadBalancerArn(), 0, null), provisioner.completeUpdate(r));
+ verify(elb).deleteLoadBalancer(REGION, renamed.getLoadBalancerArn());
+ verify(elb, never()).deleteLoadBalancer(REGION, LB_ARN);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void anOrphanFromAFailedRollbackSurvivesTheNextProvisionAndIsDeletedWithTheNextReplacement() {
+ String orphanArn = LB_ARN.replace("/web/", "/web-v2/");
+ LoadBalancer renamed = loadBalancer("web-v2");
+ renamed.setLoadBalancerArn(orphanArn);
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(renamed);
+ doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn);
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ r.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ assertEquals(LB_ARN, r.getPhysicalId());
+
+ // The next update keeps the name: nothing replaced, but the orphan is still owed.
+ when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
+ when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null)).thenReturn(List.of(loadBalancer("web")));
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web"), ctx(LB_ARN));
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(orphanArn, provisioner.updateCleanupPhysicalId(r));
+ provisioner.rollbackUpdate(r);
+ assertTrue(provisioner.hasReplacementUpdate(r), "a rollback with no replacement of its own does not forget the orphan");
+ assertEquals(LB_ARN, r.getPhysicalId());
+
+ // A later replacement adds the prior to the same list; the committed cleanup deletes both.
+ LoadBalancer third = loadBalancer("web-v3");
+ third.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v3/"));
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(third);
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v3"), ctx(LB_ARN));
+ org.mockito.Mockito.reset(elb);
+ UpdateCleanupResult cleanup = provisioner.completeUpdate(r);
+ assertTrue(cleanup.complete(), cleanup.toString());
+ verify(elb).deleteLoadBalancer(REGION, orphanArn);
+ verify(elb).deleteLoadBalancer(REGION, LB_ARN);
+ verify(elb, never()).deleteLoadBalancer(REGION, third.getLoadBalancerArn());
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ }
+
+ @Test
+ void aFailingEntryDoesNotStopTheOtherEntriesFromBeingTried() {
+ String orphanArn = LB_ARN.replace("/web/", "/web-v2/");
+ LoadBalancer renamed = loadBalancer("web-v2");
+ renamed.setLoadBalancerArn(orphanArn);
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(renamed);
+ doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn);
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ r.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ LoadBalancer third = loadBalancer("web-v3");
+ third.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v3/"));
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(third);
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v3"), ctx(LB_ARN));
+
+ // The orphan keeps failing; the prior is deleted on the first pass all the same, and the
+ // failing entry is reported with its own attempt count until the engine gives up.
+ UpdateCleanupResult first = provisioner.completeUpdate(r);
+ assertFalse(first.complete());
+ assertEquals(orphanArn, first.previousPhysicalId());
+ assertEquals(1, first.attempts());
+ verify(elb).deleteLoadBalancer(REGION, LB_ARN);
+ provisioner.completeUpdate(r);
+ UpdateCleanupResult third3 = provisioner.completeUpdate(r);
+ assertEquals(3, third3.attempts());
+ assertEquals("listeners attached", third3.failureReason());
+ verify(elb, org.mockito.Mockito.times(1)).deleteLoadBalancer(REGION, LB_ARN);
+ verify(elb, org.mockito.Mockito.times(4)).deleteLoadBalancer(REGION, orphanArn);
+ }
+
+ @Test
+ void givingUpOnOneEntityDoesNotForgetAnotherThatStillHasAttemptsLeft() {
+ String orphanArn = LB_ARN.replace("/web/", "/web-v2/");
+ LoadBalancer renamed = loadBalancer("web-v2");
+ renamed.setLoadBalancerArn(orphanArn);
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(renamed);
+ doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn);
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ r.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ // The orphan uses up its three attempts in a cleanup where it is the only entry.
+ for (int i = 0; i < 3; i++) {
+ provisioner.completeUpdate(r);
+ }
+ assertEquals(3, provisioner.completeUpdate(r).attempts());
+
+ // A later replacement lists the prior beside the exhausted orphan; its delete fails once.
+ LoadBalancer third = loadBalancer("web-v3");
+ third.setLoadBalancerArn(LB_ARN.replace("/web/", "/web-v3/"));
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v3"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(third);
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v3"), ctx(LB_ARN));
+ doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, LB_ARN);
+ UpdateCleanupResult first = provisioner.completeUpdate(r);
+ assertFalse(first.complete());
+ assertEquals(1, first.attempts(), "the entry with attempts left is what the engine retries for");
+ assertEquals(LB_ARN, first.previousPhysicalId());
+ assertEquals(first.previousPhysicalId(), provisioner.updateCleanupPhysicalId(r),
+ "progress and failure events name the same entity");
+
+ org.mockito.Mockito.doNothing().when(elb).deleteLoadBalancer(REGION, LB_ARN);
+ UpdateCleanupResult second = provisioner.completeUpdate(r);
+ assertEquals(3, second.attempts(), "only the exhausted orphan remains");
+ assertEquals(orphanArn, second.previousPhysicalId());
+ provisioner.clearUpdate(r);
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ verify(elb, org.mockito.Mockito.times(4)).deleteLoadBalancer(REGION, orphanArn);
+ }
+
+ @Test
+ void clearingAfterAGiveUpKeepsAnEntryThatStillHasAttemptsLeft() {
+ String orphanArn = LB_ARN.replace("/web/", "/web-v2/");
+ LoadBalancer renamed = loadBalancer("web-v2");
+ renamed.setLoadBalancerArn(orphanArn);
+ when(elb.createLoadBalancer(eq(REGION), eq("web-v2"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
+ .thenReturn(renamed);
+ doThrow(new AwsException("ResourceInUse", "listeners attached", 400)).when(elb).deleteLoadBalancer(REGION, orphanArn);
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
+ r.getAttributes().put("LoadBalancerName", "web");
+ provisioner.provision(r, mapper.createObjectNode().put("Name", "web-v2"), ctx(LB_ARN));
+ assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
+ provisioner.completeUpdate(r);
+
+ provisioner.clearUpdate(r);
+ assertTrue(provisioner.hasReplacementUpdate(r), "cleared with attempts left, the orphan is not forgotten");
+ assertEquals(orphanArn, provisioner.updateCleanupPhysicalId(r));
+ }
+
+ @Test
+ void aNonIntegerPortOrPriorityIsAValidationError() {
+ StackResource listener = resource("AWS::ElasticLoadBalancingV2::Listener", "Listener");
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(listener,
+ mapper.createObjectNode().put("LoadBalancerArn", LB_ARN).put("Port", "eighty"), ctx()));
+ assertEquals("ValidationError", e.getErrorCode());
+ assertNull(listener.getPhysicalId());
+
+ StackResource rule = resource("AWS::ElasticLoadBalancingV2::ListenerRule", "Rule");
+ assertThrows(AwsException.class, () -> provisioner.provision(rule,
+ mapper.createObjectNode().put("ListenerArn", LISTENER_ARN).put("Priority", "high"), ctx()));
+ }
+
+ @Test
+ void deletesCallTheServiceAndPropagateItsRefusals() {
+ provisioner.delete("AWS::ElasticLoadBalancingV2::LoadBalancer", LB_ARN, REGION);
+ provisioner.delete("AWS::ElasticLoadBalancingV2::Listener", LISTENER_ARN, REGION);
+ provisioner.delete("AWS::ElasticLoadBalancingV2::ListenerRule", RULE_ARN, REGION);
+ verify(elb).deleteLoadBalancer(REGION, LB_ARN);
+ verify(elb).deleteListener(REGION, LISTENER_ARN);
+ verify(elb).deleteRule(REGION, RULE_ARN);
+
+ doThrow(new AwsException("ResourceInUse", "in use", 400)).when(elb).deleteTargetGroup(REGION, TG_ARN);
+ AwsException e = assertThrows(AwsException.class,
+ () -> provisioner.delete("AWS::ElasticLoadBalancingV2::TargetGroup", TG_ARN, REGION));
+ assertEquals("ResourceInUse", e.getErrorCode());
+
+ // Only the type's own not-found code is delete-complete.
+ doThrow(new AwsException("LoadBalancerNotFound", "gone", 400)).when(elb).deleteLoadBalancer(REGION, "gone-arn");
+ provisioner.delete("AWS::ElasticLoadBalancingV2::LoadBalancer", "gone-arn", REGION);
+
+ provisioner.delete("AWS::ElasticLoadBalancingV2::LoadBalancer", null, REGION);
+ verify(elb, never()).deleteLoadBalancer(eq(REGION), isNull());
+ }
+
+ @Test
+ void rejectsAResourceTypeItDoesNotOwn() {
+ StackResource r = resource("AWS::ElasticLoadBalancingV2::TrustStore", "Ts");
+ assertThrows(IllegalStateException.class, () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index a7a558d61b..b404f437d1 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -66,10 +66,10 @@ AWS::ECS::Service EcsCfnProvisioner
AWS::ECS::TaskDefinition EcsCfnProvisioner
AWS::EKS::Cluster LEGACY_SWITCH
AWS::EKS::Nodegroup LEGACY_SWITCH
-AWS::ElasticLoadBalancingV2::Listener LEGACY_SWITCH
-AWS::ElasticLoadBalancingV2::ListenerRule LEGACY_SWITCH
-AWS::ElasticLoadBalancingV2::LoadBalancer LEGACY_SWITCH
-AWS::ElasticLoadBalancingV2::TargetGroup LEGACY_SWITCH
+AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner
+AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner
+AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner
+AWS::ElasticLoadBalancingV2::TargetGroup ElbV2CfnProvisioner
AWS::Events::EventBus LEGACY_SWITCH
AWS::Events::EventBusPolicy LEGACY_SWITCH
AWS::Events::Rule LEGACY_SWITCH