diff --git a/docs/services/elb.md b/docs/services/elb.md index 1f658b6da5..81b7c470ce 100644 --- a/docs/services/elb.md +++ b/docs/services/elb.md @@ -149,6 +149,8 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on - Target health starts in `initial` state with reason `Elb.RegistrationInProgress` and is updated by Floci's health checker when monitoring is active. - A newly registered Application Load Balancer target (HTTP/HTTPS target group or Lambda target) becomes healthy after its first successful check. Network and Gateway target groups retain `HealthyThresholdCount` for initial admission. The threshold applies to every group when recovering from `unhealthy`. - Health checks probe the target group's `HealthCheckPort` when it is a port number, and each target's own port when it is `traffic-port` (the default). +- `HealthCheckProtocol` defaults to `HTTP` for `HTTP` and `HTTPS` target groups and for target type `alb`, and to `TCP` for every other protocol, as for Network and Gateway Load Balancers. A health check uses `HTTP`, `HTTPS` or `TCP`. `TCP` is refused for `HTTP` and `HTTPS` target groups and for target type `alb`. `GENEVE`, `TLS`, `UDP`, `TCP_UDP`, `QUIC` and `TCP_QUIC` are refused for every target group. Each refusal is a `ValidationError` naming the protocols the target group takes, such as `Health check protocol 'TCP' must be one of 'HTTP, HTTPS'`, from `CreateTargetGroup` and `ModifyTargetGroup` alike, and changes nothing. +- A `TCP` check has no `HealthCheckPath` or `Matcher`. Naming either for one, the default `TCP` check included, is refused with `InvalidConfigurationRequest` (`Health check paths are not supported for TCP health checks`, and the same for matchers). Moving a `TCP` check to `HTTP` or `HTTPS` takes both, or `ModifyTargetGroup` answers `ValidationError` `Path and return code are required for layer 7 health checks.`. Moving a check to `TCP` drops its path and matcher. - Each `CreateListener` automatically creates an immutable default rule (`priority=default`, `isDefault=true`). This rule cannot be deleted; use `ModifyListener` to change its action. - Rule priorities are unique per listener: `CreateRule` and `SetRulePriorities` only reject a priority held by another rule on the same listener. `SetRulePriorities` is atomic: all priority assignments are validated before any change is committed. - `DeleteTargetGroup` is rejected with `ResourceInUse` while the target group is referenced by any listener or rule. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java index 58d743a5b9..00a1a8e3ad 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java @@ -263,10 +263,7 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner { } 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()); + elbV2Service.restoreHealthCheck(AwsArnUtils.parse(arn).region(), arn, prior); resource.getAttributes().remove(HEALTH_UPDATE_SNAPSHOT_ATTR); } diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java index b3ed8e63e7..47c673d734 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2QueryHandler.java @@ -860,7 +860,7 @@ public class ElbV2QueryHandler { xml.elem("TargetGroupArn", tg.getTargetGroupArn()); xml.elem("TargetGroupName", tg.getTargetGroupName()); xml.elem("Protocol", safe(tg.getProtocol())); - if (isHttpProtocol(tg.getProtocol())) { + if (ElbV2Service.isHttpProtocol(tg.getProtocol())) { xml.elem("ProtocolVersion", safe(tg.getProtocolVersion())); } if (tg.getPort() != null) xml.elem("Port", String.valueOf(tg.getPort())); @@ -872,7 +872,7 @@ public class ElbV2QueryHandler { if (tg.getHealthCheckTimeoutSeconds() != null) xml.elem("HealthCheckTimeoutSeconds", String.valueOf(tg.getHealthCheckTimeoutSeconds())); if (tg.getHealthyThresholdCount() != null) xml.elem("HealthyThresholdCount", String.valueOf(tg.getHealthyThresholdCount())); if (tg.getUnhealthyThresholdCount() != null) xml.elem("UnhealthyThresholdCount", String.valueOf(tg.getUnhealthyThresholdCount())); - if (isHttpProtocol(tg.getHealthCheckProtocol())) { + if (ElbV2Service.isHttpProtocol(tg.getHealthCheckProtocol())) { xml.elem("HealthCheckPath", safe(tg.getHealthCheckPath())); xml.start("Matcher").elem("HttpCode", safe(tg.getMatcher())).end("Matcher"); } @@ -886,10 +886,6 @@ public class ElbV2QueryHandler { return xml.build(); } - private static boolean isHttpProtocol(String protocol) { - return "HTTP".equals(protocol) || "HTTPS".equals(protocol); - } - private String listenerXml(Listener l) { XmlBuilder xml = new XmlBuilder(); xml.elem("ListenerArn", l.getListenerArn()); diff --git a/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java b/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java index 9c1c2137ae..ef2aa99a4d 100644 --- a/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/floci/aws/services/elbv2/ElbV2Service.java @@ -583,6 +583,13 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc throw new AwsException("ValidationError", "A port must be specified", 400); } validateHealthCheckPort(healthCheckPort); + String groupProtocol = protocol != null ? protocol : "HTTP"; + String groupTargetType = targetType != null ? targetType : "instance"; + validateHealthCheckProtocol(healthCheckProtocol, groupProtocol, groupTargetType); + String checkProtocol = healthCheckProtocol != null ? healthCheckProtocol + : defaultHealthCheckProtocol(groupProtocol, groupTargetType); + validateLayer7Members(checkProtocol, healthCheckPath, matcher); + boolean layer7Check = isHttpProtocol(checkProtocol); Map regionTgs = targetGroups.computeIfAbsent(region, k -> new ConcurrentHashMap<>()); boolean duplicate = regionTgs.values().stream() .anyMatch(tg -> tg.getTargetGroupName().equals(name)); @@ -597,24 +604,24 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc TargetGroup tg = new TargetGroup(); tg.setTargetGroupArn(arn); tg.setTargetGroupName(name); - tg.setProtocol(protocol != null ? protocol : "HTTP"); + tg.setProtocol(groupProtocol); tg.setProtocolVersion(protocolVersion != null ? protocolVersion : "HTTP1"); tg.setPort(port); tg.setVpcId(vpcId); - tg.setTargetType(targetType != null ? targetType : "instance"); + tg.setTargetType(groupTargetType); tg.setIpAddressType(ipAddressType != null ? ipAddressType : "ipv4"); tg.setRegion(region); // health check defaults tg.setHealthCheckEnabled(healthCheckEnabled != null ? healthCheckEnabled : true); - tg.setHealthCheckProtocol(healthCheckProtocol != null ? healthCheckProtocol : "HTTP"); + tg.setHealthCheckProtocol(checkProtocol); tg.setHealthCheckPort(healthCheckPort != null ? healthCheckPort : "traffic-port"); - tg.setHealthCheckPath(healthCheckPath != null ? healthCheckPath : "/"); + tg.setHealthCheckPath(layer7Check ? (healthCheckPath != null ? healthCheckPath : "/") : null); tg.setHealthCheckIntervalSeconds(healthCheckInterval != null ? healthCheckInterval : 30); tg.setHealthCheckTimeoutSeconds(healthCheckTimeout != null ? healthCheckTimeout : 5); tg.setHealthyThresholdCount(healthyThreshold != null ? healthyThreshold : 5); tg.setUnhealthyThresholdCount(unhealthyThreshold != null ? unhealthyThreshold : 2); - tg.setMatcher(matcher != null ? matcher : "200"); + tg.setMatcher(layer7Check ? (matcher != null ? matcher : "200") : null); regionTgs.put(arn, tg); targetGroups.put(region, regionTgs); @@ -678,8 +685,20 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc validateHealthCheckTimeout(healthCheckTimeout); TargetGroup tg = requireTargetGroup(region, arn); validateHealthCheckPort(healthCheckPort); + validateHealthCheckProtocol(healthCheckProtocol, tg.getProtocol(), tg.getTargetType()); + String checkProtocol = healthCheckProtocol != null ? healthCheckProtocol : tg.getHealthCheckProtocol(); + validateLayer7Members(checkProtocol, healthCheckPath, matcher); + if (isHttpProtocol(healthCheckProtocol) && !isHttpProtocol(tg.getHealthCheckProtocol()) + && (healthCheckPath == null || matcher == null)) { + throw new AwsException("ValidationError", "Path and return code are required for layer 7 health checks.", + 400); + } Integer previousInterval = tg.getHealthCheckIntervalSeconds(); if (healthCheckProtocol != null) tg.setHealthCheckProtocol(healthCheckProtocol); + if (!isHttpProtocol(checkProtocol)) { + tg.setHealthCheckPath(null); + tg.setMatcher(null); + } if (healthCheckPort != null) tg.setHealthCheckPort(healthCheckPort); if (healthCheckEnabled != null) tg.setHealthCheckEnabled(healthCheckEnabled); if (healthCheckPath != null) tg.setHealthCheckPath(healthCheckPath); @@ -694,6 +713,71 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc } } + /** + * Puts back the health check {@code prior} holds, as a CloudFormation rollback does. A TCP check has no path or + * matcher, so the ones a target group saved before TCP checks dropped them still holds are not put back. + */ + public void restoreHealthCheck(String region, String arn, TargetGroup prior) { + boolean layer7Check = isHttpProtocol(prior.getHealthCheckProtocol()); + modifyTargetGroup(region, arn, prior.getHealthCheckProtocol(), prior.getHealthCheckPort(), + prior.getHealthCheckEnabled(), layer7Check ? prior.getHealthCheckPath() : null, + prior.getHealthCheckIntervalSeconds(), prior.getHealthCheckTimeoutSeconds(), + prior.getHealthyThresholdCount(), prior.getUnhealthyThresholdCount(), + layer7Check ? prior.getMatcher() : null); + } + + /** + * The health check protocol a target group gets when the request names none: "For Application Load Balancers, + * the default is HTTP. For Network Load Balancers and Gateway Load Balancers, the default is TCP." An HTTP or + * HTTPS target group is an Application Load Balancer's, and one whose target is an Application Load Balancer + * supports only HTTP and HTTPS checks. + */ + static String defaultHealthCheckProtocol(String protocol, String targetType) { + return isHttpProtocol(protocol) || "alb".equals(targetType) ? "HTTP" : "TCP"; + } + + /** + * A health check uses HTTP, HTTPS or TCP: "The GENEVE, TLS, UDP, TCP_UDP, QUIC, and TCP_QUIC protocols are not + * supported for health checks", "the TCP protocol is not supported for health checks if the protocol of the + * target group is HTTP or HTTPS", and for a target type of {@code alb} "the supported health check protocols are + * HTTP and HTTPS". A protocol outside them is refused naming the ones the target group takes, as AWS refuses a + * TCP check of an HTTP target group: "Health check protocol 'TCP' must be one of 'HTTP, HTTPS'". + */ + private static void validateHealthCheckProtocol(String healthCheckProtocol, String protocol, String targetType) { + if (healthCheckProtocol == null) { + return; + } + List supported = isHttpProtocol(protocol) || "alb".equals(targetType) + ? List.of("HTTP", "HTTPS") : List.of("HTTP", "HTTPS", "TCP"); + if (!supported.contains(healthCheckProtocol)) { + throw new AwsException("ValidationError", "Health check protocol '" + healthCheckProtocol + + "' must be one of '" + String.join(", ", supported) + "'", 400); + } + } + + /** + * {@code HealthCheckPath} and {@code Matcher} are "[HTTP/HTTPS health checks]" members, so a TCP check, which + * only opens a connection, carries neither. {@code protocol} is the protocol of the check the request leaves. + */ + private static void validateLayer7Members(String protocol, String healthCheckPath, String matcher) { + if (isHttpProtocol(protocol)) { + return; + } + if (healthCheckPath != null) { + throw new AwsException("InvalidConfigurationRequest", + "Health check paths are not supported for " + protocol + " health checks", 400); + } + if (matcher != null) { + throw new AwsException("InvalidConfigurationRequest", + "Health check matchers are not supported for " + protocol + " health checks", 400); + } + } + + /** Whether {@code protocol} is HTTP or HTTPS, the protocols whose health checks have a path and a matcher. */ + static boolean isHttpProtocol(String protocol) { + return "HTTP".equals(protocol) || "HTTPS".equals(protocol); + } + private static void validateHealthCheckTimeout(Integer timeout) { if (timeout != null && (timeout < 2 || timeout > 120)) { String constraint = timeout < 2 ? "greater than or equal to 2" : "less than or equal to 120"; diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java index e06d1e99dc..4f9f45d771 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisionerTest.java @@ -43,6 +43,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; @@ -1128,8 +1129,17 @@ class ElbV2CfnProvisionerTest { } private void verifyHealthRestored(int calls) { - verify(elb, times(calls)).modifyTargetGroup(REGION, TG_ARN, "TCP", "traffic-port", true, - "/", 30, 5, 5, 2, "200"); + verify(elb, times(calls)).restoreHealthCheck(eq(REGION), eq(TG_ARN), + argThat(ElbV2CfnProvisionerTest::isPriorHealth)); + } + + private static boolean isPriorHealth(TargetGroup prior) { + return "TCP".equals(prior.getHealthCheckProtocol()) && "traffic-port".equals(prior.getHealthCheckPort()) + && Boolean.TRUE.equals(prior.getHealthCheckEnabled()) && "/".equals(prior.getHealthCheckPath()) + && Integer.valueOf(30).equals(prior.getHealthCheckIntervalSeconds()) + && Integer.valueOf(5).equals(prior.getHealthCheckTimeoutSeconds()) + && Integer.valueOf(5).equals(prior.getHealthyThresholdCount()) + && Integer.valueOf(2).equals(prior.getUnhealthyThresholdCount()) && "200".equals(prior.getMatcher()); } @Test @@ -1202,8 +1212,8 @@ class ElbV2CfnProvisionerTest { @Test void failedHealthUndoSurvivesRestoringThePreviousResourceAndCanBeRetried() { priorHealth(); - doThrow(internalFailure()).doNothing().when(elb).modifyTargetGroup(REGION, TG_ARN, - "TCP", "traffic-port", true, "/", 30, 5, 5, 2, "200"); + doThrow(internalFailure()).doNothing().when(elb).restoreHealthCheck(eq(REGION), eq(TG_ARN), + argThat(ElbV2CfnProvisionerTest::isPriorHealth)); refusingRegistration(); assertThrows(AwsException.class, () -> keptTargetGroupUpdatedTo( List.of(), changedHealth(target("10.0.0.5", 70000, null)), null)); diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2OptionalResponseFieldsIntegrationTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2OptionalResponseFieldsIntegrationTest.java index c790786b79..75355cc23c 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2OptionalResponseFieldsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2OptionalResponseFieldsIntegrationTest.java @@ -11,7 +11,9 @@ import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.acm.AcmClient; import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client; import software.amazon.awssdk.services.elasticloadbalancingv2.model.Certificate; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.ElasticLoadBalancingV2Exception; import software.amazon.awssdk.services.elasticloadbalancingv2.model.Listener; +import software.amazon.awssdk.services.elasticloadbalancingv2.model.Matcher; import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetGroup; import java.util.ArrayList; @@ -25,6 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @QuarkusTest @@ -220,11 +223,17 @@ class ElbV2OptionalResponseFieldsIntegrationTest { () -> assertEquals("/", httpGroup.healthCheckPath()), () -> assertEquals("200", httpGroup.matcher().httpCode())); + ElasticLoadBalancingV2Exception refused = assertThrows(ElasticLoadBalancingV2Exception.class, + () -> elb.modifyTargetGroup(request -> request.targetGroupArn(tcp).healthCheckProtocol("HTTP"))); + assertEquals("ValidationError", refused.awsErrorDetails().errorCode()); + assertEquals("Path and return code are required for layer 7 health checks.", + refused.awsErrorDetails().errorMessage()); TargetGroup switchedToHttpCheck = elb.modifyTargetGroup(request -> request.targetGroupArn(tcp) - .healthCheckProtocol("HTTP")).targetGroups().getFirst(); - assertAll("Switching to an HTTP check returns the stored path and matcher", - () -> assertNotNull(switchedToHttpCheck.healthCheckPath()), - () -> assertNotNull(switchedToHttpCheck.matcher())); + .healthCheckProtocol("HTTP").healthCheckPath("/ready") + .matcher(Matcher.builder().httpCode("200-399").build())).targetGroups().getFirst(); + assertAll("Switching to an HTTP check takes a path and a matcher, and returns them", + () -> assertEquals("/ready", switchedToHttpCheck.healthCheckPath()), + () -> assertEquals("200-399", switchedToHttpCheck.matcher().httpCode())); } private String createTargetGroup(String prefix, String protocol, String healthCheckProtocol) { diff --git a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java index a00e045b71..e190b47668 100644 --- a/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/elbv2/ElbV2ServiceTest.java @@ -30,6 +30,7 @@ import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -1610,6 +1611,165 @@ class ElbV2ServiceTest { assertEquals(timeout == 2 ? 120 : 2, group.getHealthCheckTimeoutSeconds()); } + /** + * "For Application Load Balancers, the default is HTTP. For Network Load Balancers and Gateway Load Balancers, + * the default is TCP", and a target type of alb supports only HTTP and HTTPS checks. A TCP check has no path or + * matcher. + */ + @ParameterizedTest + @CsvSource({"HTTP, instance, HTTP", "HTTPS, ip, HTTP", "TCP, instance, TCP", "TLS, ip, TCP", "UDP, instance, TCP", + "TCP_UDP, ip, TCP", "GENEVE, ip, TCP", "TCP, alb, HTTP"}) + void theHealthCheckProtocolDefaultsByTheTargetGroupProtocol(String protocol, String targetType, String expected) { + TargetGroup group = healthCheckedGroup("defaults-" + protocol.toLowerCase().replace('_', '-') + "-" + targetType, + protocol, targetType, null, null, null); + + assertEquals(expected, group.getHealthCheckProtocol()); + assertEquals("HTTP".equals(expected) ? "/" : null, group.getHealthCheckPath()); + assertEquals("HTTP".equals(expected) ? "200" : null, group.getMatcher()); + } + + /** + * A health check uses HTTP, HTTPS or TCP, and TCP is not supported for an HTTP or HTTPS target group or a target + * type of alb. The refusal names the protocols the target group takes, as AWS's does for a TCP check of an HTTP + * target group, on create and on modify alike: "Health check protocol 'TCP' must be one of 'HTTP, HTTPS'". + */ + @ParameterizedTest + @CsvSource({"HTTP, instance, TCP, 'HTTP, HTTPS'", "HTTPS, ip, TCP, 'HTTP, HTTPS'", "TCP, alb, TCP, 'HTTP, HTTPS'", + "HTTP, ip, TLS, 'HTTP, HTTPS'", "TCP, ip, TLS, 'HTTP, HTTPS, TCP'", "TCP, ip, UDP, 'HTTP, HTTPS, TCP'", + "UDP, ip, TCP_UDP, 'HTTP, HTTPS, TCP'", "TCP, ip, GENEVE, 'HTTP, HTTPS, TCP'", + "TCP, ip, QUIC, 'HTTP, HTTPS, TCP'", "TCP_UDP, ip, TCP_QUIC, 'HTTP, HTTPS, TCP'"}) + void aHealthCheckProtocolTheTargetGroupDoesNotTakeIsRefused(String protocol, String targetType, + String healthCheckProtocol, String supported) { + String message = "Health check protocol '" + healthCheckProtocol + "' must be one of '" + supported + "'"; + assertRefused("ValidationError", message, + () -> healthCheckedGroup("refused", protocol, targetType, healthCheckProtocol, null, null)); + assertTrue(service.describeTargetGroups(REGION, null, null, null).isEmpty()); + + TargetGroup created = healthCheckedGroup("kept", protocol, targetType, null, null, null); + String arn = created.getTargetGroupArn(); + String checkProtocol = created.getHealthCheckProtocol(); + assertRefused("ValidationError", message, () -> service.modifyTargetGroup(REGION, arn, healthCheckProtocol, + "8080", null, null, null, null, null, null, null)); + assertEquals(checkProtocol, storedGroup(arn).getHealthCheckProtocol()); + assertEquals("traffic-port", storedGroup(arn).getHealthCheckPort()); + } + + /** + * {@code HealthCheckPath} and {@code Matcher} are "[HTTP/HTTPS health checks]" members, judged against the check + * the request leaves: the protocol it names, the default, or the one the target group has. + */ + @Test + void aTcpCheckCarriesNoPathOrMatcher() { + String paths = "Health check paths are not supported for TCP health checks"; + String matchers = "Health check matchers are not supported for TCP health checks"; + assertRefused("InvalidConfigurationRequest", paths, + () -> healthCheckedGroup("named-tcp", "TCP", "ip", "TCP", "/health", null)); + assertRefused("InvalidConfigurationRequest", paths, + () -> healthCheckedGroup("default-tcp", "TLS", "ip", null, "/health", null)); + assertRefused("InvalidConfigurationRequest", matchers, + () -> healthCheckedGroup("default-tcp", "TCP", "ip", null, null, "200-399")); + assertTrue(service.describeTargetGroups(REGION, null, null, null).isEmpty()); + + String tcp = healthCheckedGroup("tcp", "TCP", "ip", null, null, null).getTargetGroupArn(); + assertRefused("InvalidConfigurationRequest", paths, () -> service.modifyTargetGroup(REGION, tcp, null, "8080", + null, "/health", null, null, null, null, null)); + assertEquals("traffic-port", storedGroup(tcp).getHealthCheckPort()); + String http = healthCheckedGroup("http", "TCP", "ip", "HTTP", "/ready", "200-399").getTargetGroupArn(); + assertRefused("InvalidConfigurationRequest", matchers, () -> service.modifyTargetGroup(REGION, http, "TCP", + null, null, null, null, null, null, null, "200")); + assertEquals("HTTP", storedGroup(http).getHealthCheckProtocol()); + assertEquals("/ready", storedGroup(http).getHealthCheckPath()); + assertEquals("200-399", storedGroup(http).getMatcher()); + } + + /** + * Moving a TCP check to HTTP or HTTPS takes both a path and a matcher: the modify fills in neither. A check that + * is HTTP or HTTPS already keeps its own, and one moved to TCP drops them. + */ + @Test + void movingATcpCheckToHttpTakesAPathAndAMatcher() { + String arn = healthCheckedGroup("to-http", "TCP", "ip", null, null, null).getTargetGroupArn(); + for (String[] members : new String[][]{{null, null}, {"/ready", null}, {null, "200-399"}}) { + assertRefused("ValidationError", "Path and return code are required for layer 7 health checks.", + () -> service.modifyTargetGroup(REGION, arn, "HTTP", "8080", null, members[0], null, null, null, + null, members[1])); + assertEquals("TCP", storedGroup(arn).getHealthCheckProtocol()); + assertEquals("traffic-port", storedGroup(arn).getHealthCheckPort()); + assertNull(storedGroup(arn).getHealthCheckPath()); + } + + service.modifyTargetGroup(REGION, arn, "HTTPS", "8443", null, "/ready", null, null, null, null, "200-399"); + assertEquals("HTTPS", storedGroup(arn).getHealthCheckProtocol()); + assertEquals("/ready", storedGroup(arn).getHealthCheckPath()); + assertEquals("200-399", storedGroup(arn).getMatcher()); + + service.modifyTargetGroup(REGION, arn, "HTTP", null, null, null, null, null, null, null, null); + assertEquals("HTTP", storedGroup(arn).getHealthCheckProtocol()); + assertEquals("/ready", storedGroup(arn).getHealthCheckPath()); + assertEquals("200-399", storedGroup(arn).getMatcher()); + + service.modifyTargetGroup(REGION, arn, "TCP", null, null, null, null, null, null, null, null); + assertEquals("TCP", storedGroup(arn).getHealthCheckProtocol()); + assertNull(storedGroup(arn).getHealthCheckPath()); + assertNull(storedGroup(arn).getMatcher()); + } + + /** + * A rollback puts back the health check it saved. A TCP check saved before TCP checks dropped their path and + * matcher still holds them, and they are not put back. + */ + @Test + void aRestoredTcpCheckGetsNoPathOrMatcher() { + String arn = healthCheckedGroup("restored", "TCP", "ip", "HTTP", "/ready", "200-399").getTargetGroupArn(); + TargetGroup saved = new TargetGroup(); + saved.setHealthCheckProtocol("TCP"); + saved.setHealthCheckPort("traffic-port"); + saved.setHealthCheckEnabled(true); + saved.setHealthCheckPath("/"); + saved.setHealthCheckIntervalSeconds(10); + saved.setHealthCheckTimeoutSeconds(6); + saved.setHealthyThresholdCount(3); + saved.setUnhealthyThresholdCount(4); + saved.setMatcher("200"); + + service.restoreHealthCheck(REGION, arn, saved); + + TargetGroup restored = storedGroup(arn); + assertEquals("TCP", restored.getHealthCheckProtocol()); + assertNull(restored.getHealthCheckPath()); + assertNull(restored.getMatcher()); + assertEquals(10, restored.getHealthCheckIntervalSeconds()); + assertEquals(6, restored.getHealthCheckTimeoutSeconds()); + assertEquals(3, restored.getHealthyThresholdCount()); + assertEquals(4, restored.getUnhealthyThresholdCount()); + + saved.setHealthCheckProtocol("HTTPS"); + saved.setHealthCheckPath("/live"); + saved.setMatcher("204"); + service.restoreHealthCheck(REGION, arn, saved); + + assertEquals("HTTPS", storedGroup(arn).getHealthCheckProtocol()); + assertEquals("/live", storedGroup(arn).getHealthCheckPath()); + assertEquals("204", storedGroup(arn).getMatcher()); + } + + private TargetGroup healthCheckedGroup(String name, String protocol, String targetType, + String healthCheckProtocol, String healthCheckPath, String matcher) { + return service.createTargetGroup(REGION, name, protocol, null, 80, "vpc-a", targetType, healthCheckProtocol, + null, null, healthCheckPath, null, null, null, null, matcher, null, Map.of()); + } + + private TargetGroup storedGroup(String arn) { + return service.describeTargetGroups(REGION, null, List.of(arn), null).getFirst(); + } + + private static void assertRefused(String code, String message, Executable call) { + AwsException refusal = assertThrows(AwsException.class, call); + assertEquals(code, refusal.getErrorCode()); + assertEquals(message, refusal.getMessage()); + assertEquals(400, refusal.getHttpStatus()); + } + private String createTargetGroup(String name) { return service.createTargetGroup( REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",