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

* refactor(cloudformation): move the ElasticLoadBalancingV2 types into ElbV2CfnProvisioner

AWS::ElasticLoadBalancingV2::LoadBalancer, TargetGroup, Listener and
ListenerRule leave the legacy switch together with the ELBv2-only helpers
(ELB-safe name generation, full-name derivation, matcher, certificates,
action and rule-condition parsing). The monolith no longer depends on
ElbV2Service; its constructor loses that parameter and CfnProvisionerFixture
passes one argument less.

Behaviour is unchanged except where the move fixes it. An unnamed load
balancer or target group keeps the name its first execution generated, read
back from the LoadBalancerName / TargetGroupName attribute since the physical
id is the ARN; the switch generated a fresh name on every pass and left the
previous resource behind. Listener and ListenerRule branch create-vs-update
on the provision context, and a listener moved to another load balancer or a
rule moved to another listener (both create-only properties) is created as a
replacement instead of being modified under the old parent; one removed out
of band is created again. A non-integer Port or Priority is a ValidationError
instead of an uncaught NumberFormatException. Deletes call the service
directly: it already returns silently for an unknown ARN, and its refusals
(ResourceInUse, OperationNotPermitted) must keep failing the stack delete.

Fn::GetAtt follows the registry schemas' readOnly properties. The five load
balancer attributes, ListenerArn, RuleArn and IsDefault are as before;
TargetGroup gains LoadBalancerArns (comma-joined, empty until a listener
forwards to the group), which the switch never set and the schema coverage
test now requires. CloudFormationIntegrationTest keeps asserting the stack
outputs end to end; ElbV2CfnProvisionerTest covers the four types against a
mocked ElbV2Service. The whole CloudFormation test package passes on this
tree apart from the pre-existing ACM schema-gap row.

* refactor(cloudformation): clean up the ELBv2 entity a replacing update displaced

Review found that a listener moved to another load balancer, or a rule moved
to another listener, was created anew while the displaced one kept running,
holding its target groups in use and never appearing in the stack's cleanup.
The same was true of a renamed load balancer or target group.

Every replacing update of the four types now enters the replacement-cleanup
lifecycle the engine already runs (UPDATE_COMPLETE_CLEANUP_IN_PROGRESS,
DELETE_IN_PROGRESS on the prior ARN, three attempts, UpdateReplacePolicy
Retain honoured). ReplacementCleanup is the plain bookkeeping for provisioners
without a rollback snapshot, beside the richer record PipesCfnProvisioner
keeps; the provisioner delegates the four interface hooks to it and deletes
through its own delete arm. The direct service deletes stay as they were:
ElbV2Service returns silently for an unknown ARN, so there is no already-gone
code for CfnDeletes.safeDelete to tolerate, and its refusals (ResourceInUse,
OperationNotPermitted) must keep failing the stack delete.

* refactor(cloudformation): roll an ELBv2 replacement back and clean up dependents first

Review found two gaps in the replacement handling. A replacement this
provisioner produces (a listener moved to another load balancer, a rule moved
to another listener, a renamed load balancer or target group) could not be
rolled back when a later resource failed the stack update: rollbackUpdate had
no implementation, so the engine reported "Rollback is not implemented", left
the replacement running and the stack in UPDATE_ROLLBACK_FAILED. And the
committed-update cleanup walked resources in creation order, so a target group
renamed in the same update as its listener was moved would be deleted while
the old listener still forwarded to it, fail ResourceInUse three times and be
left behind.

ReplacementCleanup now keeps the attributes the resource carried before the
provision alongside the prior physical id, and rollback() puts both back and
deletes the replacement through the provisioner's own delete arm, spending
the record before the delete so a failing delete cannot put the restored
prior on the next cleanup's list. The provisioner records once, in
provision(), and delegates rollbackUpdate. A load balancer or target group
without a record has nothing to put back, every property being create-only
and the update having only described the existing entity, so it rolls back as
complete; a listener or rule modified in place keeps the engine's existing
handling, as under the switch.

CloudFormationService's committed cleanup walks resources in reverse creation
order, as every other teardown walk does. CloudFormationElbV2ReplacementIntegrationTest
drives both through the engine: a renamed target group plus a moved listener
end with DELETE_COMPLETE events on both prior ARNs and neither entity left,
and a moved listener followed by a failing resource lands the stack in
UPDATE_ROLLBACK_COMPLETE with the prior listener restored and the replacement
gone.

* refactor(cloudformation): order replacement cleanup by the template and keep an orphaned replacement owed

Two gaps in the replacement lifecycle, both found in review. The committed
cleanup walked the resource map reversed, but the map is insertion order and
a resource a later update added sits after the resources that depend on it,
so a target group added after its listener would still be deleted first,
fail ResourceInUse three times and be left behind. The cleanup now walks
resourcesInCreationOrder reversed, the template's dependency order, exactly
as DeleteStack does; a resource the template no longer names sorts last.

And a rollback whose delete of the replacement failed forgot the replacement:
the record was cleared before the delete, so nothing could remove that
entity later even though UPDATE_ROLLBACK_FAILED is updatable here and both
the next committed update and DeleteStack run the cleanup first. The record
is now a list of every entity owed a delete: a replacement whose rollback
delete fails is listed in the prior's place, never retained (a failed update
created it), and the prior's own id and attributes are kept beside the list
only while this update's replacement can still be rolled back. Every listed
entity gets its attempt on every cleanup call, so one that keeps failing does
not leave the others untried.

The load balancer and target group rollback note now says what is true: this
provisioner never modifies an existing one, so an update that kept the name
has nothing to put back (in-place changes to their updatable properties are
not applied, as under the switch).

CloudFormationElbV2ReplacementIntegrationTest gains the appended-dependency
case: a target group added by a later update than its listener, then both
replaced, ends with both prior ARNs DELETE_COMPLETE.

* refactor(cloudformation): keep a displaced entity owed until its own attempts are used up

Review found that once any listed entity reached three failed deletes, the engine's give-up cleared the whole record, forgetting entities that still had attempts left. clearUpdate now drops only the entries that used up their attempts (and the rollback fields), and the cleanup result reports the lowest attempt count among what remains, naming that entity, so the engine keeps retrying until every remaining entity has had its own three attempts.

* refactor(cloudformation): tolerate the ELBv2 not-found codes on delete and name one entity per cleanup

The four ELBv2 deletes go through CfnDeletes.safeDelete with the not-found
code ElbV2Service defines for each type (LoadBalancerNotFound,
TargetGroupNotFound, ListenerNotFound, RuleNotFound), the convention every
other per-service provisioner follows. The service's delete paths return
silently on an unknown ARN today, so nothing changes in behaviour; its
refusals (ResourceInUse, OperationNotPermitted) are not in the list and keep
failing the stack delete.

The replacement cleanup picks the entity it works on through one rule, the
owed entry with the fewest attempts, for both the physical id it announces
(DELETE_IN_PROGRESS) and the one it reports on failure (DELETE_FAILED), so a
cleanup's progress and failure events name the same thing. The unused
parameter on the record's region lookup goes.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-07 09:17:32 -04:00
1 parent acc0904be4
commit 2541f1b68d
7 files changed
+1473 -347

No files matched your search

@@ -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,
@@ -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)));
}
}
@@ -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()));
}
}