mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(elbv2): retain listeners through transient bind failures (#7440)
This commit is contained in:
1 parent
7f1f22e87c
commit
ae041d690d
7 files changed
+322
-15
No files matched your search
+114
-3
@@ -38,6 +38,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.github.hectorvent.floci.services.elbv2.ElbV2PublicationTestSupport.publishRuntime;
|
||||
@@ -52,6 +53,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
@@ -444,7 +446,7 @@ class ElbV2ListenerOwnershipTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedClosePermitsABoundedBindAttemptAndIdenticalPublicationCanRetry() {
|
||||
void failedCloseRetainsListenersUntilBackgroundBindRetry() {
|
||||
Fixture fixture = new Fixture(new Registry());
|
||||
Promise<Void> close = Promise.promise();
|
||||
Listener first = listener("first", 8443, false);
|
||||
@@ -462,7 +464,7 @@ class ElbV2ListenerOwnershipTest {
|
||||
close.fail(new IllegalStateException("controlled close failure"));
|
||||
assertEquals(2, fixture.creations(8443));
|
||||
assertEquals(1, fixture.closes(8443), "failed replacement must be closed");
|
||||
publishRuntime(fixture.plane, second, REGION, second.getPort(), List.of(rule("second")));
|
||||
fixture.runNextTimer();
|
||||
assertEquals(3, fixture.creations(8443));
|
||||
fixture.serves(8443, "second");
|
||||
fixture.serves(9443, "unrelated");
|
||||
@@ -472,6 +474,95 @@ class ElbV2ListenerOwnershipTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void bindRetryWaitsForBothTimerAndFailedServerClose(boolean timerFirst) {
|
||||
Registry registry = new Registry();
|
||||
Fixture fixture = new Fixture(registry);
|
||||
Promise<Void> close = Promise.promise();
|
||||
Listener listener = listener("delayed-close", 8443, false);
|
||||
try {
|
||||
fixture.nextClose = close;
|
||||
fixture.failNextListenPort = 8443;
|
||||
publishRuntime(fixture.plane, listener, REGION, null, List.of(rule("recovered")));
|
||||
assertEquals(1, fixture.creations(8443));
|
||||
assertEquals(1, fixture.closes(8443));
|
||||
assertTrue(registry.containsKey(listener.getListenerArn()));
|
||||
if (timerFirst) {
|
||||
fixture.runNextTimer();
|
||||
assertEquals(1, fixture.creations(8443), "timer must not bind while close is pending");
|
||||
close.complete();
|
||||
} else {
|
||||
close.complete();
|
||||
assertEquals(1, fixture.creations(8443), "close must not bypass the retry timer");
|
||||
fixture.runNextTimer();
|
||||
}
|
||||
assertEquals(2, fixture.creations(8443));
|
||||
assertTrue(fixture.timers.isEmpty());
|
||||
fixture.serves(8443, "recovered");
|
||||
} finally {
|
||||
close.tryComplete();
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedBindFailuresBackOffWithoutDuplicatingPublication() {
|
||||
Fixture fixture = new Fixture(new Registry());
|
||||
Listener listener = listener("retry", 8443, false);
|
||||
try {
|
||||
fixture.failNextListenPort = 8443;
|
||||
publishRuntime(fixture.plane, listener, REGION, null, List.of(rule("retry")));
|
||||
for (long delay : List.of(100L, 200L, 400L, 800L, 1600L, 3200L, 5000L, 5000L)) {
|
||||
int creations = fixture.creations(8443);
|
||||
publishRuntime(fixture.plane, listener, REGION, listener.getPort(), List.of(rule("retry")));
|
||||
assertEquals(creations, fixture.creations(8443), "publication must not bypass an outstanding retry");
|
||||
assertEquals(1, fixture.timers.size());
|
||||
assertEquals(delay, fixture.nextTimerDelay);
|
||||
fixture.failNextListenPort = 8443;
|
||||
fixture.runNextTimer();
|
||||
}
|
||||
fixture.runNextTimer();
|
||||
fixture.serves(8443, "retry");
|
||||
assertTrue(fixture.timers.isEmpty());
|
||||
fixture.failNextListenPort = 8443;
|
||||
publishRuntime(fixture.plane, listener("retry", 8443, true), REGION, 8443, List.of(rule("retry")));
|
||||
assertEquals(100, fixture.nextTimerDelay, "a successful bind resets the next recovery delay");
|
||||
fixture.runNextTimer();
|
||||
fixture.serves(8443, "retry");
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void retirementCancelsBindRetryAndItsQueuedCallbackCannotReviveTheListener(boolean shutdown) {
|
||||
Fixture fixture = new Fixture(new Registry());
|
||||
Listener listener = listener("retiring", 8443, false);
|
||||
try {
|
||||
fixture.failNextListenPort = 8443;
|
||||
publishRuntime(fixture.plane, listener, REGION, null, List.of(rule("retiring")));
|
||||
Map.Entry<Long, Handler<Long>> pending = fixture.timers.entrySet().iterator().next();
|
||||
if (shutdown) {
|
||||
fixture.plane.shutdown();
|
||||
} else {
|
||||
removeRuntime(fixture.plane, listener.getListenerArn(), listener.getPort());
|
||||
}
|
||||
assertTrue(fixture.timers.isEmpty());
|
||||
pending.getValue().handle(pending.getKey());
|
||||
assertEquals(1, fixture.creations(8443));
|
||||
if (!shutdown) {
|
||||
publishRuntime(fixture.plane, listener("replacement", 8443, false), REGION, null, List.of(rule("replacement")));
|
||||
pending.getValue().handle(pending.getKey());
|
||||
assertEquals(2, fixture.creations(8443));
|
||||
fixture.serves(8443, "replacement");
|
||||
}
|
||||
} finally {
|
||||
fixture.plane.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Registry extends ConcurrentHashMap<String, ElbV2DataPlane.ListenerBinding> {
|
||||
private final CountDownLatch entered = new CountDownLatch(1);
|
||||
private final CountDownLatch release = new CountDownLatch(1);
|
||||
@@ -531,6 +622,10 @@ class ElbV2ListenerOwnershipTest {
|
||||
private final Map<Integer, AtomicInteger> created = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, AtomicInteger> closed = new ConcurrentHashMap<>();
|
||||
private final Map<Integer, HttpServer> servers = new ConcurrentHashMap<>();
|
||||
private final Map<Long, Handler<Long>> timers = new ConcurrentHashMap<>();
|
||||
private final AtomicLong timerSequence = new AtomicLong();
|
||||
private long nextTimerDelay;
|
||||
private Promise<Void> nextClose;
|
||||
private volatile int failNextListenPort = -1;
|
||||
|
||||
private Fixture(Registry registry) {
|
||||
@@ -554,6 +649,14 @@ class ElbV2ListenerOwnershipTest {
|
||||
CertificateMaterial material = new CertificateMaterial(CERTIFICATE, pair.certificatePem(), pair.privateKeyPem(), null);
|
||||
when(plane.certificateResolver.publishedMaterial(anyString(), eq(REGION), eq(CERTIFICATE))).thenReturn(material);
|
||||
plane.vertx = mock(Vertx.class);
|
||||
when(plane.vertx.setTimer(anyLong(), any())).thenAnswer(call -> {
|
||||
long timer = timerSequence.incrementAndGet();
|
||||
nextTimerDelay = call.getArgument(0);
|
||||
timers.put(timer, call.getArgument(1));
|
||||
return timer;
|
||||
});
|
||||
when(plane.vertx.cancelTimer(anyLong())).thenAnswer(call ->
|
||||
timers.remove(call.<Long>getArgument(0)) != null);
|
||||
when(plane.vertx.createHttpServer(any(HttpServerOptions.class))).thenAnswer(call -> {
|
||||
int port = ((HttpServerOptions) call.getArgument(0)).getPort();
|
||||
created.computeIfAbsent(port, ignored -> new AtomicInteger()).incrementAndGet();
|
||||
@@ -572,7 +675,9 @@ class ElbV2ListenerOwnershipTest {
|
||||
});
|
||||
when(server.close()).thenAnswer(ignored -> {
|
||||
closed.computeIfAbsent(port, key -> new AtomicInteger()).incrementAndGet();
|
||||
return Future.succeededFuture();
|
||||
Promise<Void> pending = nextClose;
|
||||
nextClose = null;
|
||||
return pending == null ? Future.succeededFuture() : pending.future();
|
||||
});
|
||||
when(server.updateSSLOptions(any(SSLOptions.class), eq(true))).thenReturn(Future.succeededFuture(true));
|
||||
return server;
|
||||
@@ -584,6 +689,12 @@ class ElbV2ListenerOwnershipTest {
|
||||
return count == null ? 0 : count.get();
|
||||
}
|
||||
|
||||
private void runNextTimer() {
|
||||
assertEquals(1, timers.size());
|
||||
long timer = timers.keySet().iterator().next();
|
||||
timers.remove(timer).handle(timer);
|
||||
}
|
||||
|
||||
private int closes(int port) {
|
||||
AtomicInteger count = closed.get(port);
|
||||
return count == null ? 0 : count.get();
|
||||
|
||||
@@ -408,7 +408,7 @@ class ElbV2ReservedPortTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"factory", "handler", "listen", "failed-future"})
|
||||
void identicalStartRecoversFromServerAcquisitionFailure(String stage) {
|
||||
void listenerRecoversFromServerAcquisitionFailure(String stage) {
|
||||
ElbV2DataPlane dataPlane = dataPlaneWith(4566, false, 0);
|
||||
EmulatorConfig.ElbV2ServiceConfig elb = mock(EmulatorConfig.ElbV2ServiceConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
@@ -454,6 +454,13 @@ class ElbV2ReservedPortTest {
|
||||
verify(failed).close();
|
||||
}
|
||||
publishRuntime(dataPlane, listener, "us-west-2", listener.getPort(), List.of(fixedRule("recovered")));
|
||||
if ("failed-future".equals(stage)) {
|
||||
verify(replacement, never()).listen();
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Handler<Long>> retry = ArgumentCaptor.forClass(Handler.class);
|
||||
verify(dataPlane.vertx).setTimer(eq(100L), retry.capture());
|
||||
retry.getValue().handle(0L);
|
||||
}
|
||||
verify(replacement).listen();
|
||||
assertFixedResponse(replacement, "retry.example.test", "recovered");
|
||||
removeRuntime(dataPlane, listener.getListenerArn(), listener.getPort());
|
||||
|
||||
+46
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile;
|
||||
import io.github.hectorvent.floci.testutil.LogCapture;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -55,6 +56,7 @@ import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyStore;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -362,6 +364,50 @@ class ElbV2TcpDataPlaneIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = ProtocolEnum.class, names = {"TCP", "HTTP"})
|
||||
void listenerStartsAfterExternalPortOwnerReleasesIt(ProtocolEnum protocol) throws Exception {
|
||||
LoadBalancer other = client.createLoadBalancer(request -> request.name("tcp-regression-occupied")
|
||||
.type(protocol == ProtocolEnum.TCP ? LoadBalancerTypeEnum.NETWORK : LoadBalancerTypeEnum.APPLICATION)
|
||||
.subnets(Ec2Service.defaultSubnetId("us-east-1", "a"),
|
||||
Ec2Service.defaultSubnetId("us-east-1", "b")))
|
||||
.loadBalancers().getFirst();
|
||||
try (ServerSocket occupied = new ServerSocket(0)) {
|
||||
int port = occupied.getLocalPort();
|
||||
Action action = protocol == ProtocolEnum.TCP
|
||||
? Action.builder().type(ActionTypeEnum.FORWARD).targetGroupArn(targetGroupArn).build()
|
||||
: Action.builder().type(ActionTypeEnum.FIXED_RESPONSE).fixedResponseConfig(
|
||||
FixedResponseActionConfig.builder().statusCode("200").contentType("text/plain")
|
||||
.messageBody("recovered").build()).build();
|
||||
Listener created = LogCapture.awaitRecord(ElbV2DataPlane.class, Duration.ofSeconds(5),
|
||||
record -> record.getMessage().contains("listener port failed to start")
|
||||
&& record.getParameters() != null
|
||||
&& Arrays.asList(record.getParameters()).contains(Integer.toString(port)),
|
||||
() -> client.createListener(request -> request.loadBalancerArn(other.loadBalancerArn())
|
||||
.protocol(protocol).port(port).defaultActions(action)).listeners().getFirst());
|
||||
assertEquals(created.listenerArn(), client.describeListeners(request -> request
|
||||
.loadBalancerArn(other.loadBalancerArn())).listeners().getFirst().listenerArn());
|
||||
occupied.close();
|
||||
|
||||
await().atMost(Duration.ofSeconds(5)).ignoreExceptions().untilAsserted(() -> {
|
||||
try (Socket socket = connect(port)) {
|
||||
if (protocol == ProtocolEnum.TCP) {
|
||||
assertEcho(socket, new byte[]{0, 9, 13, 10});
|
||||
} else {
|
||||
socket.setSoTimeout(2000);
|
||||
socket.getOutputStream().write(("GET / HTTP/1.1\r\nHost: " + other.dnsName()
|
||||
+ "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
|
||||
assertTrue(response.startsWith("HTTP/1.1 200"), response);
|
||||
assertTrue(response.endsWith("recovered"), response);
|
||||
}
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
client.deleteLoadBalancer(request -> request.loadBalancerArn(other.loadBalancerArn()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tcpConnectionsUseRoundRobinAndKeepTheirSelectedTarget() throws Exception {
|
||||
NetServer second = vertx.createNetServer().connectHandler(socket -> socket.handler(buffer -> {
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
package io.github.hectorvent.floci.testutil;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
@@ -14,13 +20,36 @@ public final class LogCapture {
|
||||
}
|
||||
|
||||
public static List<LogRecord> capture(Class<?> source, Runnable action) {
|
||||
List<LogRecord> records = new ArrayList<>();
|
||||
withHandler(source, records::add, () -> {
|
||||
action.run();
|
||||
return null;
|
||||
});
|
||||
return records;
|
||||
}
|
||||
|
||||
/** Runs the action with capture installed, then waits for a matching asynchronous record. */
|
||||
public static <T> T awaitRecord(Class<?> source, Duration timeout, Predicate<LogRecord> matches,
|
||||
Supplier<T> action) {
|
||||
CompletableFuture<LogRecord> matched = new CompletableFuture<>();
|
||||
return withHandler(source, record -> {
|
||||
if (matches.test(record)) {
|
||||
matched.complete(record);
|
||||
}
|
||||
}, () -> {
|
||||
T result = action.get();
|
||||
matched.orTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS).join();
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
private static <T> T withHandler(Class<?> source, Consumer<LogRecord> observer, Supplier<T> action) {
|
||||
Logger logger = Logger.getLogger(source.getName());
|
||||
Level originalLevel = logger.getLevel();
|
||||
List<LogRecord> records = new ArrayList<>();
|
||||
Handler handler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
records.add(record);
|
||||
observer.accept(record);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -35,11 +64,10 @@ public final class LogCapture {
|
||||
logger.addHandler(handler);
|
||||
try {
|
||||
logger.setLevel(Level.ALL);
|
||||
action.run();
|
||||
return action.get();
|
||||
} finally {
|
||||
logger.removeHandler(handler);
|
||||
logger.setLevel(originalLevel);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
package io.github.hectorvent.floci.testutil;
|
||||
|
||||
import io.github.hectorvent.floci.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -49,4 +59,61 @@ class LogCaptureTest {
|
||||
logger.setLevel(originalLevel);
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void awaitsMatchingRecordAfterActionReturns() throws Exception {
|
||||
Logger logger = Logger.getLogger(LogCaptureTest.class.getName());
|
||||
Level originalLevel = logger.getLevel();
|
||||
int originalHandlerCount = logger.getHandlers().length;
|
||||
CountDownLatch actionReturned = new CountDownLatch(1);
|
||||
FutureTask<String> task = new FutureTask<>(() -> LogCapture.awaitRecord(LogCaptureTest.class,
|
||||
Duration.ofSeconds(5), record -> "matched".equals(record.getMessage()), () -> {
|
||||
actionReturned.countDown();
|
||||
return "action result";
|
||||
}));
|
||||
Thread worker = new Thread(task);
|
||||
worker.start();
|
||||
try {
|
||||
assertTrue(actionReturned.await(5, TimeUnit.SECONDS));
|
||||
ThreadStates.awaitState(worker, Set.of(Thread.State.WAITING), Duration.ofSeconds(5), "log waiter");
|
||||
logger.info("unrelated");
|
||||
assertFalse(task.isDone(), "an unrelated record must not release the waiter");
|
||||
logger.info("matched");
|
||||
assertEquals("action result", task.get(5, TimeUnit.SECONDS));
|
||||
assertEquals(originalLevel, logger.getLevel());
|
||||
assertEquals(originalHandlerCount, logger.getHandlers().length);
|
||||
} finally {
|
||||
logger.info("matched");
|
||||
worker.join(6000);
|
||||
assertFalse(worker.isAlive(), "log waiter exited");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitRestoresLoggerWhenNoRecordMatches() {
|
||||
Logger logger = Logger.getLogger(LogCaptureTest.class.getName());
|
||||
Level originalLevel = logger.getLevel();
|
||||
int originalHandlerCount = logger.getHandlers().length;
|
||||
CompletionException failure = assertThrows(CompletionException.class, () ->
|
||||
LogCapture.awaitRecord(LogCaptureTest.class, Duration.ZERO,
|
||||
record -> "missing".equals(record.getMessage()), () -> {
|
||||
logger.info("unrelated");
|
||||
return null;
|
||||
}));
|
||||
assertInstanceOf(TimeoutException.class, failure.getCause());
|
||||
assertEquals(originalLevel, logger.getLevel());
|
||||
assertEquals(originalHandlerCount, logger.getHandlers().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void awaitRestoresLoggerWhenActionThrows() {
|
||||
Logger logger = Logger.getLogger(LogCaptureTest.class.getName());
|
||||
Level originalLevel = logger.getLevel();
|
||||
int originalHandlerCount = logger.getHandlers().length;
|
||||
assertThrows(IllegalStateException.class, () -> LogCapture.awaitRecord(LogCaptureTest.class,
|
||||
Duration.ofSeconds(5), record -> true, () -> {
|
||||
throw new IllegalStateException("failed action");
|
||||
}));
|
||||
assertEquals(originalLevel, logger.getLevel());
|
||||
assertEquals(originalHandlerCount, logger.getHandlers().length);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user