mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(elbv2): honor backend TLS and bound health probes (#7433)
This commit is contained in:
1 parent
a772b27583
commit
9c2a2c2a02
11 files changed
+1150
-71
No files matched your search
+127
@@ -0,0 +1,127 @@
|
||||
package io.github.hectorvent.floci.core.common.concurrent;
|
||||
|
||||
import io.github.hectorvent.floci.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SocketDeadlineTest {
|
||||
|
||||
@Test
|
||||
void resultWaitsForAdmissionCleanup() throws Exception {
|
||||
assertCleanupBeforeCompletion(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failureWaitsForAdmissionCleanup() throws Exception {
|
||||
assertCleanupBeforeCompletion(true);
|
||||
}
|
||||
|
||||
private void assertCleanupBeforeCompletion(boolean fail) throws Exception {
|
||||
CountDownLatch cleaning = new CountDownLatch(1);
|
||||
CompletableFuture<Void> release = new CompletableFuture<>();
|
||||
AtomicInteger exits = new AtomicInteger();
|
||||
IOException failure = new IOException("probe failed");
|
||||
FutureTask<String> result = new FutureTask<>(() -> SocketDeadline.call(10, () -> {
|
||||
if (fail) {
|
||||
throw failure;
|
||||
}
|
||||
return "healthy";
|
||||
}, () -> {
|
||||
cleaning.countDown();
|
||||
release.join();
|
||||
exits.incrementAndGet();
|
||||
}));
|
||||
Thread caller = Thread.ofVirtual().start(result);
|
||||
try {
|
||||
assertTrue(cleaning.await(5, TimeUnit.SECONDS));
|
||||
ThreadStates.awaitState(caller, Set.of(Thread.State.TIMED_WAITING, Thread.State.TERMINATED),
|
||||
Duration.ofSeconds(5), "probe caller");
|
||||
assertFalse(result.isDone(), "the next queued probe must not run before admission cleanup");
|
||||
} finally {
|
||||
release.complete(null);
|
||||
caller.join(5000);
|
||||
assertFalse(caller.isAlive());
|
||||
}
|
||||
if (fail) {
|
||||
assertSame(failure, assertThrows(ExecutionException.class,
|
||||
() -> result.get(5, TimeUnit.SECONDS)).getCause());
|
||||
} else {
|
||||
assertEquals("healthy", result.get(5, TimeUnit.SECONDS));
|
||||
}
|
||||
assertEquals(1, exits.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedCallerRetainsAdmissionUntilIgnoringWorkerFinishes() throws Exception {
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch exited = new CountDownLatch(1);
|
||||
CompletableFuture<Void> release = new CompletableFuture<>();
|
||||
AtomicInteger exits = new AtomicInteger();
|
||||
FutureTask<String> result = new FutureTask<>(() -> SocketDeadline.call(10, () -> {
|
||||
started.countDown();
|
||||
release.join();
|
||||
return "late";
|
||||
}, () -> {
|
||||
exits.incrementAndGet();
|
||||
exited.countDown();
|
||||
}));
|
||||
Thread caller = Thread.ofVirtual().start(result);
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
caller.interrupt();
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> result.get(5, TimeUnit.SECONDS));
|
||||
assertInstanceOf(InterruptedIOException.class, failure.getCause());
|
||||
assertEquals(0, exits.get(), "cancellation must not release a running probe's permit");
|
||||
} finally {
|
||||
release.complete(null);
|
||||
assertTrue(exited.await(5, TimeUnit.SECONDS));
|
||||
caller.join(5000);
|
||||
assertFalse(caller.isAlive());
|
||||
}
|
||||
assertEquals(1, exits.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredCallsAlwaysReleaseAdmissionExactlyOnce() throws Exception {
|
||||
for (int attempt = 0; attempt < 100; attempt++) {
|
||||
CountDownLatch exited = new CountDownLatch(1);
|
||||
AtomicInteger exits = new AtomicInteger();
|
||||
try {
|
||||
SocketDeadline.call(0, () -> "healthy", () -> {
|
||||
exits.incrementAndGet();
|
||||
exited.countDown();
|
||||
});
|
||||
} catch (SocketTimeoutException expected) {
|
||||
// The deadline may expire before the callable starts; cleanup is still required.
|
||||
}
|
||||
assertTrue(exited.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(1, exits.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupFailureIsReportedOnce() {
|
||||
IllegalStateException failure = new IllegalStateException("cleanup failed");
|
||||
AtomicInteger exits = new AtomicInteger();
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> SocketDeadline.call(10, () -> "healthy", () -> {
|
||||
exits.incrementAndGet();
|
||||
throw failure;
|
||||
})));
|
||||
assertEquals(1, exits.get());
|
||||
}
|
||||
}
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import io.vertx.core.http.UpgradeRejectedException;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
import io.vertx.core.http.WebSocketConnectOptions;
|
||||
import io.vertx.core.net.NetServer;
|
||||
import io.vertx.core.net.NetServerOptions;
|
||||
import io.vertx.core.net.NetSocket;
|
||||
import io.vertx.core.net.PemKeyCertOptions;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.Action;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancer;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.Matcher;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetDescription;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetHealthDescription;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.net.ProxySelector;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
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.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(RealElbV2DataPlaneProfile.class)
|
||||
class ElbV2BackendTlsIntegrationTest {
|
||||
|
||||
private final String name = "alb-tls-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
private final List<Executable> cleanup = new ArrayList<>();
|
||||
private final AtomicInteger healthStatus = new AtomicInteger(200);
|
||||
private final AtomicBoolean encrypted = new AtomicBoolean();
|
||||
private final AtomicReference<String> received = new AtomicReference<>();
|
||||
private Ec2Client ec2;
|
||||
private ElasticLoadBalancingV2Client elb;
|
||||
private String vpc;
|
||||
private List<String> subnets;
|
||||
private String groupArn;
|
||||
private String dns;
|
||||
private int listenerPort;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@BeforeEach
|
||||
void createSdkNetwork() {
|
||||
ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.EU_WEST_1, endpoint);
|
||||
cleanup.add(ec2::close);
|
||||
elb = AwsTestClients.create(ElasticLoadBalancingV2Client.builder(), "test", Region.EU_WEST_1, endpoint);
|
||||
cleanup.add(elb::close);
|
||||
vpc = ec2.createVpc(r -> r.cidrBlock("10.83.0.0/16")).vpc().vpcId();
|
||||
cleanup.add(() -> ec2.deleteVpc(r -> r.vpcId(vpc)));
|
||||
subnets = new ArrayList<>();
|
||||
for (int index = 0; index < 2; index++) {
|
||||
String cidr = "10.83." + index + ".0/24";
|
||||
String zone = "eu-west-1" + (char) ('a' + index);
|
||||
String subnet = ec2.createSubnet(r -> r.vpcId(vpc).cidrBlock(cidr)
|
||||
.availabilityZone(zone)).subnet().subnetId();
|
||||
subnets.add(subnet);
|
||||
cleanup.add(() -> ec2.deleteSubnet(r -> r.subnetId(subnet)));
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeOnlyThisTestsResources() {
|
||||
assertAll(cleanup.reversed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpsTargetUsesTlsEvenWhenItsHealthCheckUsesHttp() throws Exception {
|
||||
HttpServer application = backend(true);
|
||||
HttpServer health = backend(false);
|
||||
createTarget("HTTPS", application.actualPort(), "HTTP", health.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
|
||||
given().baseUri("http://127.0.0.1").port(listenerPort).urlEncodingEnabled(false)
|
||||
.header("Host", dns).header("Authorization", "native-client-signature")
|
||||
.contentType("application/octet-stream").body("native request".getBytes(StandardCharsets.UTF_8))
|
||||
.post("/packages/prepare?version=3%2E0").then().statusCode(200).body(equalTo("native request"));
|
||||
|
||||
assertTrue(encrypted.get());
|
||||
assertEquals("POST /packages/prepare?version=3%2E0 native-client-signature", received.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpTargetCanUseAnIndependentHttpsHealthEndpoint() throws Exception {
|
||||
HttpServer application = backend(false);
|
||||
HttpServer health = backend(true);
|
||||
createTarget("HTTP", application.actualPort(), "HTTPS", health.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
given().baseUri("http://127.0.0.1").port(listenerPort).header("Host", dns)
|
||||
.body("plain target".getBytes(StandardCharsets.UTF_8)).post("/echo")
|
||||
.then().statusCode(200).body(equalTo("plain target"));
|
||||
assertFalse(encrypted.get());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void healthProbeConnectsDirectlyDespiteJvmProxyConfiguration(boolean tls) throws Exception {
|
||||
HttpServer health = backend(tls);
|
||||
AtomicInteger proxied = new AtomicInteger();
|
||||
HttpServer proxy = vertx.createHttpServer().requestHandler(request -> {
|
||||
proxied.incrementAndGet();
|
||||
request.response().setStatusCode(503).end();
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
cleanup.add(() -> proxy.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
ProxySelector previous = ProxySelector.getDefault();
|
||||
ProxySelector.setDefault(new ProxySelector() {
|
||||
@Override
|
||||
public List<Proxy> select(URI uri) {
|
||||
if (uri.getPort() == health.actualPort()) {
|
||||
return List.of(new Proxy(Proxy.Type.HTTP,
|
||||
new InetSocketAddress("127.0.0.1", proxy.actualPort())));
|
||||
}
|
||||
return previous == null ? List.of(Proxy.NO_PROXY) : previous.select(uri);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectFailed(URI uri, SocketAddress address, IOException failure) {
|
||||
fail("Health checks must connect directly to the target: " + uri, failure);
|
||||
}
|
||||
});
|
||||
try {
|
||||
createTarget("HTTP", health.actualPort(), tls ? "HTTPS" : "HTTP", health.actualPort(), "200");
|
||||
await().atMost(Duration.ofSeconds(5)).until(() -> proxied.get() > 0
|
||||
|| "healthy".equals(elb.describeTargetHealth(r -> r.targetGroupArn(groupArn))
|
||||
.targetHealthDescriptions().getFirst().targetHealth().stateAsString()));
|
||||
assertEquals(0, proxied.get(), "The JVM proxy must not receive target health probes");
|
||||
awaitHealth("healthy", null);
|
||||
} finally {
|
||||
ProxySelector.setDefault(previous);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpsHealthRejectsAReachablePlaintextServer() throws Exception {
|
||||
HttpServer plain = backend(false);
|
||||
createTarget("HTTP", plain.actualPort(), "HTTPS", plain.actualPort(), "200");
|
||||
awaitHealth("unhealthy", "Target.FailedHealthChecks");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void httpsTargetNeverFallsBackToPlaintext(boolean websocket) throws Exception {
|
||||
HttpServer plain = backend(false);
|
||||
createTarget("HTTPS", plain.actualPort(), "HTTP", plain.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
|
||||
assertForwardingFailure(websocket, 502);
|
||||
assertNull(received.get(), "The plaintext application must not receive the request");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void unansweredBackendTlsHandshakeReturnsGatewayTimeout(boolean websocket) throws Exception {
|
||||
CompletableFuture<Duration> disconnected = new CompletableFuture<>();
|
||||
AtomicBoolean clientHello = new AtomicBoolean();
|
||||
NetServer stalled = vertx.createNetServer().connectHandler(socket -> {
|
||||
long accepted = System.nanoTime();
|
||||
socket.handler(buffer -> {
|
||||
if (buffer.length() > 0 && buffer.getUnsignedByte(0) == 22) {
|
||||
clientHello.set(true);
|
||||
}
|
||||
});
|
||||
socket.closeHandler(ignored ->
|
||||
disconnected.complete(Duration.ofNanos(System.nanoTime() - accepted)));
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
cleanup.add(() -> stalled.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
HttpServer health = backend(false);
|
||||
createTarget("HTTPS", stalled.actualPort(), "HTTP", health.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
|
||||
assertForwardingFailure(websocket, 504);
|
||||
assertTrue(clientHello.get(), "The backend must receive the real TLS ClientHello");
|
||||
Duration elapsed = disconnected.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(elapsed.compareTo(Duration.ofSeconds(9)) >= 0
|
||||
&& elapsed.compareTo(Duration.ofSeconds(15)) < 0,
|
||||
"An ALB backend TLS handshake has a ten-second deadline: " + elapsed);
|
||||
assertNull(received.get(), "The native wait must end before an application request is sent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpsHealthPreservesCustomMatchersAndRecovers() throws Exception {
|
||||
HttpServer tls = backend(true);
|
||||
healthStatus.set(302);
|
||||
createTarget("HTTPS", tls.actualPort(), "HTTPS", tls.actualPort(), "302");
|
||||
awaitHealth("healthy", null);
|
||||
|
||||
healthStatus.set(503);
|
||||
awaitHealth("unhealthy", "Target.ResponseCodeMismatch");
|
||||
|
||||
elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn)
|
||||
.matcher(Matcher.builder().httpCode("200-299").build()));
|
||||
healthStatus.set(204);
|
||||
awaitHealth("healthy", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingHealthProtocolAndPortReplacesTheProbeSettings() throws Exception {
|
||||
HttpServer plain = backend(false);
|
||||
HttpServer tls = backend(true);
|
||||
createTarget("HTTP", plain.actualPort(), "HTTP", plain.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
|
||||
elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckProtocol("HTTPS"));
|
||||
awaitHealth("unhealthy", "Target.FailedHealthChecks");
|
||||
|
||||
elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckPort(String.valueOf(tls.actualPort())));
|
||||
awaitHealth("healthy", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnansweredTlsHandshakeExpiresAtTheConfiguredHealthTimeout() throws Exception {
|
||||
CompletableFuture<Duration> handshakeWait = new CompletableFuture<>();
|
||||
AtomicBoolean clientHelloReceived = new AtomicBoolean();
|
||||
NetServer stalled = vertx.createNetServer().connectHandler(socket -> {
|
||||
long accepted = System.nanoTime();
|
||||
socket.handler(buffer -> {
|
||||
if (buffer.length() > 0 && buffer.getUnsignedByte(0) == 22) {
|
||||
clientHelloReceived.set(true);
|
||||
}
|
||||
});
|
||||
socket.closeHandler(ignored -> handshakeWait.complete(Duration.ofNanos(System.nanoTime() - accepted)));
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
cleanup.add(() -> stalled.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
HttpServer application = backend(false);
|
||||
createTarget("HTTP", application.actualPort(), "HTTPS", stalled.actualPort(), "200");
|
||||
|
||||
awaitHealth("unhealthy", "Target.Timeout");
|
||||
assertTrue(clientHelloReceived.get(), "The probe must start a real TLS handshake");
|
||||
Duration elapsed = handshakeWait.get(5, TimeUnit.SECONDS);
|
||||
assertTrue(elapsed.compareTo(Duration.ofMillis(1500)) >= 0
|
||||
&& elapsed.compareTo(Duration.ofSeconds(4)) < 0,
|
||||
"The configured two-second timeout must bound the handshake: " + elapsed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void websocketUpgradeUsesTheTargetsHttpsProtocol() throws Exception {
|
||||
HttpServer application = backend(true);
|
||||
HttpServer health = backend(false);
|
||||
createTarget("HTTPS", application.actualPort(), "HTTP", health.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
HttpClient client = vertx.createHttpClient();
|
||||
cleanup.add(() -> client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
WebSocket socket = client.webSocket(new WebSocketConnectOptions().setHost("127.0.0.1")
|
||||
.setPort(listenerPort).setURI("/socket.io/?transport=websocket").addHeader("Host", dns))
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
cleanup.add(() -> socket.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
CompletableFuture<String> reply = new CompletableFuture<>();
|
||||
socket.textMessageHandler(reply::complete);
|
||||
socket.writeTextMessage("native-frame").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
assertEquals("echo:native-frame", reply.get(5, TimeUnit.SECONDS));
|
||||
assertTrue(encrypted.get(), "The WebSocket handshake must reach the backend over TLS");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"HTTP", "HTTPS"})
|
||||
void slowResponseBytesCannotKeepAnUnhealthyTargetHealthy(String protocol) throws Exception {
|
||||
HttpServer healthy = backend("HTTPS".equals(protocol));
|
||||
createTarget(protocol, healthy.actualPort(), protocol, healthy.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
NetServer slow = slowPeer("HTTPS".equals(protocol), false);
|
||||
elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckPort(String.valueOf(slow.actualPort())));
|
||||
|
||||
awaitHealth("unhealthy", "Target.Timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void slowTlsRecordsCannotKeepAnUnhealthyTargetHealthy() throws Exception {
|
||||
HttpServer healthy = backend(false);
|
||||
createTarget("HTTP", healthy.actualPort(), "HTTP", healthy.actualPort(), "200");
|
||||
awaitHealth("healthy", null);
|
||||
NetServer slow = slowPeer(false, true);
|
||||
elb.modifyTargetGroup(r -> r.targetGroupArn(groupArn).healthCheckProtocol("HTTPS")
|
||||
.healthCheckPort(String.valueOf(slow.actualPort())));
|
||||
|
||||
awaitHealth("unhealthy", "Target.Timeout");
|
||||
}
|
||||
|
||||
private NetServer slowPeer(boolean tls, boolean handshake) throws Exception {
|
||||
NetServerOptions options = new NetServerOptions();
|
||||
if (tls) {
|
||||
CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator()
|
||||
.generateSelfSignedCertificate("backend.example.test", List.of(), KeyAlgorithm.RSA_2048);
|
||||
options.setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
|
||||
.setCertValue(Buffer.buffer(certificate.certificatePem()))
|
||||
.setKeyValue(Buffer.buffer(certificate.privateKeyPem())));
|
||||
}
|
||||
List<NetSocket> connections = new CopyOnWriteArrayList<>();
|
||||
List<Long> timers = new CopyOnWriteArrayList<>();
|
||||
List<Duration> closed = new CopyOnWriteArrayList<>();
|
||||
NetServer server = vertx.createNetServer(options).connectHandler(socket -> {
|
||||
connections.add(socket);
|
||||
long accepted = System.nanoTime();
|
||||
socket.handler(ignored -> {});
|
||||
socket.write(handshake ? Buffer.buffer(new byte[]{22, 3, 3, 0, 100})
|
||||
: Buffer.buffer("HTTP/1.1 200 OK\r\nX-Incomplete: "));
|
||||
long timer = vertx.setPeriodic(250, ignored -> socket.write(Buffer.buffer(new byte[]{0})));
|
||||
timers.add(timer);
|
||||
socket.closeHandler(ignored -> {
|
||||
vertx.cancelTimer(timer);
|
||||
closed.add(Duration.ofNanos(System.nanoTime() - accepted));
|
||||
});
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
cleanup.add(() -> {
|
||||
timers.forEach(vertx::cancelTimer);
|
||||
for (NetSocket socket : connections) {
|
||||
socket.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
server.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
});
|
||||
cleanup.add(() -> {
|
||||
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertTrue(closed.size() >= 2,
|
||||
"Both timed-out probe connections must be closed without fixture cleanup"));
|
||||
assertTrue(closed.stream().allMatch(wait -> wait.compareTo(Duration.ofSeconds(4)) < 0),
|
||||
"Peer connections exceeded the configured health deadline: " + closed);
|
||||
});
|
||||
return server;
|
||||
}
|
||||
|
||||
private void assertForwardingFailure(boolean websocket, int status) throws Exception {
|
||||
if (!websocket) {
|
||||
given().baseUri("http://127.0.0.1").port(listenerPort).header("Host", dns)
|
||||
.body("must remain encrypted").post("/should-not-arrive")
|
||||
.then().statusCode(status);
|
||||
return;
|
||||
}
|
||||
HttpClient client = vertx.createHttpClient();
|
||||
cleanup.add(() -> client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
ExecutionException failure = assertThrows(ExecutionException.class, () ->
|
||||
client.webSocket(new WebSocketConnectOptions().setHost("127.0.0.1")
|
||||
.setPort(listenerPort).setURI("/socket.io/").addHeader("Host", dns))
|
||||
.toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS));
|
||||
assertEquals(status, assertInstanceOf(UpgradeRejectedException.class, failure.getCause()).getStatus());
|
||||
}
|
||||
|
||||
private HttpServer backend(boolean tls) throws Exception {
|
||||
HttpServerOptions options = new HttpServerOptions();
|
||||
if (tls) {
|
||||
CertificateGenerator.GeneratedCertificate certificate = new CertificateGenerator()
|
||||
.generateSelfSignedCertificate("backend.example.test", List.of(), KeyAlgorithm.RSA_2048);
|
||||
options.setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions()
|
||||
.setCertValue(Buffer.buffer(certificate.certificatePem()))
|
||||
.setKeyValue(Buffer.buffer(certificate.privateKeyPem())));
|
||||
}
|
||||
HttpServer backend = vertx.createHttpServer(options).requestHandler(request -> {
|
||||
if ("/health".equals(request.path())) {
|
||||
request.response().setStatusCode(healthStatus.get()).putHeader("Location", "/healthy").end();
|
||||
return;
|
||||
}
|
||||
encrypted.set(request.isSSL());
|
||||
received.set(request.method() + " " + request.uri() + " " + request.getHeader("Authorization"));
|
||||
if ("websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
|
||||
request.toWebSocket().onSuccess(socket -> socket.textMessageHandler(
|
||||
message -> socket.writeTextMessage("echo:" + message)));
|
||||
} else {
|
||||
request.body().onSuccess(body -> request.response().end(body));
|
||||
}
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
cleanup.add(() -> backend.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS));
|
||||
return backend;
|
||||
}
|
||||
|
||||
private void createTarget(String protocol, int port, String healthProtocol, int healthPort, String matcher)
|
||||
throws Exception {
|
||||
LoadBalancer loadBalancer = elb.createLoadBalancer(r -> r.name(name).type("application")
|
||||
.subnets(subnets)).loadBalancers().getFirst();
|
||||
String arn = loadBalancer.loadBalancerArn();
|
||||
dns = loadBalancer.dnsName();
|
||||
cleanup.add(() -> elb.deleteLoadBalancer(r -> r.loadBalancerArn(arn)));
|
||||
groupArn = elb.createTargetGroup(r -> r.name(name).protocol(protocol).port(port).vpcId(vpc)
|
||||
.targetType("ip").healthCheckProtocol(healthProtocol).healthCheckPort(String.valueOf(healthPort))
|
||||
.healthCheckPath("/health").healthCheckIntervalSeconds(5).healthCheckTimeoutSeconds(2)
|
||||
.healthyThresholdCount(2).unhealthyThresholdCount(2)
|
||||
.matcher(Matcher.builder().httpCode(matcher).build()))
|
||||
.targetGroups().getFirst().targetGroupArn();
|
||||
cleanup.add(() -> elb.deleteTargetGroup(r -> r.targetGroupArn(groupArn)));
|
||||
try (ServerSocket reservation = new ServerSocket(0)) {
|
||||
listenerPort = reservation.getLocalPort();
|
||||
}
|
||||
String listener = elb.createListener(r -> r.loadBalancerArn(arn).protocol("HTTP").port(listenerPort)
|
||||
.defaultActions(Action.builder().type("forward").targetGroupArn(groupArn).build()))
|
||||
.listeners().getFirst().listenerArn();
|
||||
cleanup.add(() -> elb.deleteListener(r -> r.listenerArn(listener)));
|
||||
elb.registerTargets(r -> r.targetGroupArn(groupArn)
|
||||
.targets(TargetDescription.builder().id("127.0.0.1").port(port).build()));
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
|
||||
try (Socket socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress("127.0.0.1", listenerPort), 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void awaitHealth(String state, String reason) {
|
||||
await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> {
|
||||
List<TargetHealthDescription> targets = elb.describeTargetHealth(r -> r.targetGroupArn(groupArn))
|
||||
.targetHealthDescriptions();
|
||||
assertEquals(1, targets.size());
|
||||
assertEquals(state, targets.getFirst().targetHealth().stateAsString());
|
||||
assertEquals(reason, targets.getFirst().targetHealth().reasonAsString());
|
||||
});
|
||||
}
|
||||
}
|
||||
+187
-2
@@ -2,18 +2,24 @@ 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.ec2.model.Instance;
|
||||
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.Promise;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.VertxOptions;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerResponse;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -22,10 +28,12 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
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.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;
|
||||
@@ -41,6 +49,48 @@ class ElbV2HealthCheckerTest {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().join();
|
||||
}
|
||||
|
||||
@Test
|
||||
void slowProbeDoesNotOccupyTheSharedVertxWorker() throws Exception {
|
||||
Vertx isolated = Vertx.vertx(new VertxOptions().setWorkerPoolSize(1));
|
||||
HttpServer server = null;
|
||||
ElbV2HealthChecker checker = null;
|
||||
CompletableFuture<HttpServerResponse> response = new CompletableFuture<>();
|
||||
try {
|
||||
server = isolated.createHttpServer().requestHandler(request -> response.complete(request.response()))
|
||||
.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().elbv2().mock()).thenReturn(false);
|
||||
checker = new ElbV2HealthChecker(isolated, config, mock(Ec2Service.class));
|
||||
TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
group.setHealthCheckTimeoutSeconds(10);
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
checker.addTargets(group.getTargetGroupArn(), List.of(target), group);
|
||||
HttpServerResponse pendingResponse = response.get(2, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals("unrelated", assertDoesNotThrow(() -> isolated.executeBlocking(() -> "unrelated", false)
|
||||
.toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS)),
|
||||
"A probe awaiting its response must not occupy the shared worker");
|
||||
pendingResponse.end().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
ElbV2HealthChecker observed = checker;
|
||||
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals("healthy",
|
||||
observed.getState(group.getTargetGroupArn(), target.getId(), target.getPort())));
|
||||
} finally {
|
||||
try {
|
||||
if (checker != null) {
|
||||
checker.destroy();
|
||||
}
|
||||
if (response.isDone() && !response.join().ended()) {
|
||||
response.join().end();
|
||||
}
|
||||
if (server != null) {
|
||||
server.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
isolated.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulProbeTransitionsTargetToHealthy() throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
@@ -107,6 +157,100 @@ class ElbV2HealthCheckerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutLookupKeepsOneProbeUntilTheLookupActuallyCompletes() throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
CompletableFuture<Void> entered = new CompletableFuture<>();
|
||||
CompletableFuture<Void> release = new CompletableFuture<>();
|
||||
AtomicInteger lookups = new AtomicInteger();
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
Instance instance = new Instance();
|
||||
instance.setContainerBridgeIp("127.0.0.1");
|
||||
when(ec2.findInstanceById("000000000000", "i-blocked")).thenAnswer(ignored -> {
|
||||
lookups.incrementAndGet();
|
||||
entered.complete(null);
|
||||
// Like a native hostname lookup, join does not stop when its thread is interrupted.
|
||||
release.join();
|
||||
return instance;
|
||||
});
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
ElbV2HealthChecker checker = new ElbV2HealthChecker(vertx, config, ec2);
|
||||
TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
group.setTargetType("instance");
|
||||
TargetDescription blocked = target("i-blocked", server.actualPort());
|
||||
try {
|
||||
checker.addTargets(group.getTargetGroupArn(), List.of(blocked), group);
|
||||
entered.get(2, TimeUnit.SECONDS);
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> assertEquals("Target.Timeout",
|
||||
checker.getHealth(group.getTargetGroupArn(), blocked.getId(), blocked.getPort()).reason()));
|
||||
checker.addTargets(group.getTargetGroupArn(), List.of(target("127.0.0.1", server.actualPort())), group);
|
||||
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> assertEquals("healthy",
|
||||
checker.getState(group.getTargetGroupArn(), "127.0.0.1", server.actualPort())));
|
||||
await().during(Duration.ofMillis(250)).atMost(Duration.ofSeconds(1)).untilAsserted(() -> {
|
||||
checker.probeAll(group.getTargetGroupArn(), group);
|
||||
assertEquals(1, lookups.get(), "A timed-out lookup still owns its target's probe");
|
||||
});
|
||||
release.complete(null);
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
|
||||
checker.probeAll(group.getTargetGroupArn(), group);
|
||||
assertEquals("healthy",
|
||||
checker.getState(group.getTargetGroupArn(), blocked.getId(), blocked.getPort()));
|
||||
});
|
||||
} finally {
|
||||
release.complete(null);
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutLookupsRetainTheirSharedProbeSlotsUntilTheyFinish() throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
CompletableFuture<Void> release = new CompletableFuture<>();
|
||||
AtomicInteger lookups = new AtomicInteger();
|
||||
Ec2Service ec2 = mock(Ec2Service.class);
|
||||
Instance instance = new Instance();
|
||||
instance.setContainerBridgeIp("127.0.0.1");
|
||||
when(ec2.findInstanceById(eq("000000000000"), any())).thenAnswer(invocation -> {
|
||||
if (invocation.<String>getArgument(1).startsWith("i-held-")) {
|
||||
lookups.incrementAndGet();
|
||||
release.join();
|
||||
}
|
||||
return instance;
|
||||
});
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
ElbV2HealthChecker checker = new ElbV2HealthChecker(vertx, config, ec2);
|
||||
TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
group.setTargetType("instance");
|
||||
List<TargetDescription> held = new ArrayList<>();
|
||||
for (int i = 0; i < 32; i++) {
|
||||
held.add(target("i-held-" + i, server.actualPort()));
|
||||
}
|
||||
try {
|
||||
checker.addTargets(group.getTargetGroupArn(), held, group);
|
||||
await().atMost(Duration.ofSeconds(3)).until(() -> lookups.get() == 32);
|
||||
await().atMost(Duration.ofSeconds(3)).until(() -> held.stream().allMatch(target ->
|
||||
"Target.Timeout".equals(checker.getHealth(
|
||||
group.getTargetGroupArn(), target.getId(), target.getPort()).reason())));
|
||||
checker.addTargets(group.getTargetGroupArn(), List.of(target("127.0.0.1", server.actualPort())), group);
|
||||
await().during(Duration.ofMillis(250)).atMost(Duration.ofSeconds(1)).untilAsserted(() -> {
|
||||
checker.probeAll(group.getTargetGroupArn(), group);
|
||||
assertEquals(32, lookups.get());
|
||||
assertEquals("initial", checker.getState(
|
||||
group.getTargetGroupArn(), "127.0.0.1", server.actualPort()),
|
||||
"An expired caller deadline must not release a still-running worker's slot");
|
||||
});
|
||||
release.complete(null);
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> {
|
||||
checker.probeAll(group.getTargetGroupArn(), group);
|
||||
assertEquals("healthy",
|
||||
checker.getState(group.getTargetGroupArn(), "127.0.0.1", server.actualPort()));
|
||||
});
|
||||
} finally {
|
||||
release.complete(null);
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstSuccessfulProbeMakesNewTargetHealthyRegardlessOfRecoveryThreshold() throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
@@ -231,7 +375,9 @@ class ElbV2HealthCheckerTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
void initialAdmissionRespectsTargetGroupKind(String protocol, int requiredSuccesses) {
|
||||
Vertx immediate = mock(Vertx.class);
|
||||
when(immediate.executeBlocking(any(Callable.class))).thenReturn(Future.succeededFuture(200));
|
||||
WorkerExecutor workers = mock(WorkerExecutor.class);
|
||||
when(immediate.createSharedWorkerExecutor("floci-elbv2-health-probes", 32)).thenReturn(workers);
|
||||
when(workers.executeBlocking(any(Callable.class), eq(false))).thenReturn(Future.succeededFuture(200));
|
||||
doAnswer(invocation -> {
|
||||
Handler<Long> callback = invocation.getArgument(1);
|
||||
callback.handle(1L);
|
||||
@@ -265,7 +411,9 @@ class ElbV2HealthCheckerTest {
|
||||
@SuppressWarnings("unchecked")
|
||||
void periodicProbeRetainsIntervalAndNetworkAdmissionThreshold() {
|
||||
Vertx scheduled = mock(Vertx.class);
|
||||
when(scheduled.executeBlocking(any(Callable.class))).thenReturn(Future.succeededFuture(200));
|
||||
WorkerExecutor workers = mock(WorkerExecutor.class);
|
||||
when(scheduled.createSharedWorkerExecutor("floci-elbv2-health-probes", 32)).thenReturn(workers);
|
||||
when(workers.executeBlocking(any(Callable.class), eq(false))).thenReturn(Future.succeededFuture(200));
|
||||
AtomicReference<Handler<Long>> periodic = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
Handler<Long> callback = invocation.getArgument(1);
|
||||
@@ -297,6 +445,43 @@ class ElbV2HealthCheckerTest {
|
||||
assertEquals("initial", checker.getState(group.getTargetGroupArn(), target.getId(), target.getPort()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"false", "true"})
|
||||
@SuppressWarnings("unchecked")
|
||||
void queuedProbeRetainsItsHealthProtocol(boolean changeProtocol) throws Exception {
|
||||
HttpServer server = startServer(200);
|
||||
try {
|
||||
Vertx queued = mock(Vertx.class);
|
||||
WorkerExecutor workers = mock(WorkerExecutor.class);
|
||||
when(queued.createSharedWorkerExecutor("floci-elbv2-health-probes", 32)).thenReturn(workers);
|
||||
AtomicReference<Callable<Integer>> work = new AtomicReference<>();
|
||||
Promise<Integer> result = Promise.promise();
|
||||
when(workers.executeBlocking(any(Callable.class), eq(false))).thenAnswer(invocation -> {
|
||||
work.set(invocation.getArgument(0));
|
||||
return result.future();
|
||||
});
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().elbv2().mock()).thenReturn(false);
|
||||
ElbV2HealthChecker checker = new ElbV2HealthChecker(queued, config, mock(Ec2Service.class));
|
||||
TargetGroup group = targetGroup(server.actualPort(), "200", 1, 1);
|
||||
group.setHealthCheckProtocol("HTTP");
|
||||
TargetDescription target = target("127.0.0.1", server.actualPort());
|
||||
checker.addTargets(group.getTargetGroupArn(), List.of(target), group);
|
||||
checker.probeAll(group.getTargetGroupArn(), group);
|
||||
if (changeProtocol) {
|
||||
group.setHealthCheckProtocol("HTTPS");
|
||||
}
|
||||
|
||||
int status = assertDoesNotThrow(() -> work.get().call(),
|
||||
"A queued HTTP probe must keep its captured protocol");
|
||||
result.complete(status);
|
||||
assertEquals(200, status);
|
||||
assertEquals("healthy", checker.getState(group.getTargetGroupArn(), target.getId(), target.getPort()));
|
||||
} finally {
|
||||
close(server);
|
||||
}
|
||||
}
|
||||
|
||||
private ElbV2HealthChecker healthChecker() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().elbv2().mock()).thenReturn(false);
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.testing.AwsTestClients;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.ElasticLoadBalancingV2Exception;
|
||||
import software.amazon.awssdk.services.elasticloadbalancingv2.model.TargetGroup;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class ElbV2HealthTimeoutIntegrationTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {-1, 0, 1, 121})
|
||||
void invalidTimeoutRejectsCreateAndPreservesUpdatedGroup(int timeout) {
|
||||
try (ElasticLoadBalancingV2Client client = AwsTestClients.create(
|
||||
ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) {
|
||||
String name = "timeout-rejected-" + Math.abs(timeout);
|
||||
ElasticLoadBalancingV2Exception createError = assertThrows(ElasticLoadBalancingV2Exception.class,
|
||||
() -> client.createTargetGroup(b -> b.name(name).targetType("ip").protocol("HTTP")
|
||||
.port(80).healthCheckTimeoutSeconds(timeout)));
|
||||
assertEquals("ValidationError", createError.awsErrorDetails().errorCode());
|
||||
assertTrue(client.describeTargetGroups().targetGroups().stream()
|
||||
.noneMatch(group -> name.equals(group.targetGroupName())));
|
||||
String arn = client.createTargetGroup(b -> b.name(name).targetType("ip").protocol("HTTP")
|
||||
.port(80).healthCheckPath("/original")).targetGroups().getFirst().targetGroupArn();
|
||||
try {
|
||||
ElasticLoadBalancingV2Exception modifyError = assertThrows(ElasticLoadBalancingV2Exception.class,
|
||||
() -> client.modifyTargetGroup(b -> b.targetGroupArn(arn)
|
||||
.healthCheckPath("/changed").healthCheckTimeoutSeconds(timeout)));
|
||||
assertEquals("ValidationError", modifyError.awsErrorDetails().errorCode());
|
||||
TargetGroup group = client.describeTargetGroups(b -> b.targetGroupArns(arn))
|
||||
.targetGroups().getFirst();
|
||||
assertEquals("/original", group.healthCheckPath());
|
||||
assertEquals(5, group.healthCheckTimeoutSeconds());
|
||||
} finally {
|
||||
client.deleteTargetGroup(b -> b.targetGroupArn(arn));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void upperBoundValidationPrecedesMissingGroupLookup() {
|
||||
try (ElasticLoadBalancingV2Client client = AwsTestClients.create(
|
||||
ElasticLoadBalancingV2Client.builder(), "000000000000", Region.US_EAST_1)) {
|
||||
String arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:"
|
||||
+ "targetgroup/timeout-missing/0000000000000000";
|
||||
ElasticLoadBalancingV2Exception error = assertThrows(ElasticLoadBalancingV2Exception.class,
|
||||
() -> client.modifyTargetGroup(b -> b.targetGroupArn(arn).healthCheckTimeoutSeconds(121)));
|
||||
assertEquals("ValidationError", error.awsErrorDetails().errorCode());
|
||||
assertTrue(error.getMessage().contains("less than or equal to 120"));
|
||||
for (int timeout : new int[]{2, 120}) {
|
||||
ElasticLoadBalancingV2Exception missing = assertThrows(ElasticLoadBalancingV2Exception.class,
|
||||
() -> client.modifyTargetGroup(b -> b.targetGroupArn(arn).healthCheckTimeoutSeconds(timeout)));
|
||||
assertEquals("TargetGroupNotFound", missing.awsErrorDetails().errorCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -180,7 +180,7 @@ class ElbV2PreserveHostHeaderIntegrationTest {
|
||||
|
||||
BufferedReader input = new BufferedReader(
|
||||
new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1));
|
||||
assertEquals(503, readStatus(input));
|
||||
assertEquals(502, readStatus(input));
|
||||
|
||||
output.write(("GET /healthy HTTP/1.1\r\n"
|
||||
+ "Host: " + host + "\r\n"
|
||||
|
||||
@@ -1225,6 +1225,52 @@ class ElbV2ServiceTest {
|
||||
return target;
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {-1, 0, 1, 121, Integer.MAX_VALUE})
|
||||
void createRejectsInvalidHealthTimeoutBeforePublishing(int timeout) {
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.createTargetGroup(
|
||||
REGION, "invalid-timeout", "HTTP", "HTTP1", 80, "vpc-a", "ip",
|
||||
"HTTP", "traffic-port", true, "/", 30, timeout, 5, 2, "200", "ipv4", Map.of()));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("healthCheckTimeoutSeconds"));
|
||||
assertTrue(service.describeTargetGroups(REGION, null, null, null).isEmpty());
|
||||
verifyNoInteractions(healthChecker);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {-1, 0, 1, 121, Integer.MAX_VALUE})
|
||||
void modifyRejectsInvalidHealthTimeoutBeforeAnyMutation(int timeout) {
|
||||
String arn = createTargetGroup("timeout-state");
|
||||
AwsException error = assertThrows(AwsException.class, () -> service.modifyTargetGroup(
|
||||
REGION, arn, "HTTPS", "443", false, "/changed", 60, timeout, 3, 4, "204"));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
TargetGroup group = service.describeTargetGroups(REGION, null, List.of(arn), null).getFirst();
|
||||
assertEquals("HTTP", group.getHealthCheckProtocol());
|
||||
assertEquals("traffic-port", group.getHealthCheckPort());
|
||||
assertTrue(group.getHealthCheckEnabled());
|
||||
assertEquals("/v1/ready", group.getHealthCheckPath());
|
||||
assertEquals(30, group.getHealthCheckIntervalSeconds());
|
||||
assertEquals(5, group.getHealthCheckTimeoutSeconds());
|
||||
assertEquals(5, group.getHealthyThresholdCount());
|
||||
assertEquals(2, group.getUnhealthyThresholdCount());
|
||||
assertEquals("200", group.getMatcher());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {2, 120})
|
||||
void healthTimeoutBoundariesAndOmittedUpdateRemainValid(int timeout) {
|
||||
TargetGroup group = service.createTargetGroup(REGION, "timeout-boundary", "HTTP", "HTTP1", 80,
|
||||
"vpc-a", "ip", "HTTP", "traffic-port", true, "/", 30, timeout, 5, 2,
|
||||
"200", "ipv4", Map.of());
|
||||
assertEquals(timeout, group.getHealthCheckTimeoutSeconds());
|
||||
service.modifyTargetGroup(REGION, group.getTargetGroupArn(), null, null, null,
|
||||
"/changed", null, null, null, null, null);
|
||||
assertEquals(timeout, group.getHealthCheckTimeoutSeconds());
|
||||
service.modifyTargetGroup(REGION, group.getTargetGroupArn(), null, null, null,
|
||||
null, null, timeout == 2 ? 120 : 2, null, null, null);
|
||||
assertEquals(timeout == 2 ? 120 : 2, group.getHealthCheckTimeoutSeconds());
|
||||
}
|
||||
|
||||
private String createTargetGroup(String name) {
|
||||
return service.createTargetGroup(
|
||||
REGION, name, "HTTP", "HTTP1", 9999, "vpc-a", "instance",
|
||||
|
||||
Reference in new issue
Block a user