mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(elbv2): expose target health reason parity (#1743)
This commit is contained in:
1 parent
e49bc432bd
commit
aa77d4ce46
6 files changed
+342
-13
No files matched your search
@@ -70,6 +70,7 @@ import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetDescri
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetGroup;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetGroupAttribute;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthDescription;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthReasonEnum;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthStateEnum;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetTypeEnum;
|
||||
|
||||
@@ -312,9 +313,31 @@ class ElbV2Test {
|
||||
assertThat(resp.targetHealthDescriptions()).hasSize(2);
|
||||
for (TargetHealthDescription thd : resp.targetHealthDescriptions()) {
|
||||
assertThat(thd.targetHealth().state()).isEqualTo(TargetHealthStateEnum.INITIAL);
|
||||
assertThat(thd.targetHealth().reason()).isEqualTo(TargetHealthReasonEnum.ELB_REGISTRATION_IN_PROGRESS);
|
||||
assertThat(thd.targetHealth().description()).isEqualTo("Target registration is in progress");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(16)
|
||||
@DisplayName("DescribeTargetHealth - reports unused for explicit unregistered target")
|
||||
void describeTargetHealthForUnregisteredTarget() {
|
||||
DescribeTargetHealthResponse resp = elb.describeTargetHealth(
|
||||
DescribeTargetHealthRequest.builder()
|
||||
.targetGroupArn(tgArn)
|
||||
.targets(TargetDescription.builder()
|
||||
.id("i-1234567890abcdef0")
|
||||
.port(8080)
|
||||
.build())
|
||||
.build());
|
||||
|
||||
assertThat(resp.targetHealthDescriptions()).hasSize(1);
|
||||
TargetHealthDescription health = resp.targetHealthDescriptions().get(0);
|
||||
assertThat(health.targetHealth().state()).isEqualTo(TargetHealthStateEnum.UNUSED);
|
||||
assertThat(health.targetHealth().reason()).isEqualTo(TargetHealthReasonEnum.TARGET_NOT_REGISTERED);
|
||||
assertThat(health.targetHealth().description()).isEqualTo("Target is not registered to the target group");
|
||||
}
|
||||
|
||||
// ─── Listeners ───────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -12,6 +12,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -88,6 +89,9 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
String key = stateKey(t.getId(), port);
|
||||
tgStates.putIfAbsent(key, new TargetState());
|
||||
}
|
||||
if (Boolean.TRUE.equals(tg.getHealthCheckEnabled())) {
|
||||
vertx.setTimer(1, ignored -> probeAll(tgArn, tg));
|
||||
}
|
||||
}
|
||||
|
||||
public void removeTargets(String tgArn, List<TargetDescription> targets, TargetGroup tg) {
|
||||
@@ -102,15 +106,19 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
}
|
||||
|
||||
public String getState(String tgArn, String targetId, int port) {
|
||||
return getHealth(tgArn, targetId, port).state();
|
||||
}
|
||||
|
||||
public TargetHealthStatus getHealth(String tgArn, String targetId, int port) {
|
||||
Map<String, TargetState> tgStates = states.get(tgArn);
|
||||
if (tgStates == null) {
|
||||
return "initial";
|
||||
return TargetHealthStatus.registrationInProgress();
|
||||
}
|
||||
TargetState s = tgStates.get(stateKey(targetId, port));
|
||||
if (s == null) {
|
||||
return "initial";
|
||||
return TargetHealthStatus.registrationInProgress();
|
||||
}
|
||||
return s.status;
|
||||
return new TargetHealthStatus(s.status, s.reason, s.description);
|
||||
}
|
||||
|
||||
public boolean isHealthy(String tgArn, TargetDescription target, int port) {
|
||||
@@ -153,12 +161,19 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
state.consecutiveSuccesses++;
|
||||
if (state.consecutiveSuccesses >= healthyThreshold) {
|
||||
state.status = "healthy";
|
||||
state.reason = null;
|
||||
state.description = null;
|
||||
} else if ("initial".equals(state.status)) {
|
||||
state.reason = "Elb.InitialHealthChecking";
|
||||
state.description = "Initial health checks in progress";
|
||||
}
|
||||
} else {
|
||||
state.consecutiveSuccesses = 0;
|
||||
state.consecutiveFailures++;
|
||||
if (state.consecutiveFailures >= unhealthyThreshold) {
|
||||
state.status = "unhealthy";
|
||||
state.reason = "Target.ResponseCodeMismatch";
|
||||
state.description = "Health checks failed with these codes: [" + statusCode + "]";
|
||||
}
|
||||
}
|
||||
}).onFailure(err -> {
|
||||
@@ -166,6 +181,13 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
state.consecutiveFailures++;
|
||||
if (state.consecutiveFailures >= unhealthyThreshold) {
|
||||
state.status = "unhealthy";
|
||||
if (isTimeout(err)) {
|
||||
state.reason = "Target.Timeout";
|
||||
state.description = "Request timed out";
|
||||
} else {
|
||||
state.reason = "Target.FailedHealthChecks";
|
||||
state.description = "Health checks failed";
|
||||
}
|
||||
}
|
||||
LOG.debugv("Health check failed for {0}:{1} - {2}", host, port, err.getMessage());
|
||||
});
|
||||
@@ -204,12 +226,34 @@ public class ElbV2HealthChecker implements Resettable {
|
||||
.anyMatch(codeStr::equals);
|
||||
}
|
||||
|
||||
private static boolean isTimeout(Throwable err) {
|
||||
Throwable current = err;
|
||||
while (current != null) {
|
||||
if (current instanceof SocketTimeoutException) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String stateKey(String targetId, int port) {
|
||||
return targetId + ":" + port;
|
||||
}
|
||||
|
||||
public record TargetHealthStatus(String state, String reason, String description) {
|
||||
private static TargetHealthStatus registrationInProgress() {
|
||||
return new TargetHealthStatus(
|
||||
"initial",
|
||||
"Elb.RegistrationInProgress",
|
||||
"Target registration is in progress");
|
||||
}
|
||||
}
|
||||
|
||||
private static class TargetState {
|
||||
volatile String status = "initial";
|
||||
volatile String reason = "Elb.RegistrationInProgress";
|
||||
volatile String description = "Target registration is in progress";
|
||||
volatile int consecutiveSuccesses = 0;
|
||||
volatile int consecutiveFailures = 0;
|
||||
}
|
||||
|
||||
@@ -753,8 +753,8 @@ public class ElbV2Service {
|
||||
public List<TargetHealth> describeTargetHealth(String region, String tgArn,
|
||||
List<TargetDescription> filterTargets) {
|
||||
TargetGroup tg = requireTargetGroup(region, tgArn);
|
||||
List<TargetDescription> candidates = filterTargets != null && !filterTargets.isEmpty()
|
||||
? filterTargets : tg.getTargets();
|
||||
boolean hasFilterTargets = filterTargets != null && !filterTargets.isEmpty();
|
||||
List<TargetDescription> candidates = hasFilterTargets ? filterTargets : tg.getTargets();
|
||||
|
||||
boolean isLambdaTg = "lambda".equals(tg.getTargetType());
|
||||
return candidates.stream().map(t -> {
|
||||
@@ -767,19 +767,26 @@ public class ElbV2Service {
|
||||
}
|
||||
int port = ElbV2HealthChecker.effectivePort(t, tg);
|
||||
th.setHealthCheckPort(String.valueOf(port));
|
||||
String state = healthChecker.getState(tgArn, t.getId(), port);
|
||||
th.setState(state);
|
||||
if ("initial".equals(state)) {
|
||||
th.setReason("Elb.RegistrationInProgress");
|
||||
th.setDescription("Target registration is in progress");
|
||||
} else if ("unhealthy".equals(state)) {
|
||||
th.setReason("Target.FailedHealthChecks");
|
||||
th.setDescription("Health checks failed");
|
||||
if (hasFilterTargets && !isRegisteredTarget(tg, t, port)) {
|
||||
th.setState("unused");
|
||||
th.setReason("Target.NotRegistered");
|
||||
th.setDescription("Target is not registered to the target group");
|
||||
return th;
|
||||
}
|
||||
ElbV2HealthChecker.TargetHealthStatus health = healthChecker.getHealth(tgArn, t.getId(), port);
|
||||
th.setState(health.state());
|
||||
th.setReason(health.reason());
|
||||
th.setDescription(health.description());
|
||||
return th;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static boolean isRegisteredTarget(TargetGroup targetGroup, TargetDescription candidate, int candidatePort) {
|
||||
return targetGroup.getTargets().stream()
|
||||
.anyMatch(registered -> Objects.equals(registered.getId(), candidate.getId())
|
||||
&& ElbV2HealthChecker.effectivePort(registered, targetGroup) == candidatePort);
|
||||
}
|
||||
|
||||
// ── Tags ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public void addTags(List<String> resourceArns, Map<String, String> newTags) {
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
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.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
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.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ElbV2HealthCheckerTest {
|
||||
|
||||
private final Vertx vertx = Vertx.vertx();
|
||||
|
||||
@AfterEach
|
||||
void closeVertx() {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulProbeTransitionsTargetToHealthy() throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
try {
|
||||
ElbV2HealthChecker checker = healthChecker();
|
||||
TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseCodeMismatchTransitionsTargetToUnhealthyWithAwsReason() throws Exception {
|
||||
HttpServer server = startServer(503);
|
||||
try {
|
||||
ElbV2HealthChecker checker = healthChecker();
|
||||
TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
|
||||
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("unhealthy", health.state());
|
||||
assertEquals("Target.ResponseCodeMismatch", health.reason());
|
||||
assertEquals("Health checks failed with these codes: [503]", health.description());
|
||||
});
|
||||
} finally {
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutProbeTransitionsTargetToUnhealthyWithAwsReason() throws Exception {
|
||||
HttpServer server = startHangingServer();
|
||||
try {
|
||||
ElbV2HealthChecker checker = healthChecker();
|
||||
TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
|
||||
checker.addTargets(targetGroup.getTargetGroupArn(), List.of(target), targetGroup);
|
||||
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
|
||||
ElbV2HealthChecker.TargetHealthStatus health = checker.getHealth(
|
||||
targetGroup.getTargetGroupArn(), target.getId(), target.getPort());
|
||||
assertEquals("unhealthy", health.state());
|
||||
assertEquals("Target.Timeout", health.reason());
|
||||
assertEquals("Request timed out", health.description());
|
||||
});
|
||||
} finally {
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulProbeBelowThresholdReturnsInitialHealthCheckingReason() throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
try {
|
||||
ElbV2HealthChecker checker = healthChecker();
|
||||
TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 2, 1);
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
|
||||
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("initial", health.state());
|
||||
assertEquals("Elb.InitialHealthChecking", health.reason());
|
||||
assertEquals("Initial health checks in progress", health.description());
|
||||
});
|
||||
} finally {
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoveringTargetRemainsUnhealthyUntilHealthyThresholdIsMet() throws Exception {
|
||||
AtomicInteger statusCode = new AtomicInteger(503);
|
||||
AtomicInteger requestCount = new AtomicInteger();
|
||||
HttpServer server = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
requestCount.incrementAndGet();
|
||||
request.response().setStatusCode(statusCode.get()).end();
|
||||
})
|
||||
.listen(0, "127.0.0.1")
|
||||
.toCompletionStage()
|
||||
.toCompletableFuture()
|
||||
.get(2, TimeUnit.SECONDS);
|
||||
try {
|
||||
ElbV2HealthChecker checker = healthChecker();
|
||||
TargetGroup targetGroup = targetGroup(server.actualPort(), "200", 2, 1);
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
|
||||
checker.addTargets(targetGroup.getTargetGroupArn(), List.of(target), targetGroup);
|
||||
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals(
|
||||
"unhealthy",
|
||||
checker.getHealth(targetGroup.getTargetGroupArn(), target.getId(), target.getPort()).state()));
|
||||
|
||||
statusCode.set(200);
|
||||
checker.addTargets(targetGroup.getTargetGroupArn(), List.of(target), targetGroup);
|
||||
await().atMost(Duration.ofSeconds(2)).until(() -> requestCount.get() >= 2);
|
||||
|
||||
await().during(Duration.ofMillis(250)).atMost(Duration.ofSeconds(1)).untilAsserted(() -> {
|
||||
ElbV2HealthChecker.TargetHealthStatus health = checker.getHealth(
|
||||
targetGroup.getTargetGroupArn(), target.getId(), target.getPort());
|
||||
assertEquals("unhealthy", health.state());
|
||||
assertEquals("Target.ResponseCodeMismatch", health.reason());
|
||||
});
|
||||
} finally {
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void registrationStateCarriesAwsReasonUntilFirstProbeCompletes() {
|
||||
ElbV2HealthChecker checker = healthChecker();
|
||||
|
||||
ElbV2HealthChecker.TargetHealthStatus health = checker.getHealth(
|
||||
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/app/1234",
|
||||
"i-1234567890abcdef0",
|
||||
8080);
|
||||
|
||||
assertEquals("initial", health.state());
|
||||
assertEquals("Elb.RegistrationInProgress", health.reason());
|
||||
assertEquals("Target registration is in progress", health.description());
|
||||
}
|
||||
|
||||
private ElbV2HealthChecker healthChecker() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().elbv2().mock()).thenReturn(false);
|
||||
return new ElbV2HealthChecker(vertx, config, mock(Ec2Service.class));
|
||||
}
|
||||
|
||||
private HttpServer startServer(int statusCode) throws Exception {
|
||||
HttpServer server = vertx.createHttpServer()
|
||||
.requestHandler(request -> request.response().setStatusCode(statusCode).end());
|
||||
return server.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture()
|
||||
.get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private HttpServer startHangingServer() throws Exception {
|
||||
HttpServer server = vertx.createHttpServer()
|
||||
.requestHandler(request -> {});
|
||||
return server.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture()
|
||||
.get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static void close(HttpServer server) throws Exception {
|
||||
CompletableFuture<Void> closed = server.close().toCompletionStage().toCompletableFuture();
|
||||
closed.get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static TargetGroup targetGroup(int port, String matcher, int healthyThreshold, int unhealthyThreshold) {
|
||||
TargetGroup targetGroup = new TargetGroup();
|
||||
targetGroup.setTargetGroupArn(
|
||||
"arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/app/1234");
|
||||
targetGroup.setTargetType("ip");
|
||||
targetGroup.setPort(port);
|
||||
targetGroup.setHealthCheckEnabled(true);
|
||||
targetGroup.setHealthCheckPath("/");
|
||||
targetGroup.setMatcher(matcher);
|
||||
targetGroup.setHealthCheckTimeoutSeconds(1);
|
||||
targetGroup.setHealthyThresholdCount(healthyThreshold);
|
||||
targetGroup.setUnhealthyThresholdCount(unhealthyThreshold);
|
||||
return targetGroup;
|
||||
}
|
||||
|
||||
private static TargetDescription target(String id, int port) {
|
||||
TargetDescription target = new TargetDescription();
|
||||
target.setId(id);
|
||||
target.setPort(port);
|
||||
return target;
|
||||
}
|
||||
}
|
||||
@@ -676,6 +676,27 @@ class ElbV2IntegrationTest {
|
||||
equalTo("Elb.RegistrationInProgress"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(28)
|
||||
void describeTargetHealthReturnsUnusedForExplicitUnregisteredTarget() {
|
||||
given()
|
||||
.formParam("Action", "DescribeTargetHealth")
|
||||
.formParam("TargetGroupArn", tgArn)
|
||||
.formParam("Targets.member.1.Id", "i-1234567890abcdef0")
|
||||
.formParam("Targets.member.1.Port", "80")
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.TargetHealth.State",
|
||||
equalTo("unused"))
|
||||
.body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.TargetHealth.Reason",
|
||||
equalTo("Target.NotRegistered"))
|
||||
.body("DescribeTargetHealthResponse.DescribeTargetHealthResult.TargetHealthDescriptions.member.TargetHealth.Description",
|
||||
equalTo("Target is not registered to the target group"));
|
||||
}
|
||||
|
||||
// ── Listeners ─────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -211,6 +211,20 @@ class ElbV2ServiceTest {
|
||||
assertEquals(listenerArn, listenerCaptor.getValue().getListenerArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeTargetHealthReturnsUnusedForExplicitUnregisteredTarget() {
|
||||
String tgArn = createTargetGroup("sample-tg");
|
||||
TargetDescription target = new TargetDescription();
|
||||
target.setId("i-1234567890abcdef0");
|
||||
target.setPort(9999);
|
||||
|
||||
var health = service.describeTargetHealth(REGION, tgArn, List.of(target)).getFirst();
|
||||
|
||||
assertEquals("unused", health.getState());
|
||||
assertEquals("Target.NotRegistered", health.getReason());
|
||||
assertEquals("Target is not registered to the target group", health.getDescription());
|
||||
}
|
||||
|
||||
private String createTargetGroup(String name) {
|
||||
return service.createTargetGroup(
|
||||
REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",
|
||||
|
||||
Reference in new issue
Block a user