Light, fluffy, and always free - The AWS Local Emulator alternative
fix(elbv2): admit new targets after one successful health check (#6507)
Andre Kurait985a2ea94970
diff --git a/docs/services/elb.md b/docs/services/elb.mdindex b1fd66a786..4ee302b97f 100644--- a/docs/services/elb.md+++ b/docs/services/elb.md@@ -102,6 +102,7 @@ Gateway Load Balancer listeners require omitted `Port` and `Protocol` fields on- Gateway listeners require `Protocol` and `Port` to be omitted on create and modify. Their control-plane response reports `GENEVE` without a port. CloudFormation preserves omitted gateway listener settings on create and update; other load balancer types retain their existing `HTTP` and port 80 defaults.- Instance targets are resolved through EC2 instance private addresses so local load balancer traffic can reach containers.- 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).- 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.diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.javaindex d40db1d3a6..8f72ce4589 100644--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthChecker.java@@ -160,7 +160,10 @@ public class ElbV2HealthChecker implements Resettable {if (success) {state.consecutiveFailures = 0;state.consecutiveSuccesses++;- if (state.consecutiveSuccesses >= healthyThreshold) {+ boolean initialApplicationTarget = "initial".equals(state.status)+ && ("HTTP".equals(tg.getProtocol()) || "HTTPS".equals(tg.getProtocol())+ || "lambda".equals(tg.getTargetType()));+ if (initialApplicationTarget || state.consecutiveSuccesses >= healthyThreshold) {state.status = "healthy";state.reason = null;state.description = null;diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.javaindex bc3a3abd50..c51fbd8d02 100644--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2HealthCheckerTest.java@@ -4,13 +4,18 @@ import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;+import io.vertx.core.Future;+import io.vertx.core.Handler;import io.vertx.core.Vertx;import io.vertx.core.http.HttpServer;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import java.time.Duration;import java.util.List;+import java.util.concurrent.Callable;import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;@@ -18,7 +23,10 @@ import java.util.concurrent.atomic.AtomicInteger;import static org.awaitility.Awaitility.await;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.anyLong;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.when;@@ -98,11 +106,11 @@ class ElbV2HealthCheckerTest {}@Test- void successfulProbeBelowThresholdReturnsInitialHealthCheckingReason() throws Exception {+ void firstSuccessfulProbeMakesNewTargetHealthyRegardlessOfRecoveryThreshold() throws Exception {HttpServer server = startServer(200);try {ElbV2HealthChecker checker = healthChecker();- TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 2, 1);+ TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 10, 2);TargetDescription target = target("127.0.0.1", server.actualPort());checker.addTargets(targetGroup.getTargetGroupArn(), List.of(target), targetGroup);@@ -110,9 +118,9 @@ class ElbV2HealthCheckerTest {await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {ElbV2HealthChecker.TargetHealthStatus health = checker.getHealth(targetGroup.getTargetGroupArn(), target.getId(), target.getPort());- assertEquals("initial", health.state());- assertEquals("Elb.InitialHealthChecking", health.reason());- assertEquals("Initial health checks in progress", health.description());+ assertEquals("healthy", health.state());+ assertNull(health.reason());+ assertNull(health.description());});} finally {close(server);@@ -152,6 +160,15 @@ class ElbV2HealthCheckerTest {assertEquals("unhealthy", health.state());assertEquals("Target.ResponseCodeMismatch", health.reason());});++ checker.addTargets(targetGroup.getTargetGroupArn(), List.of(target), targetGroup);+ await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {+ ElbV2HealthChecker.TargetHealthStatus health = checker.getHealth(+ targetGroup.getTargetGroupArn(), target.getId(), target.getPort());+ assertEquals("healthy", health.state());+ assertNull(health.reason());+ assertNull(health.description());+ });} finally {close(server);}@@ -207,6 +224,41 @@ class ElbV2HealthCheckerTest {assertEquals("Target registration is in progress", health.description());}+ @ParameterizedTest+ @CsvSource({"HTTP,1", "HTTPS,1", "LAMBDA,1", "TCP,2", "TLS,2", "UDP,2", "TCP_UDP,2", "GENEVE,2"})+ @SuppressWarnings("unchecked")+ void initialAdmissionRespectsTargetGroupKind(String protocol, int requiredSuccesses) {+ Vertx immediate = mock(Vertx.class);+ when(immediate.executeBlocking(any(Callable.class))).thenReturn(Future.succeededFuture(200));+ doAnswer(invocation -> {+ Handler<Long> callback = invocation.getArgument(1);+ callback.handle(1L);+ return 1L;+ }).when(immediate).setTimer(anyLong(), any());+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ when(config.services().elbv2().mock()).thenReturn(false);+ ElbV2HealthChecker checker = new ElbV2HealthChecker(immediate, config, mock(Ec2Service.class));+ TargetGroup group = targetGroup(8080, "200", 2, 1);+ group.setProtocol("LAMBDA".equals(protocol) ? null : protocol);+ group.setTargetType("LAMBDA".equals(protocol) ? "lambda" : "ip");+ group.setHealthCheckProtocol("HTTP");+ TargetDescription target = target("127.0.0.1", 8080);++ checker.addTargets(group.getTargetGroupArn(), List.of(target), group);++ ElbV2HealthChecker.TargetHealthStatus first = checker.getHealth(+ group.getTargetGroupArn(), target.getId(), target.getPort());+ assertEquals(requiredSuccesses == 1 ? "healthy" : "initial", first.state());+ assertEquals(requiredSuccesses == 1 ? null : "Elb.InitialHealthChecking", first.reason());+ assertEquals(requiredSuccesses == 1 ? null : "Initial health checks in progress", first.description());+ checker.addTargets(group.getTargetGroupArn(), List.of(target), group);+ ElbV2HealthChecker.TargetHealthStatus healthy = checker.getHealth(+ group.getTargetGroupArn(), target.getId(), target.getPort());+ assertEquals("healthy", healthy.state());+ assertNull(healthy.reason());+ assertNull(healthy.description());+ }+private ElbV2HealthChecker healthChecker() {EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);when(config.services().elbv2().mock()).thenReturn(false);@@ -237,6 +289,7 @@ class ElbV2HealthCheckerTest {targetGroup.setTargetGroupArn("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/app/1234");targetGroup.setTargetType("ip");+ targetGroup.setProtocol("HTTP");targetGroup.setPort(port);targetGroup.setHealthCheckEnabled(true);targetGroup.setHealthCheckPath("/");diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2InitialHealthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2InitialHealthIntegrationTest.javanew file mode 100644index 0000000000..ef5a7dd6ec--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2InitialHealthIntegrationTest.java@@ -0,0 +1,95 @@+package io.github.hectorvent.floci.services.elbv2;++import com.sun.net.httpserver.HttpServer;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import org.junit.jupiter.api.Test;++import java.net.InetSocketAddress;+import java.time.Duration;+import java.util.Map;+import java.util.concurrent.atomic.AtomicInteger;++import static io.restassured.RestAssured.given;+import static org.awaitility.Awaitility.await;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;++@QuarkusTest+@TestProfile(ElbV2InitialHealthIntegrationTest.RealHealthChecks.class)+class ElbV2InitialHealthIntegrationTest {++ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20261025/us-east-1/elasticloadbalancing/aws4_request";++ public static class RealHealthChecks implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.elbv2.mock", "false");+ }+ }++ @Test+ void registeredTargetBecomesHealthyAfterOneActualHttpProbe() throws Exception {+ AtomicInteger probes = new AtomicInteger();+ HttpServer backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ backend.createContext("/", exchange -> {+ probes.incrementAndGet();+ exchange.sendResponseHeaders(200, -1);+ exchange.close();+ });+ backend.start();+ String groupArn = null;+ try {+ groupArn = given()+ .header("Authorization", AUTH)+ .formParam("Action", "CreateTargetGroup")+ .formParam("Name", "initial-health-wire")+ .formParam("Protocol", "HTTP")+ .formParam("Port", backend.getAddress().getPort())+ .formParam("VpcId", Ec2Service.defaultVpcId("us-east-1"))+ .formParam("TargetType", "ip")+ .formParam("HealthCheckIntervalSeconds", 300)+ .formParam("HealthyThresholdCount", 10)+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");+ given()+ .header("Authorization", AUTH)+ .formParam("Action", "RegisterTargets")+ .formParam("TargetGroupArn", groupArn)+ .formParam("Targets.member.1.Id", "127.0.0.1")+ .formParam("Targets.member.1.Port", backend.getAddress().getPort())+ .when().post("/")+ .then().statusCode(200);++ String registeredGroupArn = groupArn;+ await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> given()+ .header("Authorization", AUTH)+ .formParam("Action", "DescribeTargetHealth")+ .formParam("TargetGroupArn", registeredGroupArn)+ .when().post("/")+ .then().statusCode(200)+ .body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.TargetHealth.State",+ equalTo("healthy"))+ .body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.TargetHealth.Reason.size()",+ equalTo(0)));+ assertEquals(1, probes.get(), "Initial admission must not wait for the recovery threshold");+ } finally {+ try {+ if (groupArn != null) {+ given()+ .header("Authorization", AUTH)+ .formParam("Action", "DeleteTargetGroup")+ .formParam("TargetGroupArn", groupArn)+ .when().post("/")+ .then().statusCode(200);+ }+ } finally {+ backend.stop(0);+ }+ }+ }+}