fix(cloudformation): apply target group health updates (#8948)

Updating a target group's health check settings through CloudFormation now applies them to the existing group through ModifyTargetGroup. The prior settings are saved before the change and restored on a failed provision or a stack rollback, independently of the target registrations, and a failed undo keeps its snapshot for a retry. Properties the template omits keep their values.

A change to the health check interval replaces the group's probe timer, keeping target health, and a superseded timer's callback is ignored.

Closes #8900
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-23 20:09:29 -04:00
1 parent 39290aa8be
commit d4bbb1bf96
7 files changed
+373 -12

No files matched your search

@@ -0,0 +1,99 @@
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.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.Matcher;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetGroup;
import static io.floci.aws.testing.CfnStackWaits.output;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class CloudFormationTargetGroupHealthIntegrationTest {
@RegisterExtension
final CfnTestStack stack = new CfnTestStack("cfn-tg-health");
@ParameterizedTest
@ValueSource(booleans = {false, true})
void failedUpdateRestoresHealthAndRetainsTheGroup(boolean laterResourceFails) {
String arn = output(stack.create(template(false)), "GroupArn");
ElasticLoadBalancingV2Client elb = stack.client(ElasticLoadBalancingV2Client.builder());
TargetGroup before = elb.describeTargetGroups(request -> request.targetGroupArns(arn))
.targetGroups().getFirst();
stack.update(template(true, laterResourceFails, !laterResourceFails), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(before, elb.describeTargetGroups(request -> request.targetGroupArns(arn))
.targetGroups().getFirst());
assertEquals(arn, physicalId());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void updatesHealthSettingsInPlace(boolean directApiControl) {
String arn = output(stack.create(template(false)), "GroupArn");
ElasticLoadBalancingV2Client elb = stack.client(ElasticLoadBalancingV2Client.builder());
TargetGroup before = elb.describeTargetGroups(request -> request.targetGroupArns(arn))
.targetGroups().getFirst();
assertEquals("TCP", before.healthCheckProtocolAsString());
assertEquals("7777", before.healthCheckPort());
if (directApiControl) {
elb.modifyTargetGroup(request -> request.targetGroupArn(arn)
.healthCheckProtocol("HTTP").healthCheckPort("8888")
.healthCheckPath("/ready").healthCheckIntervalSeconds(15)
.healthCheckTimeoutSeconds(4).healthyThresholdCount(4).unhealthyThresholdCount(5)
.matcher(Matcher.builder().httpCode("200-299").build()));
} else {
stack.update(template(true), "UPDATE_COMPLETE");
}
TargetGroup after = elb.describeTargetGroups(request -> request.targetGroupArns(arn))
.targetGroups().getFirst();
assertAll(
() -> assertEquals(arn, physicalId()),
() -> assertEquals("HTTP", after.healthCheckProtocolAsString()),
() -> assertEquals("8888", after.healthCheckPort()),
() -> assertEquals("/ready", after.healthCheckPath()),
() -> assertEquals(15, after.healthCheckIntervalSeconds()),
() -> assertEquals(4, after.healthCheckTimeoutSeconds()),
() -> assertEquals(4, after.healthyThresholdCount()),
() -> assertEquals(5, after.unhealthyThresholdCount()),
() -> assertEquals("200-299", after.matcher().httpCode()));
}
private String physicalId() {
return stack.client(CloudFormationClient.builder()).describeStackResource(request ->
request.stackName(stack.name()).logicalResourceId("Group")).stackResourceDetail().physicalResourceId();
}
private static String template(boolean updated) {
return template(updated, false, false);
}
private static String template(boolean updated, boolean laterFails, boolean invalidTarget) {
String health = updated ? """
"HealthCheckProtocol":"HTTP","HealthCheckPort":"8888","HealthCheckPath":"/ready",
"HealthCheckIntervalSeconds":15,"HealthCheckTimeoutSeconds":4,
"HealthyThresholdCount":4,"UnhealthyThresholdCount":5,"Matcher":{"HttpCode":"200-299"}
""" : """
"HealthCheckProtocol":"TCP","HealthCheckPort":"7777"
""";
return """
{"Resources":{
"Vpc":{"Type":"AWS::EC2::VPC","Properties":{"CidrBlock":"10.99.0.0/16"}},
"Group":{"Type":"AWS::ElasticLoadBalancingV2::TargetGroup","Properties":{
"Protocol":"TCP","Port":25,"TargetType":"ip","VpcId":{"Ref":"Vpc"},%s%s}}%s
}, "Outputs":{"GroupArn":{"Value":{"Ref":"Group"}}}}
""".formatted(health,
invalidTarget ? ",\"Targets\":[{\"Id\":\"10.99.0.10\",\"Port\":70000}]" : "",
laterFails ? CfnStackWaits.failingResourceAfter("Group") : "");
}
}
@@ -72,6 +72,7 @@ class ElbV2CfnProvisionerTest {
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 static final String HEALTH_SNAPSHOT = ElbV2CfnProvisioner.HEALTH_UPDATE_SNAPSHOT_ATTR;
private final ElbV2Service elb = mock(ElbV2Service.class);
private final ElbV2CfnProvisioner provisioner = new ElbV2CfnProvisioner(elb);
@@ -1104,6 +1105,152 @@ class ElbV2CfnProvisionerTest {
return tg;
}
private void priorHealth() {
group.setHealthCheckProtocol("TCP");
group.setHealthCheckPort("traffic-port");
group.setHealthCheckEnabled(true);
group.setHealthCheckPath("/");
group.setHealthCheckIntervalSeconds(30);
group.setHealthCheckTimeoutSeconds(5);
group.setHealthyThresholdCount(5);
group.setUnhealthyThresholdCount(2);
group.setMatcher("200");
}
private ObjectNode changedHealth(TargetDescription... targets) {
ObjectNode props = declaring(targets).put("HealthCheckProtocol", "HTTP")
.put("HealthCheckPort", "8888").put("HealthCheckEnabled", false)
.put("HealthCheckPath", "/ready").put("HealthCheckIntervalSeconds", 15)
.put("HealthCheckTimeoutSeconds", 4).put("HealthyThresholdCount", 4)
.put("UnhealthyThresholdCount", 5);
props.putObject("Matcher").put("HttpCode", "200-299");
return props;
}
private void verifyHealthRestored(int calls) {
verify(elb, times(calls)).modifyTargetGroup(REGION, TG_ARN, "TCP", "traffic-port", true,
"/", 30, 5, 5, 2, "200");
}
@Test
void keptGroupUpdatesHealthAndRetainsSnapshotUntilCommit() {
priorHealth();
keptTargetGroupUpdatedTo(List.of(), changedHealth(), null);
verify(elb).modifyTargetGroup(REGION, TG_ARN, "HTTP", "8888", false,
"/ready", 15, 4, 4, 5, "200-299");
assertTrue(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
provisioner.completeUpdate(tgResource);
assertFalse(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
provisioner.rollbackUpdate(tgResource);
verifyHealthRestored(0);
}
@Test
void omittedHealthFieldsRemainUnsetInTheUpdate() {
priorHealth();
keptTargetGroupUpdatedTo(List.of(), declaring().put("HealthCheckPath", "/ready"), null);
verify(elb).modifyTargetGroup(REGION, TG_ARN, null, null, null,
"/ready", null, null, null, null, null);
assertTrue(provisioner.rollbackUpdate(tgResource));
verifyHealthRestored(1);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void createOrDuplicateWithoutPriorOwnershipDoesNotModifyHealth(boolean duplicate) {
priorHealth();
if (duplicate) {
when(anyCreateTargetGroup(elb)).thenThrow(new AwsException("DuplicateTargetGroupName", "exists", 400));
when(elb.describeTargetGroups(REGION, null, null, List.of("web-tg"))).thenReturn(List.of(group));
} else {
when(anyCreateTargetGroup(elb)).thenReturn(group);
}
provisioner.provision(tgResource, changedHealth().put("Name", "web-tg"), ctx());
verify(elb, never()).modifyTargetGroup(any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any());
assertFalse(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
}
@Test
void registrationFailureRestoresHealthImmediately() {
priorHealth();
AwsException refusal = refusingRegistration();
assertEquals(refusal, assertThrows(AwsException.class, () -> keptTargetGroupUpdatedTo(
List.of(), changedHealth(target("10.0.0.5", 70000, null)), null)));
verifyHealthRestored(1);
assertFalse(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
verify(elb, never()).deleteTargetGroup(any(), any());
}
@Test
void laterRollbackRestoresBothHealthAndRegistrations() {
priorHealth();
keptTargetGroupUpdatedTo(List.of(target("10.0.0.1", 80, null)),
changedHealth(target("10.0.0.2")), recordOf(target("10.0.0.1")));
assertTrue(provisioner.rollbackUpdate(tgResource));
assertSecondTargetSwappedBack();
verifyHealthRestored(1);
assertFalse(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
}
@Test
void failedHealthUndoSurvivesRestoringThePreviousResourceAndCanBeRetried() {
priorHealth();
doThrow(internalFailure()).doNothing().when(elb).modifyTargetGroup(REGION, TG_ARN,
"TCP", "traffic-port", true, "/", 30, 5, 5, 2, "200");
refusingRegistration();
assertThrows(AwsException.class, () -> keptTargetGroupUpdatedTo(
List.of(), changedHealth(target("10.0.0.5", 70000, null)), null));
assertTrue(tgResource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
restored.setPhysicalId(TG_ARN);
restored.setResourceType(tgResource.getResourceType());
provisioner.mergeFailedUpdateResourceTracking(restored, tgResource);
assertTrue(restored.getAttributes().containsKey(HEALTH_SNAPSHOT));
assertTrue(provisioner.rollbackUpdate(restored));
verifyHealthRestored(2);
assertFalse(restored.getAttributes().containsKey(HEALTH_SNAPSHOT));
}
@Test
void failedRegistrationUndoStillRestoresHealthAndRetainsRegistrationRetry() {
priorHealth();
keptTargetGroupUpdatedTo(List.of(target("10.0.0.1", 80, null)),
changedHealth(target("10.0.0.2")), recordOf(target("10.0.0.1")));
failingDeregistration(internalFailure(), 1);
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(tgResource));
verifyHealthRestored(1);
assertFalse(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
assertTrue(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT));
assertTrue(provisioner.rollbackUpdate(tgResource));
verifyHealthRestored(1);
assertFalse(tgResource.getAttributes().containsKey(TARGETS_SNAPSHOT));
}
@Test
void mutationBeforePersistenceFailureStillRestoresThePriorHealthSnapshot() {
priorHealth();
Mockito.doAnswer(invocation -> {
group.setHealthCheckProtocol("HTTP");
group.setHealthCheckPort("8888");
throw internalFailure();
}).when(elb).modifyTargetGroup(REGION, TG_ARN, "HTTP", "8888", false,
"/ready", 15, 4, 4, 5, "200-299");
assertThrows(AwsException.class, () -> keptTargetGroupUpdatedTo(List.of(), changedHealth(), null));
verifyHealthRestored(1);
assertFalse(tgResource.getAttributes().containsKey(HEALTH_SNAPSHOT));
}
/** Replaces what is registered on {@link #group}. */
private void registered(List<TargetDescription> targets) {
group.getTargets().clear();
@@ -36,11 +36,14 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -48,6 +51,35 @@ class ElbV2HealthCheckerTest {
private final Vertx vertx = Vertx.vertx();
@Test
void replacingMonitoringCancelsPreviousTimerAndIgnoresItsCallback() {
Vertx timers = mock(Vertx.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
WorkerExecutor workers = mock(WorkerExecutor.class);
when(timers.createSharedWorkerExecutor(any(), anyInt())).thenReturn(workers);
List<Handler<Long>> callbacks = new ArrayList<>();
when(timers.setPeriodic(anyLong(), any())).thenAnswer(call -> {
callbacks.add(call.getArgument(1));
return (long) callbacks.size();
});
ElbV2HealthChecker checker = spy(
new ElbV2HealthChecker(timers, config, mock(Ec2Service.class)));
TargetGroup group = targetGroup(8080, "200", 1, 1);
group.setHealthCheckIntervalSeconds(30);
checker.startMonitoring(group);
group.setHealthCheckIntervalSeconds(7);
checker.startMonitoring(group);
verify(timers).setPeriodic(eq(30_000L), any());
verify(timers).setPeriodic(eq(7_000L), any());
verify(timers).cancelTimer(1L);
callbacks.getFirst().handle(1L);
verify(checker, never()).probeAll(group.getTargetGroupArn(), group);
callbacks.get(1).handle(2L);
verify(checker).probeAll(group.getTargetGroupArn(), group);
checker.stopMonitoring(group.getTargetGroupArn());
verify(timers).cancelTimer(2L);
}
@AfterEach
void closeVertx() {
vertx.close().toCompletionStage().toCompletableFuture().join();
@@ -103,6 +103,22 @@ class ElbV2ServiceTest {
private ElbV2Service service;
@Test
void intervalUpdateAndRollbackRescheduleMonitoring() {
String arn = createTargetGroup("interval-update");
TargetGroup group = service.describeTargetGroups(REGION, null, List.of(arn), null).getFirst();
Integer original = group.getHealthCheckIntervalSeconds();
clearInvocations(healthChecker);
service.modifyTargetGroup(REGION, arn, null, null, null, null, 7, null, null, null, null);
verify(healthChecker).startMonitoring(group);
clearInvocations(healthChecker);
service.modifyTargetGroup(REGION, arn, null, null, null, null, original, null, null, null, null);
verify(healthChecker).startMonitoring(group);
clearInvocations(healthChecker);
service.modifyTargetGroup(REGION, arn, null, null, null, "/changed", null, null, null, null, null);
verifyNoInteractions(healthChecker);
}
@BeforeEach
void setUp() {
service = new ElbV2Service();