diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java b/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java index 33041bc0cf..a9f1b315e7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/KarapaceManager.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.pipes; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ContainerTeardown; import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerDetector; @@ -22,6 +23,7 @@ import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @@ -35,7 +37,7 @@ import java.util.stream.Collectors; * (multiple Pipes reading the same cluster share one Karapace instance). */ @ApplicationScoped -class KarapaceManager { +class KarapaceManager implements ContainerTeardown { private static final Logger LOG = Logger.getLogger(KarapaceManager.class); private static final int REST_PORT = 8082; @@ -49,7 +51,14 @@ class KarapaceManager { private final DockerHostResolver dockerHostResolver; private final Duration readyTimeout; private final Map restBaseUriByTarget = new ConcurrentHashMap<>(); - private final Map containerIdByTarget = new ConcurrentHashMap<>(); + private final Map containersByTarget = new ConcurrentHashMap<>(); + private final Object lifecycleLock = new Object(); + private int activeStarts; + private CompletableFuture startsDrained = CompletableFuture.completedFuture(null); + private CompletableFuture teardown; + + private record ManagedContainer(String id, int hostPort) { + } @Inject KarapaceManager(ContainerBuilder containerBuilder, @@ -80,10 +89,34 @@ class KarapaceManager { } URI ensureStarted(String bootstrapServers) { - return restBaseUriByTarget.computeIfAbsent(bootstrapServers, this::startContainer); + synchronized (lifecycleLock) { + if (teardown != null) { + throw new IllegalStateException("Karapace containers are being stopped"); + } + if (activeStarts++ == 0) { + startsDrained = new CompletableFuture<>(); + } + } + try { + return restBaseUriByTarget.computeIfAbsent(bootstrapServers, this::startContainer); + } finally { + CompletableFuture drained = null; + synchronized (lifecycleLock) { + if (--activeStarts == 0) { + drained = startsDrained; + } + } + if (drained != null) { + drained.complete(null); + } + } } private URI startContainer(String bootstrapServers) { + ManagedContainer pending = containersByTarget.get(bootstrapServers); + if (pending != null) { + stopContainer(bootstrapServers, pending); + } EmulatorConfig.KafkaRestBridgeConfig bridgeConfig = config.services().pipes().kafkaRestBridge(); String targetKey = targetKey(bootstrapServers); String containerName = ContainerStorageHelper.resourceName(config, "pipes-kafka-rest", targetKey, targetKey); @@ -121,29 +154,32 @@ class KarapaceManager { specBuilder.withExposedPort(REST_PORT); } - ContainerSpec spec = specBuilder.build(); ContainerInfo info; try { + ContainerSpec spec = specBuilder.build(); info = lifecycleManager.createAndStart(spec); } catch (RuntimeException e) { - if (!containerDetector.isRunningInContainer()) { + if (hostPort != 0) { portAllocator.release(hostPort); } throw e; } + ManagedContainer managed = new ManagedContainer(info.containerId(), hostPort); + containersByTarget.put(bootstrapServers, managed); try { - containerIdByTarget.put(bootstrapServers, info.containerId()); EndpointInfo endpoint = info.getEndpoint(REST_PORT); URI restBaseUri = URI.create("http://" + endpoint.host() + ":" + endpoint.port() + "/"); waitUntilReady(restBaseUri); LOG.infov("Karapace REST Proxy {0} started for bootstrap {1}", info.containerId(), bootstrapServers); return restBaseUri; } catch (RuntimeException e) { - containerIdByTarget.remove(bootstrapServers); - lifecycleManager.stopAndRemove(info.containerId(), null); - if (!containerDetector.isRunningInContainer()) { - portAllocator.release(hostPort); + try { + stopContainer(bootstrapServers, managed); + } catch (RuntimeException cleanupFailure) { + if (cleanupFailure != e) { + e.addSuppressed(cleanupFailure); + } } throw e; } @@ -207,16 +243,53 @@ class KarapaceManager { return Digests.sha256Hex(bootstrapServers).substring(0, 16); } + @Override + public void stopManagedContainers() { + CompletableFuture drained; + CompletableFuture finished; + synchronized (lifecycleLock) { + if (teardown != null) { + finished = teardown; + drained = null; + } else { + finished = new CompletableFuture<>(); + teardown = finished; + drained = startsDrained; + } + } + if (drained == null) { + finished.join(); + return; + } + try { + // Admission stays closed while existing starts finish and cleanup performs Docker I/O. + drained.join(); + restBaseUriByTarget.clear(); + containersByTarget.forEach((target, managed) -> { + try { + stopContainer(target, managed); + } catch (RuntimeException e) { + LOG.warnv(e, "Failed to stop Karapace container {0}", managed.id()); + } + }); + } finally { + synchronized (lifecycleLock) { + teardown = null; + } + finished.complete(null); + } + } + + private void stopContainer(String target, ManagedContainer managed) { + lifecycleManager.stopAndRemoveStrict(managed.id(), null); + if (managed.hostPort() != 0) { + portAllocator.release(managed.hostPort()); + } + containersByTarget.remove(target, managed); + } + @PreDestroy void shutdown() { - containerIdByTarget.values().forEach(containerId -> { - try { - lifecycleManager.stopAndRemove(containerId, null); - } catch (RuntimeException e) { - LOG.warnv("Failed to stop Karapace container {0}: {1}", containerId, e.getMessage()); - } - }); - containerIdByTarget.clear(); - restBaseUriByTarget.clear(); + stopManagedContainers(); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java index bbf3a72950..3d11711016 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/KarapaceManagerTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.pipes; import com.sun.net.httpserver.HttpServer; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ContainerTeardown; import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerDetector; @@ -16,23 +17,36 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; 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.assertSame; 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.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -79,6 +93,7 @@ class KarapaceManagerTest { @AfterEach void tearDown() { + manager.shutdown(); if (fakeRestServer != null) { fakeRestServer.stop(0); } @@ -86,10 +101,14 @@ class KarapaceManagerTest { /** Stands in for Karapace's own {@code GET /_health}, which {@code isReady} polls. */ private int startFakeRestServer() throws Exception { + return startFakeRestServer(new AtomicInteger(200)); + } + + private int startFakeRestServer(AtomicInteger healthStatus) throws Exception { fakeRestServer = HttpServer.create(new InetSocketAddress("localhost", 0), 0); fakeRestServer.createContext("/_health", exchange -> { byte[] body = "{}".getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(200, body.length); + exchange.sendResponseHeaders(healthStatus.get(), body.length); exchange.getResponseBody().write(body); exchange.close(); }); @@ -208,7 +227,232 @@ class KarapaceManagerTest { assertThrows(IllegalStateException.class, () -> manager.ensureStarted("broker-1:9092")); - verify(lifecycleManager).stopAndRemove("container-1", null); + verify(lifecycleManager).stopAndRemoveStrict("container-1", null); verify(portAllocator).release(54321); } + + @Test + void managedTeardownStopsEveryTargetAndPredestroyDoesNotStopThemAgain() throws Exception { + int hostPort = startFakeRestServer(); + when(containerDetector.isRunningInContainer()).thenReturn(true); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))), + new ContainerInfo("container-2", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)))); + manager.ensureStarted("broker-1:9092"); + manager.ensureStarted("broker-2:9092"); + + ContainerTeardown teardown = assertInstanceOf(ContainerTeardown.class, manager); + teardown.stopManagedContainers(); + manager.shutdown(); + + verify(lifecycleManager, times(1)).stopAndRemoveStrict("container-1", null); + verify(lifecycleManager, times(1)).stopAndRemoveStrict("container-2", null); + } + + @Test + void managedTeardownClearsCachedTargetBeforeTheNextStart() throws Exception { + int hostPort = startFakeRestServer(); + when(containerDetector.isRunningInContainer()).thenReturn(true); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))), + new ContainerInfo("container-2", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)))); + manager.ensureStarted("broker-1:9092"); + + ContainerTeardown teardown = assertInstanceOf(ContainerTeardown.class, manager); + teardown.stopManagedContainers(); + manager.ensureStarted("broker-1:9092"); + teardown.stopManagedContainers(); + + verify(lifecycleManager, times(2)).createAndStart(any()); + verify(lifecycleManager, times(1)).stopAndRemoveStrict("container-1", null); + verify(lifecycleManager, times(1)).stopAndRemoveStrict("container-2", null); + } + + @Test + void failedManagedStopDoesNotPreventStoppingAnotherTarget() throws Exception { + int hostPort = startFakeRestServer(); + when(containerDetector.isRunningInContainer()).thenReturn(true); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))), + new ContainerInfo("container-2", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)))); + manager.ensureStarted("broker-1:9092"); + manager.ensureStarted("broker-2:9092"); + doThrow(new IllegalStateException("Docker stop failed")) + .when(lifecycleManager).stopAndRemoveStrict("container-1", null); + + ContainerTeardown teardown = assertInstanceOf(ContainerTeardown.class, manager); + teardown.stopManagedContainers(); + + verify(lifecycleManager).stopAndRemoveStrict("container-1", null); + verify(lifecycleManager).stopAndRemoveStrict("container-2", null); + } + @Test + void hostModeResetReusesTheOnlyAvailablePort() throws Exception { + int endpointPort = startFakeRestServer(); + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + when(config.services().pipes().kafkaRestBridge().hostPortBase()).thenReturn(port); + when(config.services().pipes().kafkaRestBridge().hostPortMax()).thenReturn(port); + when(containerDetector.isRunningInContainer()).thenReturn(false); + PortAllocator allocator = new PortAllocator(); + manager = new KarapaceManager(new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer), + lifecycleManager, containerDetector, config, allocator, dockerHostResolver, Duration.ofMillis(500)); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", endpointPort))), + new ContainerInfo("container-2", Map.of(REST_PORT, new EndpointInfo("localhost", endpointPort)))); + + manager.ensureStarted("broker:9092"); + manager.stopManagedContainers(); + assertDoesNotThrow(() -> manager.ensureStarted("broker:9092")); + manager.stopManagedContainers(); + + ArgumentCaptor specs = ArgumentCaptor.forClass(ContainerSpec.class); + verify(lifecycleManager, times(2)).createAndStart(specs.capture()); + for (ContainerSpec spec : specs.getAllValues()) { + assertEquals(port, spec.portBindings().get(REST_PORT)); + } + assertEquals(port, allocator.allocate(port, port)); + allocator.release(port); + } + + @Test + void resetDrainsAnAdmittedStartAndRejectsNewStartsUntilCleanupEnds() throws Exception { + int hostPort = startFakeRestServer(); + when(containerDetector.isRunningInContainer()).thenReturn(false); + when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort); + CountDownLatch creating = new CountDownLatch(1); + CountDownLatch finishCreating = new CountDownLatch(1); + CountDownLatch cleanupEntered = new CountDownLatch(1); + CountDownLatch finishCleanup = new CountDownLatch(1); + lenient().doAnswer(call -> { + cleanupEntered.countDown(); + assertTrue(finishCleanup.await(5, TimeUnit.SECONDS)); + return null; + }).when(lifecycleManager).stopAndRemoveStrict("container-1", null); + when(lifecycleManager.createAndStart(any())).thenAnswer(call -> { + ContainerSpec spec = call.getArgument(0); + if (spec.env().contains("KARAPACE_BOOTSTRAP_URI=other:9092")) { + return new ContainerInfo("other-container", + Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))); + } + creating.countDown(); + assertTrue(finishCreating.await(5, TimeUnit.SECONDS)); + return new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))); + }); + FutureTask start = new FutureTask<>(() -> manager.ensureStarted("broker:9092")); + FutureTask reset = new FutureTask<>(() -> { + manager.stopManagedContainers(); + return null; + }); + Thread starting = new Thread(start, "karapace-test-start"); + Thread resetting = new Thread(reset, "karapace-test-reset"); + starting.start(); + try { + assertTrue(creating.await(5, TimeUnit.SECONDS)); + resetting.start(); + awaitBlockedOrDone(resetting); + assertFalse(reset.isDone(), "reset must wait for the admitted create before taking ownership"); + assertThrows(IllegalStateException.class, () -> manager.ensureStarted("other:9092")); + verify(lifecycleManager, never()).stopAndRemoveStrict("container-1", null); + finishCreating.countDown(); + start.get(5, TimeUnit.SECONDS); + assertTrue(cleanupEntered.await(5, TimeUnit.SECONDS)); + assertFalse(reset.isDone(), "reset must finish strict removal before reopening admission"); + assertThrows(IllegalStateException.class, () -> manager.ensureStarted("other:9092")); + verify(portAllocator, never()).release(hostPort); + finishCleanup.countDown(); + reset.get(5, TimeUnit.SECONDS); + verify(lifecycleManager).stopAndRemoveStrict("container-1", null); + verify(portAllocator).release(hostPort); + manager.ensureStarted("broker:9092"); + verify(lifecycleManager, times(2)).createAndStart(any()); + } finally { + finishCreating.countDown(); + finishCleanup.countDown(); + starting.join(5000); + resetting.join(5000); + assertFalse(starting.isAlive()); + assertFalse(resetting.isAlive()); + } + } + + @Test + void failedStopRetainsContainerAndPortForRetry() throws Exception { + int hostPort = startFakeRestServer(); + when(containerDetector.isRunningInContainer()).thenReturn(false); + when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))), + new ContainerInfo("container-2", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)))); + manager.ensureStarted("broker:9092"); + lenient().doThrow(new IllegalStateException("Docker stop failed")).doNothing() + .when(lifecycleManager).stopAndRemoveStrict("container-1", null); + + manager.stopManagedContainers(); + + verify(portAllocator, never()).release(hostPort); + assertDoesNotThrow(() -> manager.ensureStarted("broker:9092")); + verify(lifecycleManager, times(2)).stopAndRemoveStrict("container-1", null); + verify(portAllocator).release(hostPort); + manager.stopManagedContainers(); + verify(lifecycleManager).stopAndRemoveStrict("container-2", null); + verify(portAllocator, times(2)).release(hostPort); + } + + @Test + void failedReadinessCleanupRetriesBeforeAllocatingAReplacement() throws Exception { + AtomicInteger healthStatus = new AtomicInteger(503); + int hostPort = startFakeRestServer(healthStatus); + when(containerDetector.isRunningInContainer()).thenReturn(false); + when(portAllocator.allocate(9500, 9599)).thenReturn(hostPort); + when(lifecycleManager.createAndStart(any())).thenReturn( + new ContainerInfo("container-1", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort))), + new ContainerInfo("container-2", Map.of(REST_PORT, new EndpointInfo("localhost", hostPort)))); + IllegalStateException cleanupFailure = new IllegalStateException("Docker removal unavailable"); + lenient().doThrow(cleanupFailure).doThrow(cleanupFailure).doNothing() + .when(lifecycleManager).stopAndRemoveStrict("container-1", null); + + IllegalStateException readinessFailure = assertThrows(IllegalStateException.class, + () -> manager.ensureStarted("broker:9092")); + assertTrue(readinessFailure.getMessage().contains("did not become ready")); + assertEquals(1, readinessFailure.getSuppressed().length); + assertSame(cleanupFailure, readinessFailure.getSuppressed()[0]); + verify(portAllocator, never()).release(hostPort); + + assertSame(cleanupFailure, assertThrows(IllegalStateException.class, + () -> manager.ensureStarted("broker:9092"))); + verify(portAllocator, never()).release(hostPort); + verify(portAllocator).allocate(9500, 9599); + verify(lifecycleManager).createAndStart(any()); + + healthStatus.set(200); + assertEquals(URI.create("http://localhost:" + hostPort + "/"), manager.ensureStarted("broker:9092")); + InOrder cleanupOrder = inOrder(lifecycleManager, portAllocator); + cleanupOrder.verify(lifecycleManager, times(3)).stopAndRemoveStrict("container-1", null); + cleanupOrder.verify(portAllocator).release(hostPort); + cleanupOrder.verify(portAllocator).allocate(9500, 9599); + cleanupOrder.verify(lifecycleManager).createAndStart(any()); + verify(lifecycleManager, times(3)).stopAndRemoveStrict("container-1", null); + verify(portAllocator).release(hostPort); + verify(portAllocator, times(2)).allocate(9500, 9599); + verify(lifecycleManager, times(2)).createAndStart(any()); + manager.stopManagedContainers(); + verify(lifecycleManager).stopAndRemoveStrict("container-2", null); + verify(portAllocator, times(2)).release(hostPort); + } + + @Test + void createFailureReleasesItsAllocatedPort() { + when(containerDetector.isRunningInContainer()).thenReturn(false); + when(portAllocator.allocate(9500, 9599)).thenReturn(9500); + IllegalStateException failure = new IllegalStateException("create failed"); + when(lifecycleManager.createAndStart(any())).thenThrow(failure); + + assertSame(failure, assertThrows(IllegalStateException.class, () -> manager.ensureStarted("broker:9092"))); + + verify(portAllocator).release(9500); + } + }