fix(elbv2): honor backend TLS and bound health probes (#7433)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-03 16:29:45 -04:00
1 parent a772b27583
commit 9c2a2c2a02
11 files changed
+1150 -71

No files matched your search

@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.core.common.concurrent;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/** One deadline for socket operations, including peers that continually send incomplete responses. */
public final class SocketDeadline {
private SocketDeadline() {}
public static <T> T call(int timeoutSeconds, Callable<T> operation) throws IOException {
return call(timeoutSeconds, operation, () -> {});
}
/**
* Releases worker ownership before publishing a normal result. Cancelled work retains ownership
* until it actually finishes, even when it ignores interruption.
*/
public static <T> T call(int timeoutSeconds, Callable<T> operation, Runnable onWorkerExit) throws IOException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
AtomicBoolean exited = new AtomicBoolean();
Runnable finish = () -> {
if (exited.compareAndSet(false, true)) {
onWorkerExit.run();
}
};
FutureTask<T> result = new FutureTask<>(() -> {
try {
return operation.call();
} finally {
// Publish an ordinary result only after resource admission is released.
finish.run();
}
});
// Interrupting a virtual thread closes its blocking java.net sockets.
try {
Thread.ofVirtual().name("socket-deadline").start(() -> {
try {
result.run();
} finally {
finish.run();
}
});
} catch (RuntimeException | Error failure) {
finish.run();
throw failure;
}
try {
return result.get(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
} catch (TimeoutException timeout) {
throw new SocketTimeoutException("Socket operation exceeded " + timeoutSeconds + " seconds");
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
InterruptedIOException failure = new InterruptedIOException("Socket operation interrupted");
failure.initCause(interrupted);
throw failure;
} catch (ExecutionException failed) {
Throwable cause = failed.getCause();
if (cause instanceof IOException io) {
throw io;
}
if (cause instanceof RuntimeException runtime) {
throw runtime;
}
if (cause instanceof Error error) {
throw error;
}
throw new IOException("Socket operation failed", cause);
} finally {
result.cancel(true);
}
}
}
@@ -21,6 +21,8 @@ import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.netty.channel.ConnectTimeoutException;
import io.netty.handler.ssl.SslHandshakeTimeoutException;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
@@ -53,6 +55,7 @@ import javax.naming.ldap.Rdn;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
@@ -70,6 +73,8 @@ import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -226,8 +231,12 @@ public class ElbV2DataPlane {
@PostConstruct
void init() {
proxyClient = vertx.createHttpClient(new HttpClientOptions()
.setTrustAll(true)
.setVerifyHost(false)
.setMaxPoolSize(100)
.setConnectTimeout(5000)
.setConnectTimeout(10_000)
.setSslHandshakeTimeout(10)
.setSslHandshakeTimeoutUnit(TimeUnit.SECONDS)
.setKeepAlive(true)
.setMaxHeaderSize(MAX_RESPONSE_HEADER_SIZE));
tcpClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(5000)
@@ -1100,12 +1109,13 @@ public class ElbV2DataPlane {
List<String> cookies = duration > 0 ? stickyCookie.headers(scope, tg, target) : List.of();
int targetPort = ElbV2HealthChecker.effectivePort(target, tg);
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, target);
boolean secure = "HTTPS".equals(tg.getProtocol());
if (isWebSocketUpgrade(req)) {
proxyUpgrade(req, host, targetPort, hostHeader, forwarded,
proxyUpgrade(req, host, targetPort, secure, hostHeader, forwarded,
idleTimeoutMillis(listenerArn, region), cookies);
return;
}
proxyRequest(req, host, targetPort, hostHeader, forwarded, cookies);
proxyRequest(req, host, targetPort, secure, hostHeader, forwarded, cookies);
}
private String loadBalancerAttribute(String listenerArn, String region, String key) {
@@ -1365,20 +1375,20 @@ public class ElbV2DataPlane {
return tuples.get(tuples.size() - 1).getTargetGroupArn();
}
private void proxyRequest(HttpServerRequest req, String host, int port, String hostHeader,
private void proxyRequest(HttpServerRequest req, String host, int port, boolean secure, String hostHeader,
ElbV2ForwardedHeaders forwarded, List<String> cookies) {
req.pause();
if (ElbV2TargetResolver.isIpLiteral(host)) {
try {
proxyRequestTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port,
hostHeader, forwarded, cookies);
secure, hostHeader, forwarded, cookies);
} catch (IOException e) {
rejectTarget(req, host, e);
}
return;
}
vertx.<String>executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
.onSuccess(address -> proxyRequestTo(req, address, host, port, hostHeader, forwarded, cookies))
.onSuccess(address -> proxyRequestTo(req, address, host, port, secure, hostHeader, forwarded, cookies))
.onFailure(err -> rejectTarget(req, host, err));
}
@@ -1388,9 +1398,10 @@ public class ElbV2DataPlane {
req.response().setStatusCode(503).end("Service unavailable");
}
private void proxyRequestTo(HttpServerRequest req, String address, String host, int port,
private void proxyRequestTo(HttpServerRequest req, String address, String host, int port, boolean secure,
String hostHeader, ElbV2ForwardedHeaders forwarded, List<String> cookies) {
RequestOptions opts = new RequestOptions()
.setSsl(secure)
.setHost(address)
.setPort(port)
.setURI(req.uri())
@@ -1442,10 +1453,19 @@ public class ElbV2DataPlane {
clientReq.send(req);
req.resume();
})
.onFailure(err -> {
req.resume();
req.response().setStatusCode(503).end("Service unavailable");
});
.onFailure(err -> backendConnectionFailed(req, err));
}
private void backendConnectionFailed(HttpServerRequest req, Throwable error) {
req.resume();
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
if (cause instanceof ConnectTimeoutException || cause instanceof SslHandshakeTimeoutException
|| cause instanceof SocketTimeoutException || cause instanceof TimeoutException) {
req.response().setStatusCode(504).end("Gateway timeout");
return;
}
}
req.response().setStatusCode(502).end("Bad gateway");
}
private static void copyTargetResponseHeaders(MultiMap headers, HttpServerResponse response) {
@@ -1461,20 +1481,20 @@ public class ElbV2DataPlane {
return WebSocketUpgrades.isHandshake(req);
}
private void proxyUpgrade(HttpServerRequest req, String host, int port, String hostHeader,
private void proxyUpgrade(HttpServerRequest req, String host, int port, boolean secure, String hostHeader,
ElbV2ForwardedHeaders forwarded, long idleTimeoutMillis, List<String> cookies) {
req.pause();
if (ElbV2TargetResolver.isIpLiteral(host)) {
try {
proxyUpgradeTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port,
hostHeader, forwarded, idleTimeoutMillis, cookies);
secure, hostHeader, forwarded, idleTimeoutMillis, cookies);
} catch (IOException e) {
rejectTarget(req, host, e);
}
return;
}
vertx.<String>executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
.onSuccess(address -> proxyUpgradeTo(req, address, host, port, hostHeader,
.onSuccess(address -> proxyUpgradeTo(req, address, host, port, secure, hostHeader,
forwarded, idleTimeoutMillis, cookies))
.onFailure(err -> rejectTarget(req, host, err));
}
@@ -1484,10 +1504,11 @@ public class ElbV2DataPlane {
* relays that answer and joins the two connections into a byte tunnel. Any other answer means
* the target refused the upgrade and is relayed as an ordinary response.
*/
private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port,
private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port, boolean secure,
String hostHeader, ElbV2ForwardedHeaders forwarded,
long idleTimeoutMillis, List<String> cookies) {
RequestOptions opts = new RequestOptions()
.setSsl(secure)
.setHost(address)
.setPort(port)
.setURI(req.uri())
@@ -1541,10 +1562,7 @@ public class ElbV2DataPlane {
}
});
})
.onFailure(err -> {
req.resume();
req.response().setStatusCode(503).end("Service unavailable");
});
.onFailure(err -> backendConnectionFailed(req, err));
}
/**
@@ -2,42 +2,57 @@ package io.github.hectorvent.floci.services.elbv2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.concurrent.SocketDeadline;
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.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.vertx.core.Vertx;
import io.vertx.core.WorkerExecutor;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
@ApplicationScoped
public class ElbV2HealthChecker implements Resettable {
private static final Logger LOG = Logger.getLogger(ElbV2HealthChecker.class);
private static final int MAX_CONCURRENT_PROBES = 32;
private final Vertx vertx;
private final WorkerExecutor probeWorkers;
private final EmulatorConfig config;
private final Ec2Service ec2Service;
private final SSLSocketFactory backendTls = backendTls();
// tgArn → (targetKey → TargetState)
private final Map<String, Map<String, TargetState>> states = new ConcurrentHashMap<>();
// tgArn → timerId
private final Map<String, Long> timers = new ConcurrentHashMap<>();
private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES);
@Inject
public ElbV2HealthChecker(Vertx vertx, EmulatorConfig config, Ec2Service ec2Service) {
this.vertx = vertx;
this.config = config;
this.ec2Service = ec2Service;
this.probeWorkers = vertx.createSharedWorkerExecutor("floci-elbv2-health-probes", MAX_CONCURRENT_PROBES);
}
public static int effectivePort(TargetDescription target, TargetGroup tg) {
@@ -79,6 +94,12 @@ public class ElbV2HealthChecker implements Resettable {
states.clear();
}
@PreDestroy
void destroy() {
clear();
probeWorkers.close();
}
public void addTargets(String tgArn, List<TargetDescription> targets, TargetGroup tg) {
if (config.services().elbv2().mock()) {
return;
@@ -118,7 +139,9 @@ public class ElbV2HealthChecker implements Resettable {
if (s == null) {
return TargetHealthStatus.registrationInProgress();
}
return new TargetHealthStatus(s.status, s.reason, s.description);
synchronized (s) {
return new TargetHealthStatus(s.status, s.reason, s.description);
}
}
public boolean isHealthy(String tgArn, TargetDescription target, int port) {
@@ -145,7 +168,7 @@ public class ElbV2HealthChecker implements Resettable {
} catch (NumberFormatException e) {
continue;
}
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, targetId);
String protocol = tg.getHealthCheckProtocol();
String path = tg.getHealthCheckPath() != null ? tg.getHealthCheckPath() : "/";
String matcher = tg.getMatcher() != null ? tg.getMatcher() : "200";
int timeout = tg.getHealthCheckTimeoutSeconds() != null ? tg.getHealthCheckTimeoutSeconds() : 5;
@@ -153,54 +176,99 @@ public class ElbV2HealthChecker implements Resettable {
int unhealthyThreshold = tg.getUnhealthyThresholdCount() != null ? tg.getUnhealthyThresholdCount() : 2;
int probePort = healthCheckPort(tg, port);
vertx.executeBlocking(() -> {
return probe(host, probePort, path, timeout);
}).onSuccess(statusCode -> {
boolean success = matchesStatusCode(statusCode, matcher);
if (success) {
state.consecutiveFailures = 0;
state.consecutiveSuccesses++;
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;
} 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 + "]";
}
synchronized (state) {
if (state.inFlight || state.workerRunning) {
continue;
}
}).onFailure(err -> {
state.consecutiveSuccesses = 0;
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";
state.inFlight = true;
}
try {
probeWorkers.<Integer>executeBlocking(() -> {
synchronized (state) {
if (states.get(tgArn) != tgStates || tgStates.get(key) != state
|| !probeSlots.tryAcquire()) {
return null;
}
state.workerRunning = true;
}
return SocketDeadline.call(timeout, () -> {
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, targetId);
return probeOnce(host, probePort, path, timeout, protocol);
}, () -> {
synchronized (state) {
state.workerRunning = false;
probeSlots.release();
}
});
}, false).onComplete(outcome -> {
synchronized (state) {
try {
if (states.get(tgArn) != tgStates || tgStates.get(key) != state) {
return;
}
if (outcome.failed()) {
state.consecutiveSuccesses = 0;
state.consecutiveFailures++;
if (state.consecutiveFailures >= unhealthyThreshold) {
state.status = "unhealthy";
if (isTimeout(outcome.cause())) {
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}",
targetId, port, outcome.cause().getMessage());
} else if (outcome.result() != null) {
int statusCode = outcome.result();
if (matchesStatusCode(statusCode, matcher)) {
state.consecutiveFailures = 0;
state.consecutiveSuccesses++;
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;
} 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 + "]";
}
}
}
} finally {
state.inFlight = false;
}
}
});
} catch (RuntimeException | Error error) {
synchronized (state) {
state.inFlight = false;
}
LOG.debugv("Health check failed for {0}:{1} - {2}", host, port, err.getMessage());
});
throw error;
}
}
}
private int probe(String host, int port, String path, int timeoutSeconds) throws IOException {
URL url = new URL("http", ElbV2TargetResolver.resolveCheckedAddress(host), port, path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
private int probeOnce(String host, int port, String path, int timeoutSeconds, String protocol) throws IOException {
String scheme = "HTTPS".equals(protocol) ? "https" : "http";
URL url = new URL(scheme, ElbV2TargetResolver.resolveCheckedAddress(host), port, path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
if (conn instanceof HttpsURLConnection https) {
https.setSSLSocketFactory(backendTls);
https.setHostnameVerifier((hostname, session) -> true);
}
conn.setConnectTimeout(timeoutSeconds * 1000);
conn.setReadTimeout(timeoutSeconds * 1000);
conn.setRequestMethod("GET");
@@ -213,6 +281,17 @@ public class ElbV2HealthChecker implements Resettable {
}
}
private static SSLSocketFactory backendTls() {
try {
// ALB encrypts target connections without validating target certificates.
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
return context.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new IllegalStateException("Cannot initialize ELBv2 backend TLS", e);
}
}
/**
* AWS probes {@code HealthCheckPort} when it is a number and the target's own port when it is
* {@code traffic-port} or unset. Health state stays keyed by the traffic port either way.
@@ -286,6 +365,8 @@ public class ElbV2HealthChecker implements Resettable {
}
private static class TargetState {
boolean inFlight;
boolean workerRunning;
volatile String status = "initial";
volatile String reason = "Elb.RegistrationInProgress";
volatile String description = "Target registration is in progress";
@@ -494,6 +494,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
Integer healthyThreshold, Integer unhealthyThreshold,
String matcher, String ipAddressType,
Map<String, String> initialTags) {
validateHealthCheckTimeout(healthCheckTimeout);
validatePort(port, "port");
validateName(name, "target group");
if (port == null && !"lambda".equals(targetType)) {
@@ -592,6 +593,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
String healthCheckPath, Integer healthCheckInterval,
Integer healthCheckTimeout, Integer healthyThreshold,
Integer unhealthyThreshold, String matcher) {
validateHealthCheckTimeout(healthCheckTimeout);
TargetGroup tg = requireTargetGroup(region, arn);
validateHealthCheckPort(healthCheckPort);
if (healthCheckProtocol != null) tg.setHealthCheckProtocol(healthCheckProtocol);
@@ -606,6 +608,15 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
persistRegion(targetGroups, region);
}
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";
throw new AwsException("ValidationError", "1 validation error detected: Value '" + timeout
+ "' at 'healthCheckTimeoutSeconds' failed to satisfy constraint: Member must have value "
+ constraint, 400);
}
}
public Map<String, String> describeTargetGroupAttributes(String region, String arn) {
TargetGroup tg = requireTargetGroup(region, arn);
return ElbV2DefaultAttributes.merge(ElbV2DefaultAttributes.forTargetGroup(tg), tg.getAttributes());