mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
39290aa8be
commit
d4bbb1bf96
7 files changed
+373
-12
No files matched your search
+63
-7
@@ -54,6 +54,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
* update commits or when the replacement is rolled back.
|
||||
*/
|
||||
private static final String LISTENER_CERTIFICATES_ATTR = "__FlociListenerCertificates";
|
||||
static final String HEALTH_UPDATE_SNAPSHOT_ATTR = "__FlociTargetGroupHealthUpdateSnapshot";
|
||||
/** 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.";
|
||||
/**
|
||||
@@ -87,6 +88,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
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);
|
||||
r.getAttributes().remove(HEALTH_UPDATE_SNAPSHOT_ATTR);
|
||||
r.getAttributes().remove(CfnRollback.LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR);
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
switch (r.getResourceType()) {
|
||||
@@ -172,6 +174,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static void clearTargetUpdateRecords(StackResource resource) {
|
||||
resource.getAttributes().remove(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR);
|
||||
resource.getAttributes().remove(HEALTH_UPDATE_SNAPSHOT_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR);
|
||||
DECLARED_TARGETS.clearPrior(resource);
|
||||
}
|
||||
@@ -186,15 +189,14 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
|
||||
CfnRollback.carryFailedUndoSnapshot(previous, attempted,
|
||||
CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR,
|
||||
CfnRollback.LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR);
|
||||
CfnRollback.LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR, HEALTH_UPDATE_SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 certificate resource gets
|
||||
* the registrations and health settings the update changed. A listener certificate resource gets
|
||||
* back the certificates the update changed on its listener. 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.
|
||||
@@ -215,7 +217,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
return restorePriorSubnets(resource);
|
||||
}
|
||||
if (TARGET_GROUP.equals(resource.getResourceType())) {
|
||||
restorePriorRegistrations(resource);
|
||||
restorePriorTargetGroup(resource);
|
||||
return true;
|
||||
}
|
||||
if (LISTENER_CERTIFICATE.equals(resource.getResourceType())) {
|
||||
@@ -225,6 +227,49 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
return false;
|
||||
}
|
||||
|
||||
private void restorePriorTargetGroup(StackResource resource) {
|
||||
RuntimeException failure = null;
|
||||
try {
|
||||
restorePriorRegistrations(resource);
|
||||
} catch (RuntimeException e) {
|
||||
failure = e;
|
||||
}
|
||||
try {
|
||||
restorePriorHealth(resource);
|
||||
} catch (RuntimeException e) {
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
} else if (failure != e) {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private static void recordPriorHealth(StackResource resource, TargetGroup group) {
|
||||
ObjectNode saved = MAPPER.valueToTree(group);
|
||||
saved.retain("healthCheckProtocol", "healthCheckPort", "healthCheckEnabled", "healthCheckPath",
|
||||
"healthCheckIntervalSeconds", "healthCheckTimeoutSeconds", "healthyThresholdCount",
|
||||
"unhealthyThresholdCount", "matcher");
|
||||
resource.getAttributes().put(HEALTH_UPDATE_SNAPSHOT_ATTR, saved.toString());
|
||||
}
|
||||
|
||||
private void restorePriorHealth(StackResource resource) {
|
||||
JsonNode saved = CfnRollback.updateSnapshot(resource, HEALTH_UPDATE_SNAPSHOT_ATTR);
|
||||
if (saved == null) {
|
||||
return;
|
||||
}
|
||||
TargetGroup prior = MAPPER.convertValue(saved, TargetGroup.class);
|
||||
String arn = resource.getPhysicalId();
|
||||
elbV2Service.modifyTargetGroup(AwsArnUtils.parse(arn).region(), arn, prior.getHealthCheckProtocol(),
|
||||
prior.getHealthCheckPort(), prior.getHealthCheckEnabled(), prior.getHealthCheckPath(),
|
||||
prior.getHealthCheckIntervalSeconds(), prior.getHealthCheckTimeoutSeconds(),
|
||||
prior.getHealthyThresholdCount(), prior.getUnhealthyThresholdCount(), prior.getMatcher());
|
||||
resource.getAttributes().remove(HEALTH_UPDATE_SNAPSHOT_ATTR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -380,7 +425,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
* 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.
|
||||
* registrations and health settings it had.
|
||||
*/
|
||||
private void provisionTargetGroup(StackResource r, JsonNode props, ProvisionContext ctx,
|
||||
Map<String, String> attributesBefore) {
|
||||
@@ -431,8 +476,19 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
TargetGroup group = tg;
|
||||
CfnRollback.guarded(r, ctx, created,
|
||||
() -> elbV2Service.deleteTargetGroup(ctx.region(), group.getTargetGroupArn()),
|
||||
() -> restorePriorRegistrations(r),
|
||||
() -> reconcileTargets(r, group, targets, ctx));
|
||||
() -> restorePriorTargetGroup(r),
|
||||
() -> {
|
||||
if (ctx.reusesPriorEntity(group.getTargetGroupArn())
|
||||
&& (hcProtocol != null || hcPort != null || hcEnabled != null || hcPath != null
|
||||
|| hcInterval != null || hcTimeout != null || healthyThreshold != null
|
||||
|| unhealthyThreshold != null || matcher != null)) {
|
||||
recordPriorHealth(r, group);
|
||||
elbV2Service.modifyTargetGroup(ctx.region(), group.getTargetGroupArn(),
|
||||
hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
|
||||
healthyThreshold, unhealthyThreshold, matcher);
|
||||
}
|
||||
reconcileTargets(r, group, targets, ctx);
|
||||
});
|
||||
DECLARED_TARGETS.record(r, ctx, attributesBefore, declaredRecord);
|
||||
}
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
return Objects.equals(a.getId(), b.getId()) && effectivePort(a, tg) == effectivePort(b, tg);
|
||||
}
|
||||
|
||||
public void startMonitoring(TargetGroup tg) {
|
||||
public synchronized void startMonitoring(TargetGroup tg) {
|
||||
if (config.services().elbv2().mock()) {
|
||||
return;
|
||||
}
|
||||
@@ -95,11 +95,18 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
states.computeIfAbsent(tgArn, k -> new ConcurrentHashMap<>());
|
||||
|
||||
long intervalMs = (tg.getHealthCheckIntervalSeconds() != null ? tg.getHealthCheckIntervalSeconds() : 30) * 1000L;
|
||||
long timerId = vertx.setPeriodic(intervalMs, id -> probeAll(tgArn, tg));
|
||||
timers.put(tgArn, timerId);
|
||||
long timerId = vertx.setPeriodic(intervalMs, id -> {
|
||||
if (Objects.equals(timers.get(tgArn), id)) {
|
||||
probeAll(tgArn, tg);
|
||||
}
|
||||
});
|
||||
Long previous = timers.put(tgArn, timerId);
|
||||
if (previous != null) {
|
||||
vertx.cancelTimer(previous);
|
||||
}
|
||||
}
|
||||
|
||||
public void stopMonitoring(String tgArn) {
|
||||
public synchronized void stopMonitoring(String tgArn) {
|
||||
Long timerId = timers.remove(tgArn);
|
||||
if (timerId != null) {
|
||||
vertx.cancelTimer(timerId);
|
||||
@@ -107,7 +114,7 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
states.remove(tgArn);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
public synchronized void clear() {
|
||||
timers.values().forEach(vertx::cancelTimer);
|
||||
timers.clear();
|
||||
states.clear();
|
||||
|
||||
@@ -678,6 +678,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
validateHealthCheckTimeout(healthCheckTimeout);
|
||||
TargetGroup tg = requireTargetGroup(region, arn);
|
||||
validateHealthCheckPort(healthCheckPort);
|
||||
Integer previousInterval = tg.getHealthCheckIntervalSeconds();
|
||||
if (healthCheckProtocol != null) tg.setHealthCheckProtocol(healthCheckProtocol);
|
||||
if (healthCheckPort != null) tg.setHealthCheckPort(healthCheckPort);
|
||||
if (healthCheckEnabled != null) tg.setHealthCheckEnabled(healthCheckEnabled);
|
||||
@@ -688,6 +689,9 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
|
||||
if (unhealthyThreshold != null) tg.setUnhealthyThresholdCount(unhealthyThreshold);
|
||||
if (matcher != null) tg.setMatcher(matcher);
|
||||
persistRegion(targetGroups, region);
|
||||
if (!Objects.equals(previousInterval, tg.getHealthCheckIntervalSeconds())) {
|
||||
healthChecker.startMonitoring(tg);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateHealthCheckTimeout(Integer timeout) {
|
||||
|
||||
+99
@@ -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") : "");
|
||||
}
|
||||
}
|
||||
+147
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user