Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): move a kept load balancer onto the template's subnets (#5881)
Jackson Price94288dadd91e
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.javaindex b8fe80811c..784d990511 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java@@ -42,6 +42,14 @@ public final class CfnRollback {*/public static final String PIPE_UPDATE_SNAPSHOT_ATTR = "__FlociPipeUpdateSnapshot";+ /**+ * Holds the subnets a kept ELBv2 load balancer had before the update in flight moved it,+ * comma-joined, so a failed stack update can move it back. Written by+ * {@code ElbV2CfnProvisioner} after its SetSubnets and spent by its {@code rollbackUpdate},+ * retained across a failed move back.+ */+ public static final String LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR = "__FlociLoadBalancerSubnetsUpdateSnapshot";+/*** Holds the targets an EventBridge rule carried before the update in flight reconciled them,* with the rule name, bus and region needed to address them again, so a failed stack update candiff --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.javaindex e34341c44a..6726e5bd95 100644--- 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@@ -6,6 +6,7 @@ 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.AvailabilityZone;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;@@ -50,6 +51,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {@Overridepublic void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ r.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());switch (r.getResourceType()) {case LOAD_BALANCER -> provisionLoadBalancer(r, props, ctx);@@ -99,19 +101,23 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {@Overridepublic UpdateCleanupResult completeUpdate(StackResource resource) {+ if ("UPDATE_COMPLETE".equals(resource.getStatus())) {+ resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);+ }return ReplacementCleanup.complete(resource, this::delete);}@Overridepublic void clearUpdate(StackResource resource) {+ resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);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+ * A replacement is undone through the cleanup record. Without one, a load balancer is moved+ * back to the subnets an update took it off, and otherwise it and a target group have nothing to+ * put back: an update that kept the name changed nothing else, the way the switch did. 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@@ -119,7 +125,26 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {if (ReplacementCleanup.rollback(resource, this::delete)) {return true;}- return LOAD_BALANCER.equals(resource.getResourceType()) || TARGET_GROUP.equals(resource.getResourceType());+ if (LOAD_BALANCER.equals(resource.getResourceType())) {+ return restorePriorSubnets(resource);+ }+ return TARGET_GROUP.equals(resource.getResourceType());+ }++ /**+ * A failed move back propagates, so the engine reports its reason rather than an unimplemented+ * rollback, and the snapshot stays until a move back succeeds.+ */+ private boolean restorePriorSubnets(StackResource resource) {+ String prior = resource.getAttributes().get(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);+ if (prior == null) {+ return true;+ }+ String arn = resource.getPhysicalId();+ elbV2Service.setSubnets(AwsArnUtils.parse(arn).region(), arn,+ prior.isEmpty() ? List.of() : List.of(prior.split(",")));+ resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);+ return true;}/**@@ -135,7 +160,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {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> subnets = templateSubnets(props, ctx);List<String> securityGroups = ctx.resolveStringList(props, "SecurityGroups");Map<String, String> tags = ctx.resolveTags(props, "Tags");@@ -148,6 +173,9 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {throw e;}lb = elbV2Service.describeLoadBalancers(ctx.region(), null, List.of(name), null, null).get(0);+ if (ctx.reusesPriorEntity(lb.getLoadBalancerArn())) {+ moveToTemplateSubnets(r, lb, subnets, ctx);+ }}r.setPhysicalId(lb.getLoadBalancerArn());@@ -158,6 +186,56 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));}+ /**+ * The template's subnets: {@code Subnets}, or else the {@code SubnetId} of each+ * {@code SubnetMappings} entry, the form a Network Load Balancer uses to give a zone an Elastic IP.+ * Both non-empty fails the resource with the error CreateLoadBalancer gives, as the resource allows+ * one or the other; an empty side, such as one an Fn::If drops, does not count. {@code SubnetId} is+ * required in a mapping, so one without it fails the resource before anything is created or moved,+ * with the error the resource schema gives. A blank one counts as a mapping and, with no+ * {@code Subnets}, is passed on as given for ELBv2 to refuse as an unknown subnet; dropping it would+ * create or move the balancer without it.+ */+ private static List<String> templateSubnets(JsonNode props, ProvisionContext ctx) {+ List<String> subnets = ctx.resolveStringList(props, "Subnets");+ if (props == null || !props.has("SubnetMappings")) {+ return subnets;+ }+ List<String> mapped = new ArrayList<>();+ // A mapping, or its SubnetId, that an Fn::If drops with AWS::NoValue is left out, as on AWS.+ JsonNode mappings = ctx.engine().resolveNodeOmittingNoValue(props.get("SubnetMappings"));+ if (mappings != null && mappings.isArray()) {+ for (int i = 0; i < mappings.size(); i++) {+ String subnetId = ctx.resolveOptional(mappings.get(i), "SubnetId");+ if (subnetId == null) {+ throw new AwsException("InvalidRequest",+ "Model validation failed (#/SubnetMappings/" + i + ": required key [SubnetId] not found)", 400);+ }+ mapped.add(subnetId);+ }+ }+ if (!subnets.isEmpty() && !mapped.isEmpty()) {+ throw new AwsException("ValidationError",+ "You can specify either subnets or subnet mappings, not both", 400);+ }+ return subnets.isEmpty() ? mapped : subnets;+ }++ /**+ * {@code Subnets} is not create-only, so an update that keeps the balancer moves it onto the+ * template's subnets in place, as SetSubnets does, rather than leaving it on a subnet the template+ * dropped or replaced and the update cleanup then deletes. The prior list is kept for a rollback.+ */+ private void moveToTemplateSubnets(StackResource r, LoadBalancer lb, List<String> subnets,+ ProvisionContext ctx) {+ List<String> current = lb.getAvailabilityZones().stream().map(AvailabilityZone::getSubnetId).toList();+ if (subnets.isEmpty() || Set.copyOf(subnets).equals(Set.copyOf(current))) {+ return;+ }+ elbV2Service.setSubnets(ctx.region(), lb.getLoadBalancerArn(), subnets);+ r.getAttributes().put(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR, String.join(",", current));+ }+private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {String name = nameOrPrior(ctx.resolveOptional(props, "Name"), r.getAttributes().get("TargetGroupName"),ctx, r.getLogicalId());diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.javanew file mode 100644index 0000000000..3c64c875db--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationElbV2SubnetMappingsIntegrationTest.java@@ -0,0 +1,145 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.core.common.XmlParser;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.ValidatableResponse;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;++import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * {@code SubnetId} is required in a load balancer's {@code SubnetMappings}. A mapping that names no+ * subnet fails its stack, as on AWS, rather than the balancer being created with no subnets, while a+ * mapping an {@code Fn::If} drops with {@code AWS::NoValue} is left out. {@code Subnets} and+ * {@code SubnetMappings} together fail it too, as ELBv2 takes one or the other.+ */+@QuarkusTest+class CloudFormationElbV2SubnetMappingsIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20261018/us-east-1/cloudformation/aws4_request";+ private static final String ELB_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20261018/us-east-1/elasticloadbalancing/aws4_request";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ /**+ * A mapping with no {@code SubnetId}, one whose {@code SubnetId} an {@code Fn::If} drops, and one+ * whose {@code SubnetId} is blank, each with the reason the resource fails with.+ */+ @ParameterizedTest+ @CsvSource(delimiter = '|', value = {+ "{\"AllocationId\": \"eipalloc-12345678\"}|required key [SubnetId] not found",+ "{\"SubnetId\": {\"Fn::If\": [\"Never\", {\"Ref\": \"SubnetA\"}, {\"Ref\": \"AWS::NoValue\"}]}}|required key [SubnetId] not found",+ "{\"SubnetId\": \"\"}|The subnet ID '' does not exist"+ })+ void aSubnetMappingThatNamesNoSubnetFailsTheStackWithoutALoadBalancer(String mapping, String reason) {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stack = "nlb-mappings-" + suffix;+ String name = "nlb-" + suffix;+ try {+ request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template(name, mapping))+ .statusCode(200);+ CfnStackWaits.awaitStatus(stack, "ROLLBACK_COMPLETE");+ String events = request(CFN_AUTH, "DescribeStackEvents", "StackName", stack).statusCode(200)+ .extract().asString();+ List<String> reasons = XmlParser.extractAll(events, "ResourceStatusReason");+ assertTrue(reasons.stream().anyMatch(r -> r.contains(reason)), String.join(" | ", reasons));+ request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(400)+ .body(containsString("LoadBalancerNotFound"));+ } finally {+ request(CFN_AUTH, "DeleteStack", "StackName", stack);+ }+ }++ /** {@code Subnets} and {@code SubnetMappings} together fail the stack, as ELBv2 refuses both. */+ @Test+ void subnetsAndSubnetMappingsTogetherFailTheStack() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stack = "nlb-both-" + suffix;+ String name = "nlb-both-" + suffix;+ String template = template(name, "{\"SubnetId\": {\"Ref\": \"SubnetA\"}}")+ .replace("\"SubnetMappings\":", "\"Subnets\": [{\"Ref\": \"SubnetB\"}], \"SubnetMappings\":");+ try {+ request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template).statusCode(200);+ CfnStackWaits.awaitStatus(stack, "ROLLBACK_COMPLETE");+ String events = request(CFN_AUTH, "DescribeStackEvents", "StackName", stack).statusCode(200)+ .extract().asString();+ List<String> reasons = XmlParser.extractAll(events, "ResourceStatusReason");+ assertTrue(reasons.stream().anyMatch(r -> r.contains("either subnets or subnet mappings, not both")),+ String.join(" | ", reasons));+ request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(400)+ .body(containsString("LoadBalancerNotFound"));+ } finally {+ request(CFN_AUTH, "DeleteStack", "StackName", stack);+ }+ }++ /** A second mapping an {@code Fn::If} drops leaves the balancer on the first mapping's subnet. */+ @Test+ void aMappingAnFnIfDropsIsLeftOut() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stack = "nlb-mappings-if-" + suffix;+ String name = "nlb-if-" + suffix;+ String mappings = "{\"SubnetId\": {\"Ref\": \"SubnetA\"}}, "+ + "{\"Fn::If\": [\"Never\", {\"SubnetId\": {\"Ref\": \"SubnetB\"}}, {\"Ref\": \"AWS::NoValue\"}]}";+ try {+ request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template(name, mappings))+ .statusCode(200);+ CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");+ String outputs = request(CFN_AUTH, "DescribeStacks", "StackName", stack).statusCode(200)+ .extract().asString();+ String subnetA = XmlParser.extractPairs(outputs, "member", "OutputKey", "OutputValue").get("SubnetA");+ String described = request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(200)+ .extract().asString();+ assertEquals(List.of(subnetA), XmlParser.extractAll(described, "SubnetId"));+ } finally {+ request(CFN_AUTH, "DeleteStack", "StackName", stack);+ }+ }++ /** A VPC with two subnets and a network load balancer with the given mappings. */+ private static String template(String name, String mappings) {+ return """+ {+ "Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},+ "Resources": {+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.97.0.0/16"}},+ "SubnetA": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": {"Ref": "Vpc"},+ "CidrBlock": "10.97.1.0/24", "AvailabilityZone": "us-east-1a"}},+ "SubnetB": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": {"Ref": "Vpc"},+ "CidrBlock": "10.97.2.0/24", "AvailabilityZone": "us-east-1b"}},+ "Nlb": {+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",+ "Properties": {"Name": "%s", "Type": "network", "Scheme": "internal", "SubnetMappings": [%s]}+ }+ },+ "Outputs": {"SubnetA": {"Value": {"Ref": "SubnetA"}}}+ }+ """.formatted(name, mappings);+ }++ private static ValidatableResponse request(String auth, String action, String... values) {+ Map<String, String> parameters = new LinkedHashMap<>();+ parameters.put("Action", action);+ for (int i = 0; i < values.length; i += 2) {+ parameters.put(values[i], values[i + 1]);+ }+ return given().contentType("application/x-www-form-urlencoded").header("Authorization", auth)+ .formParams(parameters).when().post("/").then().log().ifValidationFails();+ }+}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.javaindex 14c9faae8b..af7b97d853 100644--- 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@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateimport 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.AvailabilityZone;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;@@ -40,6 +41,7 @@ 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.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -73,6 +75,7 @@ class ElbV2CfnProvisionerTest {return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();});when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));+ when(engine.resolveNodeOmittingNoValue(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();@@ -405,13 +408,259 @@ class ElbV2CfnProvisionerTest {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.+ // The update declared no subnets, so it only described the existing balancer and 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());}+ private LoadBalancer loadBalancerOn(String name, String... subnetIds) {+ LoadBalancer lb = loadBalancer(name);+ for (String subnetId : subnetIds) {+ AvailabilityZone zone = new AvailabilityZone();+ zone.setSubnetId(subnetId);+ lb.getAvailabilityZones().add(zone);+ }+ return lb;+ }++ private StackResource keptLoadBalancerUpdatedTo(LoadBalancer existing, String... subnets) {+ 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(existing));+ ObjectNode props = mapper.createObjectNode().put("Name", "web");+ ArrayNode subnetList = props.putArray("Subnets");+ for (String subnet : subnets) {+ subnetList.add(subnet);+ }+ StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");+ lb.getAttributes().put("LoadBalancerName", "web");+ provisioner.provision(lb, props, ctx(LB_ARN));+ return lb;+ }++ @Test+ void anUpdateMovesTheKeptLoadBalancerOntoTheTemplateSubnetsAndARollbackMovesItBack() {+ StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),+ "subnet-1", "subnet-3");++ verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-3"));+ assertEquals(LB_ARN, lb.getPhysicalId());++ assertTrue(provisioner.rollbackUpdate(lb));+ verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));+ }++ @Test+ void theSameSubnetsInAnotherOrderLeaveTheKeptLoadBalancerAlone() {+ StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),+ "subnet-2", "subnet-1");++ assertTrue(provisioner.rollbackUpdate(lb));+ verify(elb, never()).setSubnets(anyString(), anyString(), anyList());+ }++ @Test+ void aCommittedUpdateForgetsThePriorSubnets() {+ StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),+ "subnet-1", "subnet-3");+ lb.setStatus("UPDATE_COMPLETE");++ provisioner.completeUpdate(lb);++ assertTrue(provisioner.rollbackUpdate(lb));+ verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-3"));+ verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));+ }++ @Test+ void aFailedMoveBackPropagatesAndKeepsThePriorSubnetsForAnotherTry() {+ StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),+ "subnet-1", "subnet-3");+ doThrow(new AwsException("SubnetNotFound", "The subnet ID 'subnet-2' does not exist", 400)).doNothing()+ .when(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(lb));+ assertEquals("SubnetNotFound", failure.getErrorCode());+ assertTrue(provisioner.rollbackUpdate(lb));+ verify(elb, times(2)).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));+ }++ @Test+ void aClearedUpdateForgetsThePriorSubnets() {+ StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),+ "subnet-1", "subnet-3");++ provisioner.clearUpdate(lb);++ assertTrue(provisioner.rollbackUpdate(lb));+ verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));+ }++ @Test+ void aLaterUpdateThatLeavesTheSubnetsAloneDropsAStaleSnapshot() {+ StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),+ "subnet-1", "subnet-3");+ ObjectNode props = mapper.createObjectNode().put("Name", "web");+ props.putArray("Subnets").add("subnet-2").add("subnet-1");++ provisioner.provision(lb, props, ctx(LB_ARN));++ assertTrue(provisioner.rollbackUpdate(lb));+ verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));+ }++ @Test+ void aCreateThatFindsTheNameTakenLeavesThatLoadBalancerOnItsSubnets() {+ 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(loadBalancerOn("web", "subnet-1", "subnet-2")));+ ObjectNode props = mapper.createObjectNode().put("Name", "web");+ props.putArray("Subnets").add("subnet-3").add("subnet-4");++ provisioner.provision(resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"), props, ctx());++ verify(elb, never()).setSubnets(anyString(), anyString(), anyList());+ }++ @Test+ void subnetMappingsGiveTheSubnetsWhenSubnetsIsAbsent() {+ when(elb.createLoadBalancer(eq(REGION), eq("nlb"), isNull(), eq("network"), isNull(),+ eq(List.of("subnet-1", "subnet-2")), anyList(), any())).thenReturn(loadBalancer("nlb"));+ ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");+ ArrayNode mappings = props.putArray("SubnetMappings");+ mappings.addObject().put("SubnetId", "subnet-1").put("AllocationId", "eipalloc-1");+ mappings.addObject().put("SubnetId", "subnet-2");++ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb");+ provisioner.provision(r, props, ctx());++ assertEquals(LB_ARN, r.getPhysicalId());+ }++ /**+ * {@code SubnetId} is required in a {@code SubnetMapping}. A mapping without one fails the+ * resource before any load balancer is created, rather than leaving a balancer with no subnets.+ */+ @Test+ void aSubnetMappingWithoutASubnetIdIsRefusedBeforeTheLoadBalancerIsCreated() {+ ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");+ props.putArray("SubnetMappings").addObject().put("AllocationId", "eipalloc-1");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(+ resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb"), props, ctx()));++ assertEquals("InvalidRequest", e.getErrorCode());+ assertTrue(e.getMessage().contains("#/SubnetMappings/0: required key [SubnetId] not found"), e.getMessage());+ verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());+ }++ /** The same mapping on an update of a kept load balancer fails before it is moved anywhere. */+ @Test+ void anUpdateWithASubnetMappingWithoutASubnetIdLeavesTheKeptLoadBalancerAlone() {+ ObjectNode props = mapper.createObjectNode().put("Name", "web");+ ArrayNode mappings = props.putArray("SubnetMappings");+ mappings.addObject().put("SubnetId", "subnet-1");+ mappings.addObject().put("PrivateIPv4Address", "10.0.2.10");+ StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");+ lb.getAttributes().put("LoadBalancerName", "web");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));++ assertTrue(e.getMessage().contains("#/SubnetMappings/1: required key [SubnetId] not found"), e.getMessage());+ verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());+ verify(elb, never()).setSubnets(anyString(), anyString(), anyList());+ }++ /**+ * A blank {@code SubnetId} is passed on as given, so ELBv2 refuses it as an unknown subnet+ * rather than the mapping being dropped and the balancer created without it.+ */+ @Test+ void aBlankSubnetIdIsPassedOnRatherThanDropped() {+ when(elb.createLoadBalancer(eq(REGION), eq("nlb"), isNull(), eq("network"), isNull(),+ eq(List.of(" ")), anyList(), any()))+ .thenThrow(new AwsException("SubnetNotFound", "The subnet ID ' ' does not exist", 400));+ ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");+ props.putArray("SubnetMappings").addObject().put("SubnetId", " ");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(+ resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb"), props, ctx()));++ assertEquals("SubnetNotFound", e.getErrorCode());+ }++ /** On an update of a kept load balancer, a blank {@code SubnetId} reaches SetSubnets for ELBv2 to refuse. */+ @Test+ void anUpdateWithABlankSubnetIdIsRefusedByTheMoveAndKeepsNoSnapshot() {+ 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(loadBalancerOn("web", "subnet-1", "subnet-2")));+ doThrow(new AwsException("SubnetNotFound", "The subnet ID ' ' does not exist", 400))+ .when(elb).setSubnets(REGION, LB_ARN, List.of(" "));+ ObjectNode props = mapper.createObjectNode().put("Name", "web");+ props.putArray("SubnetMappings").addObject().put("SubnetId", " ");+ StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");+ lb.getAttributes().put("LoadBalancerName", "web");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));++ assertEquals("SubnetNotFound", e.getErrorCode());+ assertNull(lb.getAttributes().get(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR));+ }++ /**+ * {@code Subnets} and {@code SubnetMappings} together fail the resource with the error ELBv2's+ * CreateLoadBalancer gives for both, before any load balancer is created.+ */+ @Test+ void subnetsAndSubnetMappingsTogetherAreRefusedBeforeTheLoadBalancerIsCreated() {+ ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");+ props.putArray("Subnets").add("subnet-1");+ props.putArray("SubnetMappings").addObject().put("SubnetId", "subnet-2");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(+ resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb"), props, ctx()));++ assertEquals("ValidationError", e.getErrorCode());+ assertEquals("You can specify either subnets or subnet mappings, not both", e.getMessage());+ verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());+ }++ /** An empty {@code SubnetMappings} beside {@code Subnets}, as an Fn::If that drops each leaves, is allowed. */+ @Test+ void anEmptySubnetMappingsBesideSubnetsIsAllowed() {+ when(elb.createLoadBalancer(eq(REGION), eq("alb"), isNull(), isNull(), isNull(),+ eq(List.of("subnet-1", "subnet-2")), anyList(), any())).thenReturn(loadBalancer("alb"));+ ObjectNode props = mapper.createObjectNode().put("Name", "alb");+ props.putArray("Subnets").add("subnet-1").add("subnet-2");+ props.putArray("SubnetMappings");++ StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");+ provisioner.provision(r, props, ctx());++ assertEquals(LB_ARN, r.getPhysicalId());+ }++ /** The same on an update of a kept load balancer, before it is moved anywhere. */+ @Test+ void anUpdateWithSubnetsAndSubnetMappingsTogetherLeavesTheKeptLoadBalancerAlone() {+ ObjectNode props = mapper.createObjectNode().put("Name", "web");+ props.putArray("Subnets").add("subnet-1").add("subnet-3");+ props.putArray("SubnetMappings").addObject().put("SubnetId", "subnet-3");+ StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");+ lb.getAttributes().put("LoadBalancerName", "web");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));++ assertEquals("ValidationError", e.getErrorCode());+ verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());+ verify(elb, never()).setSubnets(anyString(), anyString(), anyList());+ }+@Testvoid anInPlaceListenerUpdateIsNotRolledBackHere() {when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));