fix(cloudformation): register a target group's Targets and keep them in step on update (#8199)

This commit is contained in:
Suja Shaj authored and GitHub committed 2026-11-13 08:27:19 -04:00
1 parent 5816d8a908
commit 7d7c87338f
10 files changed
+858 -87

No files matched your search

+26
View File
@@ -603,6 +603,32 @@ Dynamic-reference expansion is currently scoped to these RDS credential properti
only through a parameter, or anything else the update changes, is not seen there.
- `KmsKeyId` is still accepted and ignored, so an encrypted instance reports no key.
## ELBv2 target group targets
`AWS::ElasticLoadBalancingV2::TargetGroup` registers its `Targets` once the group is created, as
`RegisterTargets` does, so `DescribeTargetHealth` reports them. A target is its `Id` and its `Port`,
the group's port when it names none, so one instance can be declared on several ports. A Lambda
target has no port and is its function ARN alone.
- On `UpdateStack` (no interruption, as in AWS), the group keeps its ARN. The targets the template
gains are registered first, then the targets the previous template declared and the new one
drops are deregistered. A template that drops `Targets` deregisters every target the stack
declared. A target registered some other way, by `RegisterTargets`, an Auto Scaling group or an
ECS service, stays registered until a template declares it and a later one drops it. A declared
target registered with another `AvailabilityZone` is registered again with the declared one.
- A target `RegisterTargets` refuses registers nothing, as it checks every target before it
registers any. A group the stack had just created for the resource is then deleted again, and a
group the update kept is left as it was. If deregistering fails after the registration, a kept
group gets back the registrations it had.
- A failed update deregisters the targets the update registered and registers the ones it
deregistered again. When the group is gone by then, the rollback fails with
`TargetGroupNotFound` and leaves the stack in `UPDATE_ROLLBACK_FAILED`. `ContinueUpdateRollback`
fails the same way until the target group is passed in `ResourcesToSkip` (see
[Failed update rollbacks](#failed-update-rollbacks)).
- A target group created before Floci registered `Targets` has no targets from its template. The
first update that changes the group registers the declared targets and deregisters nothing.
- `QuicServerId` is accepted and ignored, as Floci's `RegisterTargets` has no QUIC support.
## S3 ownership controls
`AWS::S3::Bucket` applies `OwnershipControls` through the same S3 call as
@@ -79,6 +79,15 @@ public final class CfnRollback {
*/
public static final String LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR = "__FlociLoadBalancerSubnetsUpdateSnapshot";
/**
* Holds what an update that kept an ELBv2 target group changed in its registrations: the targets
* it registered that were not registered before, and the registrations it deregistered or
* registered over, so a failed stack update can put them back. Written by
* {@code ElbV2CfnProvisioner} between its RegisterTargets and DeregisterTargets and spent by the
* undo of a failed provision or by its {@code rollbackUpdate}, retained across a failed put back.
*/
public static final String TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR = "__FlociTargetGroupTargetsUpdateSnapshot";
/**
* 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 can
@@ -1,9 +1,14 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.elbv2.ElbV2HealthChecker;
import io.floci.aws.services.elbv2.ElbV2Service;
import io.floci.aws.services.elbv2.model.Action;
import io.floci.aws.services.elbv2.model.AvailabilityZone;
@@ -11,6 +16,7 @@ import io.floci.aws.services.elbv2.model.Listener;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.services.elbv2.model.Rule;
import io.floci.aws.services.elbv2.model.RuleCondition;
import io.floci.aws.services.elbv2.model.TargetDescription;
import io.floci.aws.services.elbv2.model.TargetGroup;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -19,6 +25,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@@ -38,6 +45,19 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
private static final String LISTENER_RULE = "AWS::ElasticLoadBalancingV2::ListenerRule";
/** Prefixes one uses attribute per subnet a load balancer is on, numbered from 1. */
private static final String USED_SUBNET_ATTR_PREFIX = CfnRollback.USES_ATTR_PREFIX + "Subnet.";
/**
* The {@code Targets} the template declared at the last successful provision of a target group, a
* JSON array of {@code {id, port, availabilityZone}}. An update deregisters only the targets this
* record names and the template no longer does, so a target registered some other way, by
* RegisterTargets, an Auto Scaling group or an ECS service, stays registered. A target group
* provisioned before the record was kept has none: Floci registered nothing for it, so its first
* update deregisters nothing. The record an update overwrote is kept until the update commits, so
* a rollback puts it back.
*/
private static final CreateOnlyInputs DECLARED_TARGETS = new CreateOnlyInputs(
"__FlociTargetGroupTargets", "__FlociTargetGroupTargetsPrior");
private static final TypeReference<List<TargetDescription>> TARGET_LIST = new TypeReference<>() { };
private static final ObjectMapper MAPPER = new ObjectMapper();
private final ElbV2Service elbV2Service;
@@ -54,10 +74,11 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
r.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);
r.getAttributes().remove(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR);
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 TARGET_GROUP -> provisionTargetGroup(r, props, ctx, attributesBefore);
case LISTENER -> provisionListener(r, props, ctx);
case LISTENER_RULE -> provisionListenerRule(r, props, ctx);
default -> throw new IllegalStateException("ElbV2CfnProvisioner cannot handle " + r.getResourceType());
@@ -106,31 +127,90 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
if ("UPDATE_COMPLETE".equals(resource.getStatus())) {
resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);
}
clearTargetUpdateRecords(resource);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR);
clearTargetUpdateRecords(resource);
ReplacementCleanup.clear(resource);
}
private static void clearTargetUpdateRecords(StackResource resource) {
resource.getAttributes().remove(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR);
DECLARED_TARGETS.clearPrior(resource);
}
/**
* 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.
* Keeps the snapshot of a target group update whose own undo did not complete. The engine restores
* the previous resource and reports the rollback failure once; with the snapshot, a
* ContinueUpdateRollback puts back the registrations the update started from, instead of finding
* nothing to undo.
*/
@Override
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
String snapshot = attempted.getAttributes().get(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR);
if (snapshot != null && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) {
previous.getAttributes().put(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR, snapshot);
}
}
/**
* A replacement is undone through the cleanup record, and a target group's record of its declared
* targets goes back with it, even when deleting the replacement fails. Without a cleanup record, a
* load balancer is moved back to the subnets an update took it off, and a target group gets back
* the registrations the update changed; otherwise neither has anything 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
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
boolean replaced;
try {
replaced = ReplacementCleanup.rollback(resource, this::delete);
} finally {
DECLARED_TARGETS.restorePrior(resource);
}
if (replaced) {
return true;
}
if (LOAD_BALANCER.equals(resource.getResourceType())) {
return restorePriorSubnets(resource);
}
return TARGET_GROUP.equals(resource.getResourceType());
if (TARGET_GROUP.equals(resource.getResourceType())) {
restorePriorRegistrations(resource);
return true;
}
return false;
}
/**
* Deregisters the targets the update registered and registers again the ones it deregistered or
* registered over, as they were registered before it: the undo of a provision that failed, and the
* rollback of one that succeeded when a later resource fails the update. A failed call propagates,
* so the engine reports its reason, a target group gone since the update included, and the
* snapshot stays until a put back succeeds.
*/
private void restorePriorRegistrations(StackResource resource) {
JsonNode saved = CfnRollback.updateSnapshot(resource,
CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR);
if (saved == null) {
return;
}
String arn = resource.getPhysicalId();
String region = AwsArnUtils.parse(arn).region();
List<TargetDescription> added = MAPPER.convertValue(saved.path("added"), TARGET_LIST);
List<TargetDescription> removed = MAPPER.convertValue(saved.path("removed"), TARGET_LIST);
if (!added.isEmpty()) {
elbV2Service.deregisterTargets(region, arn, added);
}
if (!removed.isEmpty()) {
elbV2Service.registerTargets(region, arn, removed);
}
resource.getAttributes().remove(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR);
}
/**
@@ -257,7 +337,15 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
return subnets;
}
private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
/**
* {@code Targets} is not create-only, so an update that keeps the group brings its registrations
* to the template's targets in place (see {@link #reconcileTargets}). When that fails, what it did
* is undone before the failure propagates ({@link CfnRollback#guarded}): a target group this
* provision created, on a create or a replacement, is deleted again, and a kept one gets back the
* registrations it had.
*/
private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx,
Map<String, String> attributesBefore) {
String name = nameOrPrior(ctx.resolveOptional(props, "Name"), r.getAttributes().get("TargetGroupName"),
ctx, r.getLogicalId());
String protocol = ctx.resolveOptional(props, "Protocol");
@@ -276,8 +364,13 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
String matcher = parseMatcher(props, ctx);
String ipAddressType = ctx.resolveOptional(props, "IpAddressType");
Map<String, String> tags = ctx.resolveTags(props, "Tags");
List<TargetDescription> targets = declaredTargets(props, ctx);
// Taken before RegisterTargets fills in the group's port on these targets, so the record
// keeps them as declared.
String declaredRecord = MAPPER.valueToTree(targets).toString();
TargetGroup tg;
boolean created = true;
try {
tg = elbV2Service.createTargetGroup(ctx.region(), name, protocol, protocolVersion, port, vpcId, targetType,
hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
@@ -287,6 +380,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
throw e;
}
tg = elbV2Service.describeTargetGroups(ctx.region(), null, null, List.of(name)).get(0);
created = false;
}
r.setPhysicalId(tg.getTargetGroupArn());
@@ -296,6 +390,107 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
// 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()));
TargetGroup group = tg;
CfnRollback.guarded(r, ctx, created,
() -> elbV2Service.deleteTargetGroup(ctx.region(), group.getTargetGroupArn()),
() -> restorePriorRegistrations(r),
() -> reconcileTargets(r, group, targets, ctx));
DECLARED_TARGETS.record(r, ctx, attributesBefore, declaredRecord);
}
/**
* The template's {@code Targets}. An Fn::If that drops a target, or a member of one, with
* AWS::NoValue leaves it out. {@code Id} is required in a target, so one without it fails the
* resource before anything is created or registered, with the error the resource schema gives.
*/
private static List<TargetDescription> declaredTargets(JsonNode props, ProvisionContext ctx) {
List<TargetDescription> targets = new ArrayList<>();
if (props == null || !props.has("Targets")) {
return targets;
}
JsonNode declared = ctx.engine().resolveNodeOmittingNoValue(props.get("Targets"));
if (declared == null || !declared.isArray()) {
return targets;
}
for (int i = 0; i < declared.size(); i++) {
JsonNode item = declared.get(i);
String id = ctx.resolveOptional(item, "Id");
if (id == null) {
throw new AwsException("InvalidRequest",
"Model validation failed (#/Targets/" + i + ": required key [Id] not found)", 400);
}
TargetDescription target = new TargetDescription();
target.setId(id);
target.setPort(ctx.resolveOptionalInt(item, "Port"));
target.setAvailabilityZone(ctx.resolveOptional(item, "AvailabilityZone"));
targets.add(target);
}
return targets;
}
/**
* Brings the group's registrations to {@code targets}: registers each target that is not
* registered as declared, then deregisters the registered targets the last template declared and
* this one does not (see {@link #DECLARED_TARGETS}). A target is its Id and the port it receives
* traffic on, the group's when it names none, which is how RegisterTargets and DeregisterTargets
* tell registrations apart. RegisterTargets checks every target before registering any, so a
* refused target leaves the group as it was, and the deregistration, of targets that passed those
* checks when they were registered, comes last. An update that keeps the group saves what it
* changed once RegisterTargets has taken the targets, before the deregistration, and
* {@link #restorePriorRegistrations} puts it back from that. A refused target is not in it: the
* save comes after RegisterTargets has accepted every target, so the way back never names a
* target that was never registered.
*/
private void reconcileTargets(StackResource r, TargetGroup tg, List<TargetDescription> targets,
ProvisionContext ctx) {
String arn = tg.getTargetGroupArn();
boolean kept = ctx.reusesPriorEntity(arn);
List<TargetDescription> recorded = kept ? recordedTargets(r) : List.of();
List<TargetDescription> registered = List.copyOf(tg.getTargets());
List<TargetDescription> register = targets.stream()
.filter(target -> registered.stream().noneMatch(existing ->
ElbV2HealthChecker.sameTarget(existing, target, tg)
&& Objects.equals(existing.getAvailabilityZone(), target.getAvailabilityZone())))
.toList();
List<TargetDescription> deregister = registered.stream()
.filter(existing -> containsTarget(recorded, existing, tg) && !containsTarget(targets, existing, tg))
.toList();
if (register.isEmpty() && deregister.isEmpty()) {
return;
}
if (!register.isEmpty()) {
elbV2Service.registerTargets(ctx.region(), arn, register);
}
if (kept) {
List<TargetDescription> removed = new ArrayList<>(deregister);
registered.stream().filter(existing -> containsTarget(register, existing, tg)).forEach(removed::add);
ObjectNode saved = MAPPER.createObjectNode();
saved.set("added", MAPPER.valueToTree(register.stream()
.filter(target -> !containsTarget(registered, target, tg)).toList()));
saved.set("removed", MAPPER.valueToTree(removed));
r.getAttributes().put(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR, saved.toString());
}
if (!deregister.isEmpty()) {
elbV2Service.deregisterTargets(ctx.region(), arn, deregister);
}
}
private static List<TargetDescription> recordedTargets(StackResource r) {
String recorded = DECLARED_TARGETS.read(r.getAttributes());
if (recorded == null) {
return List.of();
}
try {
return MAPPER.readValue(recorded, TARGET_LIST);
} catch (JsonProcessingException e) {
LOG.warnv("Ignoring unreadable Targets record on {0} ({1}): {2}", r.getLogicalId(), e.getMessage(),
recorded);
return List.of();
}
}
private static boolean containsTarget(List<TargetDescription> targets, TargetDescription target, TargetGroup tg) {
return targets.stream().anyMatch(candidate -> ElbV2HealthChecker.sameTarget(candidate, target, tg));
}
/**
@@ -26,6 +26,7 @@ import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
@@ -65,6 +66,14 @@ public class ElbV2HealthChecker implements Resettable {
return 80;
}
/**
* Whether {@code a} and {@code b} are the same registration in {@code tg}: the same Id on the same
* effective port, which is how RegisterTargets and DeregisterTargets tell registrations apart.
*/
public static boolean sameTarget(TargetDescription a, TargetDescription b, TargetGroup tg) {
return Objects.equals(a.getId(), b.getId()) && effectivePort(a, tg) == effectivePort(b, tg);
}
public void startMonitoring(TargetGroup tg) {
if (config.services().elbv2().mock()) {
return;
@@ -1108,8 +1108,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
t.setPort(tg.getPort());
}
// replace if same id+port already registered
existing.removeIf(e -> e.getId().equals(t.getId())
&& ElbV2HealthChecker.effectivePort(e, tg) == ElbV2HealthChecker.effectivePort(t, tg));
existing.removeIf(e -> ElbV2HealthChecker.sameTarget(e, t, tg));
existing.add(t);
}
persistRegion(targetGroups, region);
@@ -1133,8 +1132,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
TargetGroup tg = requireTargetGroup(region, tgArn);
validateLambdaTargetPorts(tg, targets);
for (TargetDescription t : targets) {
tg.getTargets().removeIf(e -> e.getId().equals(t.getId())
&& ElbV2HealthChecker.effectivePort(e, tg) == ElbV2HealthChecker.effectivePort(t, tg));
tg.getTargets().removeIf(e -> ElbV2HealthChecker.sameTarget(e, t, tg));
}
persistRegion(targetGroups, region);
healthChecker.removeTargets(tgArn, targets, tg);
@@ -0,0 +1,125 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.CfnTestStack;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetDescription;
import java.util.Set;
import java.util.stream.Collectors;
import static io.floci.aws.testing.CfnStackWaits.output;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* {@code Targets} on {@code AWS::ElasticLoadBalancingV2::TargetGroup}, read back through the AWS SDK's
* DescribeTargetHealth: the stack registers the declared targets, an update registers the ones the
* template gains and deregisters the ones it drops on the same group, a failed update puts them back,
* whether it failed on the group or on a later resource, and a target registered outside the stack
* stays registered.
*/
@QuarkusTest
class CloudFormationElbV2TargetGroupTargetsIntegrationTest {
@RegisterExtension
final CfnTestStack stack = new CfnTestStack("cfn-tg-targets");
@Test
void ipTargetsFollowTheTemplateThroughChangeRollbackRefusalAndRemoval() {
String arn = createGroup("ip", target("10.0.0.10"));
assertEquals(Set.of("10.0.0.10:80"), registrations(arn));
elb().registerTargets(request -> request.targetGroupArn(arn).targets(target -> target.id("10.0.0.99")));
Stack changed = stack.update(template("ip", false, target("10.0.0.11"), target("10.0.0.12")),
"UPDATE_COMPLETE");
assertEquals(arn, output(changed, "TgArn"));
Set<String> changedTargets = Set.of("10.0.0.11:80", "10.0.0.12:80", "10.0.0.99:80");
assertEquals(changedTargets, registrations(arn));
stack.update(template("ip", true, target("10.0.0.10")), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(changedTargets, registrations(arn));
// RegisterTargets refuses a port out of range, so this update fails on the group itself.
stack.update(template("ip", false, target("10.0.0.11"), target("10.0.0.13", 70000)),
"UPDATE_ROLLBACK_COMPLETE");
assertEquals(changedTargets, registrations(arn));
stack.update(template("ip", false), "UPDATE_COMPLETE");
assertEquals(Set.of("10.0.0.99:80"), registrations(arn));
}
/** An instance registered on two ports is two targets, and an update drops only the one it leaves out. */
@Test
void anInstanceTargetIsItsIdAndPort() {
String first = "i-0aaaaaaaaaaaaaaa1";
String second = "i-0bbbbbbbbbbbbbbb2";
String arn = createGroup("instance", target(first), target(first, 8080), target(second));
assertEquals(Set.of(first + ":80", first + ":8080", second + ":80"), registrations(arn));
stack.update(template("instance", false, target(first, 8080)), "UPDATE_COMPLETE");
assertEquals(Set.of(first + ":8080"), registrations(arn));
}
/** A Lambda target names no port, so the function is the whole target. */
@Test
void aLambdaTargetGroupSwitchesToTheDeclaredFunction() {
String arn = createGroup("lambda", target(functionArn("first")));
assertEquals(Set.of(functionArn("first")), registrations(arn));
stack.update(template("lambda", false, target(functionArn("second"))), "UPDATE_COMPLETE");
assertEquals(Set.of(functionArn("second")), registrations(arn));
}
private ElasticLoadBalancingV2Client elb() {
return stack.client(ElasticLoadBalancingV2Client.builder());
}
/** Creates the stack with a target group of {@code type} declaring {@code targets}, and returns its ARN. */
private String createGroup(String type, String... targets) {
return output(stack.create(template(type, false, targets)), "TgArn");
}
/** The group's registrations, each its Id and, when it has one, its port. */
private Set<String> registrations(String arn) {
return elb().describeTargetHealth(request -> request.targetGroupArn(arn)).targetHealthDescriptions().stream()
.map(description -> {
TargetDescription target = description.target();
return target.port() == null ? target.id() : target.id() + ":" + target.port();
})
.collect(Collectors.toSet());
}
/**
* A target group of {@code type}, on port 80 unless it is a Lambda group, declaring {@code targets},
* or no {@code Targets} when there are none; with a resource that fails after it when
* {@code laterFails}.
*/
private static String template(String type, boolean laterFails, String... targets) {
String port = "lambda".equals(type) ? "" : ", \"Protocol\": \"HTTP\", \"Port\": 80";
String declared = targets.length == 0 ? "" : ", \"Targets\": [" + String.join(", ", targets) + "]";
return """
{"Resources": {
"Tg": {"Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
"Properties": {"TargetType": "%s"%s%s}}%s
}, "Outputs": {"TgArn": {"Value": {"Ref": "Tg"}}}}
""".formatted(type, port, declared, laterFails ? CfnStackWaits.failingResourceAfter("Tg") : "");
}
/** A declared target that names only its Id, so it takes the group's port. */
private static String target(String id) {
return "{\"Id\": \"" + id + "\"}";
}
/** A declared target with a port of its own. */
private static String target(String id, int port) {
return "{\"Id\": \"" + id + "\", \"Port\": " + port + "}";
}
private static String functionArn(String name) {
return "arn:aws:lambda:us-east-1:000000000000:function:" + name;
}
}
@@ -1,15 +1,12 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.CfnTestStack;
import io.floci.aws.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.rds.RdsClient;
@@ -33,74 +30,49 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@TestProfile(RdsMockProfile.class)
class CloudFormationRdsDbInstanceIntegrationTest {
private final String stackName = "cfn-rds-db-" + Long.toString(System.nanoTime(), 36);
private CloudFormationClient cloudFormation;
private RdsClient rds;
@BeforeEach
void clients() {
cloudFormation = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
rds = AwsTestClients.create(RdsClient.builder(), "test", Region.US_EAST_1);
}
@AfterEach
void deleteStack() {
try {
CfnStackWaits.deleteStack(stackName);
} finally {
cloudFormation.close();
rds.close();
}
}
@RegisterExtension
final CfnTestStack stack = new CfnTestStack("cfn-rds-db");
@Test
void securityGroupsFollowTheTemplateThroughChangeRollbackAndRemoval() {
Stack created = create(template("First", false, false));
Stack created = stack.create(template("First", false, false));
String id = output(created, "DbId");
assertEquals(List.of(output(created, "FirstId")), groups(id));
Stack changed = update(template("Second", false, false), "UPDATE_COMPLETE");
Stack changed = stack.update(template("Second", false, false), "UPDATE_COMPLETE");
assertEquals(id, output(changed, "DbId"));
assertEquals(List.of(output(changed, "SecondId")), groups(id));
update(template("First", false, true), "UPDATE_ROLLBACK_COMPLETE");
stack.update(template("First", false, true), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(List.of(output(changed, "SecondId")), groups(id));
// As AWS's handler does, a template that drops the groups puts the instance on its VPC's default group.
Stack cleared = update(template(null, false, false), "UPDATE_COMPLETE");
Stack cleared = stack.update(template(null, false, false), "UPDATE_COMPLETE");
assertEquals(id, output(cleared, "DbId"));
assertEquals(List.of(defaultGroupOf(instance(id).dbSubnetGroup().vpcId())), groups(id));
}
@Test
void aStorageEncryptedChangeReplacesTheInstanceAndAFailedOneKeepsIt() {
String id = output(create(template(null, true, false)), "DbId");
String id = output(stack.create(template(null, true, false)), "DbId");
assertTrue(instance(id).storageEncrypted());
// Dropping StorageEncrypted asks for an unencrypted instance, which only a new one can be.
update(template(null, false, true), "UPDATE_ROLLBACK_COMPLETE");
stack.update(template(null, false, true), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(List.of(id), stackInstanceIds(), "the replacement is deleted again");
assertTrue(instance(id).storageEncrypted());
String unencrypted = output(update(template(null, false, false), "UPDATE_COMPLETE"), "DbId");
String unencrypted = output(stack.update(template(null, false, false), "UPDATE_COMPLETE"), "DbId");
assertNotEquals(id, unencrypted);
assertFalse(instance(unencrypted).storageEncrypted());
assertEquals(List.of(unencrypted), stackInstanceIds(), "the prior instance is deleted once the update commits");
String encrypted = output(update(template(null, true, false), "UPDATE_COMPLETE"), "DbId");
String encrypted = output(stack.update(template(null, true, false), "UPDATE_COMPLETE"), "DbId");
assertNotEquals(unencrypted, encrypted);
assertTrue(instance(encrypted).storageEncrypted());
assertEquals(List.of(encrypted), stackInstanceIds());
}
private Stack create(String template) {
return CfnStackWaits.createStack(cloudFormation, stackName, template, "CREATE_COMPLETE");
}
private Stack update(String template, String expectedStatus) {
return CfnStackWaits.updateStack(cloudFormation, stackName, template, expectedStatus);
}
/**
* Two security groups and a DB instance on {@code group}, First or Second, or on none when it is
* null; with {@code StorageEncrypted: true} when {@code encrypted}, and with a resource that fails
@@ -125,8 +97,12 @@ class CloudFormationRdsDbInstanceIntegrationTest {
laterFails ? CfnStackWaits.failingResourceAfter("Db") : "");
}
private RdsClient rds() {
return stack.client(RdsClient.builder());
}
private DBInstance instance(String id) {
return rds.describeDBInstances(request -> request.dbInstanceIdentifier(id)).dbInstances().getFirst();
return rds().describeDBInstances(request -> request.dbInstanceIdentifier(id)).dbInstances().getFirst();
}
private List<String> groups(String id) {
@@ -135,16 +111,15 @@ class CloudFormationRdsDbInstanceIntegrationTest {
/** The instances this stack's {@code Db} resource has, by the name CloudFormation generates for it. */
private List<String> stackInstanceIds() {
return rds.describeDBInstances().dbInstances().stream().map(DBInstance::dbInstanceIdentifier)
.filter(id -> id.startsWith(stackName + "-db-")).toList();
return rds().describeDBInstances().dbInstances().stream()
.map(DBInstance::dbInstanceIdentifier)
.filter(id -> id.startsWith(stack.name() + "-db-")).toList();
}
private static String defaultGroupOf(String vpcId) {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) {
return ec2.describeSecurityGroups(request -> request.filters(
filter -> filter.name("vpc-id").values(vpcId),
filter -> filter.name("group-name").values("default")))
.securityGroups().getFirst().groupId();
}
private String defaultGroupOf(String vpcId) {
return stack.client(Ec2Client.builder()).describeSecurityGroups(request -> request.filters(
filter -> filter.name("vpc-id").values(vpcId),
filter -> filter.name("group-name").values("default")))
.securityGroups().getFirst().groupId();
}
}
@@ -14,20 +14,24 @@ import io.floci.aws.services.elbv2.model.Listener;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import io.floci.aws.services.elbv2.model.Rule;
import io.floci.aws.services.elbv2.model.RuleCondition;
import io.floci.aws.services.elbv2.model.TargetDescription;
import io.floci.aws.services.elbv2.model.TargetGroup;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.stubbing.Stubber;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -65,10 +69,19 @@ class ElbV2CfnProvisionerTest {
private static final String RULE_ARN = LISTENER_ARN.replace(":listener/", ":listener-rule/") + "/9683b2d02a6cabee";
private static final List<String> TWO_SUBNETS = List.of("subnet-1", "subnet-2");
private static final String DECLARED_TARGETS = "__FlociTargetGroupTargets";
private static final String DECLARED_TARGETS_PRIOR = "__FlociTargetGroupTargetsPrior";
private static final String TARGETS_SNAPSHOT = CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR;
private final ElbV2Service elb = mock(ElbV2Service.class);
private final ElbV2CfnProvisioner provisioner = new ElbV2CfnProvisioner(elb);
private final ObjectMapper mapper = new ObjectMapper();
/** The target group the Targets tests provision: on port 80, nothing registered until a test registers targets. */
private final TargetGroup group = targetGroupOnPort80();
/** The stack resource the target group tests provision. */
private final StackResource tgResource = resource("AWS::ElasticLoadBalancingV2::TargetGroup", "Tg");
/** The previous resource the engine restores when a target group update fails. */
private final StackResource restored = new StackResource();
@BeforeEach
void defaultListenerLoadBalancer() {
@@ -267,14 +280,13 @@ class ElbV2CfnProvisionerTest {
.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());
provisioner.provision(tgResource, 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"));
assertEquals(TG_ARN, tgResource.getPhysicalId());
assertEquals(Set.of("TargetGroupArn", "TargetGroupName", "TargetGroupFullName", "LoadBalancerArns",
DECLARED_TARGETS), tgResource.getAttributes().keySet());
assertEquals("targetgroup/web-tg/73e2d6bc24d8a067", tgResource.getAttributes().get("TargetGroupFullName"));
assertEquals(LB_ARN, tgResource.getAttributes().get("LoadBalancerArns"));
}
@Test
@@ -1007,43 +1019,389 @@ class ElbV2CfnProvisionerTest {
}
private void assertRejected(String property, String value) {
StackResource r = resource("AWS::ElasticLoadBalancingV2::TargetGroup", "Tg");
ObjectNode props = mapper.createObjectNode().put("Name", "web-tg").put(property, value);
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(tgResource, props, ctx()));
assertEquals("ValidationError", e.getErrorCode());
assertEquals("Value of property " + property + " must be an integer.", e.getMessage());
assertNull(r.getPhysicalId());
verify(elb, never()).createTargetGroup(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any(), any(), any());
assertNull(tgResource.getPhysicalId());
anyCreateTargetGroup(verify(elb, never()));
}
@Test
void anIntegerAnIntrinsicResolvesToNothingReachesTheServiceUnset() {
// Fn::If [cond, 30, AWS::NoValue] drops the property; the engine resolves AWS::NoValue to blank.
when(elb.createTargetGroup(eq(REGION), eq("fn-tg"), isNull(), isNull(), isNull(), isNull(), eq("lambda"),
isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
eq(Map.of()))).thenReturn(targetGroup("fn-tg"));
ObjectNode props = mapper.createObjectNode().put("Name", "fn-tg").put("TargetType", "lambda");
ObjectNode props = lambdaGroup();
props.putObject("HealthCheckIntervalSeconds").put("Ref", "AWS::NoValue");
StackResource r = resource("AWS::ElasticLoadBalancingV2::TargetGroup", "Tg");
provisioner.provision(r, props, ctx());
assertEquals(TG_ARN, r.getPhysicalId());
assertCreatedWithEveryOptionalUnset(props);
}
@Test
void absentTargetGroupIntegersReachTheServiceUnset() {
assertCreatedWithEveryOptionalUnset(lambdaGroup());
}
/** Properties of a Lambda target group that name only the group and its type. */
private ObjectNode lambdaGroup() {
return mapper.createObjectNode().put("Name", "fn-tg").put("TargetType", "lambda");
}
/**
* Provisions {@code props}, a Lambda group named fn-tg, and asserts the group was created, which the
* stub allows only when CreateTargetGroup got every optional argument unset.
*/
private void assertCreatedWithEveryOptionalUnset(ObjectNode props) {
when(elb.createTargetGroup(eq(REGION), eq("fn-tg"), isNull(), isNull(), isNull(), isNull(), eq("lambda"),
isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
eq(Map.of()))).thenReturn(targetGroup("fn-tg"));
StackResource r = resource("AWS::ElasticLoadBalancingV2::TargetGroup", "Tg");
provisioner.provision(r, mapper.createObjectNode().put("Name", "fn-tg").put("TargetType", "lambda"), ctx());
provisioner.provision(tgResource, props, ctx());
assertEquals(TG_ARN, r.getPhysicalId());
assertEquals(TG_ARN, tgResource.getPhysicalId());
}
/** A target as the group and the record carry it: its Id, port and zone, the last two null when unset. */
private TargetDescription target(String id, Integer port, String zone) {
return mapper.convertValue(mapper.createObjectNode().put("id", id).put("port", port)
.put("availabilityZone", zone), TargetDescription.class);
}
private TargetDescription target(String id) {
return target(id, null, null);
}
private static List<String> described(List<TargetDescription> targets) {
return targets.stream().map(t -> t.getId() + ":" + t.getPort() + ":" + t.getAvailabilityZone()).toList();
}
private String recordOf(TargetDescription... targets) {
return mapper.valueToTree(List.of(targets)).toString();
}
/** Target group properties declaring {@code targets}, or no Targets when there are none. */
private ObjectNode declaring(TargetDescription... targets) {
ObjectNode props = mapper.createObjectNode().put("Name", "web-tg").put("Port", "80");
if (targets.length > 0) {
ArrayNode list = props.putArray("Targets");
for (TargetDescription target : targets) {
ObjectNode item = list.addObject().put("Id", target.getId());
if (target.getPort() != null) {
item.put("Port", String.valueOf(target.getPort()));
}
if (target.getAvailabilityZone() != null) {
item.put("AvailabilityZone", target.getAvailabilityZone());
}
}
}
return props;
}
private TargetGroup targetGroupOnPort80() {
TargetGroup tg = targetGroup("web-tg");
tg.setPort(80);
return tg;
}
/** Replaces what is registered on {@link #group}. */
private void registered(List<TargetDescription> targets) {
group.getTargets().clear();
group.getTargets().addAll(targets);
}
/** CreateTargetGroup with any arguments, called on {@code service}: the mock, or a verification of it. */
private static TargetGroup anyCreateTargetGroup(ElbV2Service service) {
return service.createTargetGroup(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any(), any(), any());
}
/** Provisions {@link #tgResource} as {@link #group}, which the provision creates, declaring {@code targets}. */
private void createdTargetGroupDeclaring(ProvisionContext ctx, TargetDescription... targets) {
when(anyCreateTargetGroup(elb)).thenReturn(group);
provisioner.provision(tgResource, declaring(targets), ctx);
}
/**
* Provisions an update of {@link #tgResource}, whose group the stack keeps with {@code onTheGroup}
* registered, to {@code props}, with {@code record} as the targets the last template declared, or
* none recorded when it is null.
*/
private void keptTargetGroupUpdatedTo(List<TargetDescription> onTheGroup, ObjectNode props, String record) {
registered(onTheGroup);
when(anyCreateTargetGroup(elb)).thenThrow(new AwsException("DuplicateTargetGroupName", "exists", 400));
when(elb.describeTargetGroups(REGION, null, null, List.of("web-tg"))).thenReturn(List.of(group));
tgResource.setPhysicalId(TG_ARN);
tgResource.getAttributes().put("TargetGroupName", "web-tg");
if (record != null) {
tgResource.getAttributes().put(DECLARED_TARGETS, record);
}
provisioner.provision(tgResource, props, ctx(TG_ARN));
}
/**
* An update of the kept group from a template declaring 10.0.0.1 to one declaring 10.0.0.2, with
* 10.0.0.1 and 10.0.0.9, registered outside the stack, on the group.
*/
private void keptGroupSwitchedToASecondTarget() {
keptTargetGroupUpdatedTo(List.of(target("10.0.0.1", 80, null), target("10.0.0.9", 80, null)),
declaring(target("10.0.0.2")), recordOf(target("10.0.0.1")));
}
/** {@link #keptGroupSwitchedToASecondTarget}, checked to leave the snapshot and prior record for a later step. */
private void keptGroupSwitchedLeavingItsRecords() {
keptGroupSwitchedToASecondTarget();
assertTrue(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT));
assertTrue(tgResource.getAttributes().containsKey(DECLARED_TARGETS_PRIOR));
}
/** Asserts that 10.0.0.2 was registered and deregistered again, and 10.0.0.1 deregistered and registered again. */
private void assertSecondTargetSwappedBack() {
assertEquals(List.of("10.0.0.2:null:null", "10.0.0.1:80:null"), registeredBy(2));
assertEquals(List.of("10.0.0.1:80:null", "10.0.0.2:null:null"), deregisteredBy(2));
}
private static AwsException internalFailure() {
return new AwsException("InternalFailure", "storage failed", 500);
}
/** Makes deleting {@link #group} fail, and returns the failure. */
private AwsException failingGroupDelete() {
AwsException deleteFailure = internalFailure();
doThrow(deleteFailure).when(elb).deleteTargetGroup(REGION, TG_ARN);
return deleteFailure;
}
/** Makes the first RegisterTargets call refuse its targets, as it refuses a port out of range, and returns it. */
private AwsException refusingRegistration() {
AwsException refusal = new AwsException("ValidationError", "port out of range", 400);
doThrow(refusal).doNothing().when(elb).registerTargets(eq(REGION), eq(TG_ARN), anyList());
return refusal;
}
/** Makes DeregisterTargets throw {@code failure} on its first {@code calls} calls, and returns it. */
private AwsException failingDeregistration(AwsException failure, int calls) {
Stubber stub = doThrow(failure);
for (int i = 1; i < calls; i++) {
stub = stub.doThrow(failure);
}
stub.doNothing().when(elb).deregisterTargets(eq(REGION), eq(TG_ARN), anyList());
return failure;
}
private List<String> registeredBy(int calls) {
return targetsSentBy(calls,
(service, sent) -> service.registerTargets(eq(REGION), eq(TG_ARN), sent.capture()));
}
private List<String> deregisteredBy(int calls) {
return targetsSentBy(calls,
(service, sent) -> service.deregisterTargets(eq(REGION), eq(TG_ARN), sent.capture()));
}
/** The targets handed to {@code call}, made on a verification of the mock, over its {@code calls} calls. */
@SuppressWarnings("unchecked")
private List<String> targetsSentBy(int calls,
BiConsumer<ElbV2Service, ArgumentCaptor<List<TargetDescription>>> call) {
ArgumentCaptor<List<TargetDescription>> sent = ArgumentCaptor.forClass(List.class);
call.accept(verify(elb, times(calls)), sent);
return sent.getAllValues().stream().flatMap(targets -> described(targets).stream()).toList();
}
@Test
void aCreatedTargetGroupRegistersTheDeclaredTargetsAndRecordsThem() {
createdTargetGroupDeclaring(ctx(), target("i-1"), target("i-1", 8080, null));
assertEquals(List.of("i-1:null:null", "i-1:8080:null"), registeredBy(1));
verify(elb, never()).deregisterTargets(any(), any(), any());
assertEquals(recordOf(target("i-1"), target("i-1", 8080, null)),
tgResource.getAttributes().get(DECLARED_TARGETS));
assertFalse(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT), "a create has nothing to roll back");
}
@Test
void aTargetWithoutAnIdFailsBeforeTheGroupIsCreated() {
ObjectNode props = declaring();
props.putArray("Targets").addObject().put("Port", "80");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(tgResource, props, ctx()));
assertEquals("InvalidRequest", e.getErrorCode());
assertEquals("Model validation failed (#/Targets/0: required key [Id] not found)", e.getMessage());
anyCreateTargetGroup(verify(elb, never()));
}
@Test
void refusedTargetsDeleteTheGroupThisProvisionCreated() {
AwsException refusal = refusingRegistration();
AwsException deleteFailure = failingGroupDelete();
AwsException e = assertThrows(AwsException.class,
() -> createdTargetGroupDeclaring(ctx(), target("10.0.0.5", 70000, null)));
assertEquals(refusal, e);
assertEquals(List.of(deleteFailure), List.of(e.getSuppressed()));
verify(elb).deleteTargetGroup(REGION, TG_ARN);
// A group whose delete failed stays marked as the stack's, so the stack's rollback deletes it.
assertEquals(TG_ARN, tgResource.getPhysicalId());
assertEquals("true", tgResource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
}
@Test
void aTargetRefusedOnAKeptGroupIsNotDeregisteredOnTheWayBack() {
AwsException refusal = refusingRegistration();
assertEquals(refusal, assertThrows(AwsException.class, this::keptGroupSwitchedToASecondTarget));
// RegisterTargets registered nothing, so the way back has nothing to deregister.
verify(elb, never()).deregisterTargets(any(), any(), any());
verify(elb, never()).deleteTargetGroup(any(), any());
assertFalse(tgResource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void aFailedDeregistrationPutsAKeptGroupBack() {
AwsException failure = failingDeregistration(internalFailure(), 1);
assertEquals(failure, assertThrows(AwsException.class, this::keptGroupSwitchedToASecondTarget));
assertSecondTargetSwappedBack();
verify(elb, never()).deleteTargetGroup(any(), any());
assertFalse(tgResource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void anUndoThatFailsLeavesItsSnapshotForTheRestoredResource() {
failingDeregistration(internalFailure(), 2);
assertThrows(AwsException.class, this::keptGroupSwitchedToASecondTarget);
provisioner.mergeFailedUpdateResourceTracking(restored, tgResource);
assertTrue(tgResource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
assertTrue(restored.getAttributes().containsKey(TARGETS_SNAPSHOT));
assertEquals(tgResource.getAttributes().get(TARGETS_SNAPSHOT), restored.getAttributes().get(TARGETS_SNAPSHOT));
}
@Test
void aSnapshotWithoutAFailedUndoStaysWithTheFailedAttempt() {
tgResource.getAttributes().put(TARGETS_SNAPSHOT, "{\"added\":[],\"removed\":[]}");
provisioner.mergeFailedUpdateResourceTracking(restored, tgResource);
assertFalse(restored.getAttributes().containsKey(TARGETS_SNAPSHOT));
}
@Test
void aReplacementRegistersOnTheNewGroupAndItsRollbackRestoresTheRecordEvenWhenTheDeleteFails() {
String priorArn = TG_ARN.replace("web-tg/73e2d6bc24d8a067", "old-tg/0123456789abcdef");
tgResource.setPhysicalId(priorArn);
tgResource.getAttributes().put(DECLARED_TARGETS, recordOf(target("10.0.0.1")));
createdTargetGroupDeclaring(ctx(priorArn), target("10.0.0.2"));
assertEquals(TG_ARN, tgResource.getPhysicalId());
assertEquals(List.of("10.0.0.2:null:null"), registeredBy(1));
verify(elb, never()).deregisterTargets(any(), any(), any());
assertFalse(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT), "the new group has nothing to put back");
failingGroupDelete();
AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(tgResource));
assertEquals("InternalFailure", e.getErrorCode(), "the replacement's delete failed");
assertEquals(priorArn, tgResource.getPhysicalId());
assertEquals(recordOf(target("10.0.0.1")), tgResource.getAttributes().get(DECLARED_TARGETS));
assertFalse(tgResource.getAttributes().containsKey(DECLARED_TARGETS_PRIOR));
}
@Test
void anUpdateSwapsTheDeclaredTargetsAndARollbackSwapsThemBack() {
keptGroupSwitchedToASecondTarget();
assertEquals(List.of("10.0.0.2:null:null"), registeredBy(1));
assertEquals(List.of("10.0.0.1:80:null"), deregisteredBy(1), "the target registered outside the stack stays");
InOrder order = inOrder(elb);
order.verify(elb).registerTargets(eq(REGION), eq(TG_ARN), anyList());
order.verify(elb).deregisterTargets(eq(REGION), eq(TG_ARN), anyList());
assertEquals(recordOf(target("10.0.0.2")), tgResource.getAttributes().get(DECLARED_TARGETS));
assertTrue(provisioner.rollbackUpdate(tgResource));
assertSecondTargetSwappedBack();
assertEquals(recordOf(target("10.0.0.1")), tgResource.getAttributes().get(DECLARED_TARGETS));
assertFalse(tgResource.getAttributes().containsKey(DECLARED_TARGETS_PRIOR));
assertFalse(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT));
}
@Test
void aTargetDeclaredInAnotherZoneIsRegisteredOverAndARollbackPutsTheZoneBack() {
keptTargetGroupUpdatedTo(List.of(target("10.0.0.1", 80, null)), declaring(target("10.0.0.1", null, "all")),
recordOf(target("10.0.0.1")));
assertEquals(List.of("10.0.0.1:null:all"), registeredBy(1));
verify(elb, never()).deregisterTargets(any(), any(), any());
assertTrue(provisioner.rollbackUpdate(tgResource));
assertEquals(List.of("10.0.0.1:null:all", "10.0.0.1:80:null"), registeredBy(2));
verify(elb, never()).deregisterTargets(any(), any(), any());
}
@ParameterizedTest
@NullSource
@ValueSource(strings = "not json")
void aGroupWithNoReadableRecordRegistersItsTargetsAndDeregistersNothing(String record) {
// Provisioned before Floci registered targets, or with a record that cannot be read, so nothing
// registered is known to be the stack's.
keptTargetGroupUpdatedTo(List.of(target("10.0.0.1", 80, null)), declaring(target("10.0.0.2")), record);
assertEquals(List.of("10.0.0.2:null:null"), registeredBy(1));
verify(elb, never()).deregisterTargets(any(), any(), any());
assertEquals(recordOf(target("10.0.0.2")), tgResource.getAttributes().get(DECLARED_TARGETS));
}
@Test
void droppingTargetsDeregistersOnlyTheDeclaredOnes() {
keptTargetGroupUpdatedTo(List.of(target("i-1", 80, null), target("i-1", 8080, null), target("i-2", 80, null)),
declaring(), recordOf(target("i-1"), target("i-2", 80, null)));
assertEquals(List.of("i-1:80:null", "i-2:80:null"), deregisteredBy(1));
verify(elb, never()).registerTargets(any(), any(), any());
assertEquals("[]", tgResource.getAttributes().get(DECLARED_TARGETS));
}
@Test
void anUpdateThatChangesNoRegistrationDropsAnEarlierSnapshotAndHasNothingToRollBack() {
keptGroupSwitchedLeavingItsRecords();
registered(List.of(target("10.0.0.2", 80, null), target("10.0.0.9", 80, null)));
provisioner.provision(tgResource, declaring(target("10.0.0.2", 80, null)), ctx(TG_ARN));
assertFalse(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT));
assertTrue(provisioner.rollbackUpdate(tgResource));
assertEquals(List.of("10.0.0.2:null:null"), registeredBy(1));
assertEquals(List.of("10.0.0.1:80:null"), deregisteredBy(1));
}
@Test
void aRollbackOfAGroupGoneSinceTheUpdateFailsAndKeepsTheSnapshot() {
keptGroupSwitchedToASecondTarget();
failingDeregistration(new AwsException("TargetGroupNotFound", "gone", 400), 1);
AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(tgResource));
assertEquals("TargetGroupNotFound", e.getErrorCode());
assertTrue(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT), "a retried rollback tries again");
}
@Test
void aCommittedUpdateSpendsTheTargetSnapshotAndPriorRecord() {
keptGroupSwitchedLeavingItsRecords();
provisioner.completeUpdate(tgResource);
assertFalse(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT));
assertFalse(tgResource.getAttributes().containsKey(DECLARED_TARGETS_PRIOR));
assertEquals(recordOf(target("10.0.0.2")), tgResource.getAttributes().get(DECLARED_TARGETS));
}
@Test
@@ -0,0 +1,77 @@
package io.floci.aws.testing;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.client.builder.AwsSyncClientBuilder;
import software.amazon.awssdk.core.SdkClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A CloudFormation stack a test creates and updates through the SDK, and the SDK clients the test
* reads its resources back through, all with the {@code test} credentials in {@code us-east-1}. After
* each test the stack is deleted, once the test created it, and the clients are closed.
*
* <pre>{@code
* @RegisterExtension
* final CfnTestStack stack = new CfnTestStack("cfn-rds-db");
* ...
* Stack created = stack.create(template);
* stack.client(RdsClient.builder()).describeDBInstances();
* }</pre>
*/
public final class CfnTestStack implements AfterEachCallback {
private final String name;
private final Map<Class<?>, SdkClient> clients = new LinkedHashMap<>();
private boolean created;
/** A stack named {@code namePrefix} plus a suffix unique to the test. */
public CfnTestStack(String namePrefix) {
this.name = namePrefix + "-" + Long.toString(System.nanoTime(), 36);
}
public String name() {
return name;
}
/** Creates the stack from {@code template} and waits for CREATE_COMPLETE. */
public Stack create(String template) {
created = true;
return CfnStackWaits.createStack(client(CloudFormationClient.builder()), name, template, "CREATE_COMPLETE");
}
/** Updates the stack to {@code template} and waits for {@code expectedStatus}. */
public Stack update(String template, String expectedStatus) {
return CfnStackWaits.updateStack(client(CloudFormationClient.builder()), name, template, expectedStatus);
}
/**
* The client {@code builder} builds: made on the test's first call for that kind of builder and
* handed back on every later one, whatever that builder sets, so a test asks for it where it uses
* it. Closed after the test.
*/
@SuppressWarnings("unchecked")
public <B extends AwsClientBuilder<B, C> & AwsSyncClientBuilder<B, C>, C extends SdkClient> C client(B builder) {
return (C) clients.computeIfAbsent(builder.getClass(),
type -> AwsTestClients.create(builder, "test", Region.US_EAST_1));
}
@Override
public void afterEach(ExtensionContext context) {
try {
if (created) {
CfnStackWaits.deleteStack(name);
}
} finally {
clients.values().forEach(SdkClient::close);
clients.clear();
created = false;
}
}
}
@@ -350,7 +350,6 @@ AWS::ElasticLoadBalancingV2::LoadBalancer LoadBalancerAttributes accepted and ig
AWS::ElasticLoadBalancingV2::LoadBalancer MinimumLoadBalancerCapacity accepted and ignored
AWS::ElasticLoadBalancingV2::TargetGroup TargetControlPort accepted and ignored
AWS::ElasticLoadBalancingV2::TargetGroup TargetGroupAttributes accepted and ignored
AWS::ElasticLoadBalancingV2::TargetGroup Targets accepted and ignored
AWS::Events::Archive KmsKeyIdentifier documented as ignored (docs/services/cloudformation.md, EventBridge)
AWS::Events::EventBus DeadLetterConfig rejected with a ValidationError, not supported by Floci
AWS::Events::EventBus KmsKeyIdentifier rejected with a ValidationError, not supported by Floci
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
350 AWS::ElasticLoadBalancingV2::LoadBalancer MinimumLoadBalancerCapacity accepted and ignored
351 AWS::ElasticLoadBalancingV2::TargetGroup TargetControlPort accepted and ignored
352 AWS::ElasticLoadBalancingV2::TargetGroup TargetGroupAttributes accepted and ignored
AWS::ElasticLoadBalancingV2::TargetGroup Targets accepted and ignored
353 AWS::Events::Archive KmsKeyIdentifier documented as ignored (docs/services/cloudformation.md, EventBridge)
354 AWS::Events::EventBus DeadLetterConfig rejected with a ValidationError, not supported by Floci
355 AWS::Events::EventBus KmsKeyIdentifier rejected with a ValidationError, not supported by Floci