diff --git a/core/src/main/java/org/testcontainers/DockerClientFactory.java b/core/src/main/java/org/testcontainers/DockerClientFactory.java index d44cd3b5b6f..793f4d110ff 100644 --- a/core/src/main/java/org/testcontainers/DockerClientFactory.java +++ b/core/src/main/java/org/testcontainers/DockerClientFactory.java @@ -175,8 +175,7 @@ public DockerClient client() { final DockerClientProviderStrategy strategy = getOrInitializeStrategy(); - String hostIpAddress = strategy.getDockerHostIpAddress(); - log.info("Docker host IP address is {}", hostIpAddress); + log.info("Docker host IP address is {}", strategy.getDockerHostIpAddress()); final DockerClient client = new DelegatingDockerClient(strategy.getDockerClient()) { @Override public void close() { @@ -200,7 +199,8 @@ public void close() { if (useRyuk) { log.debug("Ryuk is enabled"); try { - ryukContainerId = ResourceReaper.start(hostIpAddress, client); + //noinspection deprecation + ryukContainerId = ResourceReaper.start(client); } catch (RuntimeException e) { cachedClientFailure = e; throw e; diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 3b0cfa1e289..56d682b3360 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -5,34 +5,28 @@ import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.exception.NotFoundException; import com.github.dockerjava.api.model.Bind; -import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.Frame; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.Network; -import com.github.dockerjava.api.model.Ports; +import com.github.dockerjava.api.model.StreamType; import com.github.dockerjava.api.model.Volume; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.collect.Sets; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -import org.rnorth.ducttape.ratelimits.RateLimiter; -import org.rnorth.ducttape.ratelimits.RateLimiterBuilder; +import org.rnorth.ducttape.TimeoutException; +import org.rnorth.ducttape.unreliables.Unreliables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.DockerClientFactory; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; import java.io.UnsupportedEncodingException; -import java.net.Socket; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.AbstractMap.SimpleEntry; -import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -42,7 +36,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; -import java.util.stream.Stream; /** * Component that responsible for container removal and automatic cleanup of dead containers at JVM shutdown. @@ -52,14 +45,8 @@ public final class ResourceReaper { private static final Logger LOGGER = LoggerFactory.getLogger(ResourceReaper.class); - private static final List>> DEATH_NOTE = new ArrayList<>(); - private static final RateLimiter RYUK_ACK_RATE_LIMITER = RateLimiterBuilder - .newBuilder() - .withRate(4, TimeUnit.SECONDS) - .withConstantThroughput() - .build(); - private static ResourceReaper instance; + private static RyukClient ryukClient; private final DockerClient dockerClient; private Map registeredContainers = new ConcurrentHashMap<>(); private Set registeredNetworks = Sets.newConcurrentHashSet(); @@ -70,118 +57,162 @@ private ResourceReaper() { dockerClient = DockerClientFactory.instance().client(); } - @SneakyThrows(InterruptedException.class) + /** + * + * @deprecated internal API + */ + @Deprecated public static String start(String hostIpAddress, DockerClient client) { + return start(client); + } + + /** + * + * @deprecated internal API + */ + @Deprecated + public static String start(DockerClient client) { + String ryukContainerId = startRyukContainer(client); + + String query = toQuery( + DockerClientFactory.DEFAULT_LABELS.entrySet().stream() + .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) + .collect(Collectors.toList()) + ); + + ryukClient = new RyukClient(client, ryukContainerId); + + try { + Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS, () -> { + CountDownLatch ack = new CountDownLatch(1); + + Thread kiraThread = new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> { + while (true) { + log.debug("Connecting to the Ryuk watchdog container"); + ResultCallback.Adapter callback = new ResultCallback.Adapter() { + @Override + @SneakyThrows + public void onNext(Frame object) { + String payload = new String(object.getPayload(), StandardCharsets.UTF_8); + if (payload.contains("ACK")) { + ack.countDown(); + } + } + }; + + try { + ryukClient.acknowledge(query, callback); + callback.awaitCompletion(); + } catch (InterruptedException e) { + try { + callback.close(); + } catch (Exception ignored) { + } + break; + } catch (Exception e) { + log.warn("Ryuk connection failure", e); + } + } + }, "testcontainers-ryuk"); + kiraThread.setDaemon(true); + kiraThread.start(); + + if (!ack.await(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { + kiraThread.interrupt(); + throw new IllegalStateException("Timed out waiting for the Ryuk watchdog container default filters to be registered"); + } + return null; + }); + } catch (TimeoutException e) { + throw new IllegalStateException("Timed out waiting for the default Ryuk filters to be registered", e); + } + + return ryukContainerId; + } + + @SneakyThrows(InterruptedException.class) + private static String startRyukContainer(DockerClient client) { String ryukImage = ImageNameSubstitutor.instance() - .apply(DockerImageName.parse("testcontainers/ryuk:0.3.0")) + .apply(DockerImageName.parse("testcontainers/ryuk:latest")) .asCanonicalNameString(); DockerClientFactory.instance().checkAndPullImage(client, ryukImage); - List binds = new ArrayList<>(); - binds.add(new Bind(DockerClientFactory.instance().getRemoteDockerUnixSocketPath(), new Volume("/var/run/docker.sock"))); - + log.debug("Creating Ryuk container"); String ryukContainerId = client.createContainerCmd(ryukImage) - .withHostConfig(new HostConfig().withAutoRemove(true)) - .withExposedPorts(new ExposedPort(8080)) - .withPublishAllPorts(true) - .withName("testcontainers-ryuk-" + DockerClientFactory.SESSION_ID) - .withLabels(Collections.singletonMap(DockerClientFactory.TESTCONTAINERS_LABEL, "true")) - .withBinds(binds) - .withPrivileged(TestcontainersConfiguration.getInstance().isRyukPrivileged()) - .exec() - .getId(); - - client.startContainerCmd(ryukContainerId).exec(); + .withHostConfig( + new HostConfig() + .withAutoRemove(true) + .withBinds(Arrays.asList( + new Bind( + DockerClientFactory.instance().getRemoteDockerUnixSocketPath(), + new Volume("/var/run/docker.sock") + ) + )) + .withPrivileged(TestcontainersConfiguration.getInstance().isRyukPrivileged()) + ) + .withName("testcontainers-ryuk-" + DockerClientFactory.SESSION_ID) + .withLabels(Collections.singletonMap(DockerClientFactory.TESTCONTAINERS_LABEL, "true")) + .exec() + .getId(); StringBuilder ryukLog = new StringBuilder(); - ResultCallback.Adapter logCallback = client.logContainerCmd(ryukContainerId) - .withSince(0) + CountDownLatch started = new CountDownLatch(1); + + log.debug("Attaching to the Ryuk container with id: '{}'", ryukContainerId); + ResultCallback.Adapter attachment = client.attachContainerCmd(ryukContainerId) .withFollowStream(true) - .withStdOut(true) + .withLogs(true) .withStdErr(true) + .withStdOut(true) .exec(new ResultCallback.Adapter() { @Override public void onNext(Frame frame) { - ryukLog.append(new String(frame.getPayload(), StandardCharsets.UTF_8)); + String payload = new String(frame.getPayload(), StandardCharsets.UTF_8); + // Poor Man's log-based wait strategy :) + if (frame.getStreamType() == StreamType.STDERR && payload.contains("Started!")) { + started.countDown(); + } + ryukLog.append(payload); } }); - - InspectContainerResponse inspectedContainer = client.inspectContainerCmd(ryukContainerId).exec(); - - Integer ryukPort = inspectedContainer.getNetworkSettings().getPorts().getBindings().values().stream() - .flatMap(Stream::of) - .findFirst() - .map(Ports.Binding::getHostPortSpec) - .map(Integer::parseInt) - .get(); - - CountDownLatch ryukScheduledLatch = new CountDownLatch(1); - - synchronized (DEATH_NOTE) { - DEATH_NOTE.add( - DockerClientFactory.DEFAULT_LABELS.entrySet().stream() - .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) - .collect(Collectors.toList()) - ); + if (!attachment.awaitStarted(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { + log.error("Timed out waiting for the Ryuk watchdog container's attach. Container id: '{}'", ryukContainerId); + throw new IllegalStateException("Failed to attach to Ryuk"); } - Thread kiraThread = new Thread( - DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, - () -> { - while (true) { - RYUK_ACK_RATE_LIMITER.doWhenReady(() -> { - int index = 0; - try(Socket clientSocket = new Socket(hostIpAddress, ryukPort)) { - FilterRegistry registry = new FilterRegistry(clientSocket.getInputStream(), clientSocket.getOutputStream()); - - synchronized (DEATH_NOTE) { - while (true) { - if (DEATH_NOTE.size() <= index) { - try { - DEATH_NOTE.wait(1_000); - continue; - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - List> filters = DEATH_NOTE.get(index); - boolean isAcknowledged = registry.register(filters); - if (isAcknowledged) { - log.debug("Received 'ACK' from Ryuk"); - ryukScheduledLatch.countDown(); - index++; - } else { - log.debug("Didn't receive 'ACK' from Ryuk. Will retry to send filters."); - } - } - } - } catch (IOException e) { - log.warn("Can not connect to Ryuk at {}:{}", hostIpAddress, ryukPort, e); - } - }); - } - }, - "testcontainers-ryuk" - ); - kiraThread.setDaemon(true); - kiraThread.start(); + log.debug("Starting Ryuk container with id: '{}'", ryukContainerId); + client.startContainerCmd(ryukContainerId).exec(); + try { - // We need to wait before we can start any containers to make sure that we delete them - if (!ryukScheduledLatch.await(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { - log.error("Timed out waiting for Ryuk container to start. Ryuk's logs:\n{}", ryukLog); - throw new IllegalStateException(String.format("Could not connect to Ryuk at %s:%s", hostIpAddress, ryukPort)); + if (!started.await(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { + log.error("Timed out waiting for the Ryuk watchdog container to start. Ryuk's logs:\n{}", ryukLog); + throw new IllegalStateException("Timed out waiting for the Ryuk watchdog container to start"); } } finally { try { - logCallback.close(); + attachment.close(); } catch (IOException ignored) { } } + log.debug("Ryuk started"); return ryukContainerId; } + @VisibleForTesting + static String toQuery(List> filters) { + return filters.stream() + .map(it -> { + try { + return URLEncoder.encode(it.getKey(), "UTF-8") + "=" + URLEncoder.encode(it.getValue(), "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.joining("&")); + } + public synchronized static ResourceReaper instance() { if (instance == null) { instance = new ResourceReaper(); @@ -204,11 +235,18 @@ public synchronized void performCleanup() { * * @param filter the filter */ + @SneakyThrows(InterruptedException.class) public void registerFilterForCleanup(List> filter) { - synchronized (DEATH_NOTE) { - DEATH_NOTE.add(filter); - DEATH_NOTE.notifyAll(); - } + ryukClient.acknowledge(toQuery(filter), new ResultCallback.Adapter() { + @Override + @SneakyThrows(IOException.class) + public void onNext(Frame object) { + String payload = new String(object.getPayload(), StandardCharsets.UTF_8); + if (payload.contains("ACK")) { + close(); + } + } + }).awaitCompletion(); } /** @@ -391,53 +429,4 @@ private void setHook() { Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, this::performCleanup)); } } - - static class FilterRegistry { - - @VisibleForTesting - static final String ACKNOWLEDGMENT = "ACK"; - - private final BufferedReader in; - private final OutputStream out; - - FilterRegistry(InputStream ryukInputStream, OutputStream ryukOutputStream) { - this.in = new BufferedReader(new InputStreamReader(ryukInputStream)); - this.out = ryukOutputStream; - } - - /** - * Registers the given filters with Ryuk - * - * @param filters the filter to register - * @return true if the filters have been registered successfuly, false otherwise - * @throws IOException if communication with Ryuk fails - */ - protected boolean register(List> filters) throws IOException { - String query = filters.stream() - .map(it -> { - try { - return URLEncoder.encode(it.getKey(), "UTF-8") + "=" + URLEncoder.encode(it.getValue(), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - }) - .collect(Collectors.joining("&")); - - log.debug("Sending '{}' to Ryuk", query); - out.write(query.getBytes()); - out.write('\n'); - out.flush(); - - return waitForAcknowledgment(in); - } - - private static boolean waitForAcknowledgment(BufferedReader in) throws IOException { - String line = in.readLine(); - while (line != null && !ACKNOWLEDGMENT.equalsIgnoreCase(line)) { - line = in.readLine(); - } - return ACKNOWLEDGMENT.equalsIgnoreCase(line); - } - - } } diff --git a/core/src/main/java/org/testcontainers/utility/RyukClient.java b/core/src/main/java/org/testcontainers/utility/RyukClient.java new file mode 100644 index 00000000000..41c02bc1745 --- /dev/null +++ b/core/src/main/java/org/testcontainers/utility/RyukClient.java @@ -0,0 +1,35 @@ +package org.testcontainers.utility; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.command.ExecCreateCmdResponse; +import com.github.dockerjava.api.model.Frame; +import lombok.extern.slf4j.Slf4j; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; + +@Slf4j +class RyukClient { + + private final DockerClient dockerClient; + + private final String ryukContainerId; + + public RyukClient(DockerClient dockerClient, String ryukContainerId) { + this.dockerClient = dockerClient; + this.ryukContainerId = ryukContainerId; + } + + public > T acknowledge(String query, T callback) { + ExecCreateCmdResponse exec = dockerClient.execCreateCmd(ryukContainerId) + .withAttachStdin(true) + .withAttachStdout(true) + .withCmd("nc", "localhost", "8080") + .exec(); + + return dockerClient.execStartCmd(exec.getId()) + .withStdIn(new ByteArrayInputStream((query + "\n").getBytes(StandardCharsets.UTF_8))) + .exec(callback); + } +} diff --git a/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java b/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java deleted file mode 100644 index 49bc870e8d0..00000000000 --- a/core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.testcontainers.utility; - -import org.junit.Test; -import org.testcontainers.utility.ResourceReaper.FilterRegistry; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.AbstractMap.SimpleEntry; -import java.util.List; -import java.util.Map.Entry; - -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class FilterRegistryTest { - - private static final List> FILTERS = asList( - new SimpleEntry<>("key1!", "value2?"), new SimpleEntry<>("key2#", "value2%") - ); - private static final String URL_ENCODED_FILTERS = "key1%21=value2%3F&key2%23=value2%25"; - private static final byte[] ACKNOWLEDGEMENT = FilterRegistry.ACKNOWLEDGMENT.getBytes(); - private static final byte[] NO_ACKNOWLEDGEMENT = "".getBytes(); - private static final String NEW_LINE = "\n"; - - @Test - public void registerReturnsTrueIfAcknowledgementIsReadFromInputStream() throws IOException { - FilterRegistry registry = new FilterRegistry(inputStream(ACKNOWLEDGEMENT), anyOutputStream()); - - boolean successful = registry.register(FILTERS); - - assertTrue(successful); - } - - @Test - public void registerReturnsFalseIfNoAcknowledgementIsReadFromInputStream() throws IOException { - FilterRegistry registry = new FilterRegistry(inputStream(NO_ACKNOWLEDGEMENT), anyOutputStream()); - - boolean successful = registry.register(FILTERS); - - assertFalse(successful); - } - - @Test - public void registerWritesUrlEncodedFiltersAndNewlineToOutputStream() throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - FilterRegistry registry = new FilterRegistry(anyInputStream(), outputStream); - - registry.register(FILTERS); - - assertEquals(URL_ENCODED_FILTERS + NEW_LINE, new String(outputStream.toByteArray())); - } - - private static InputStream inputStream(byte[] bytes) { - return new ByteArrayInputStream(bytes); - } - - private static InputStream anyInputStream() { - return inputStream(ACKNOWLEDGEMENT); - } - - private static OutputStream anyOutputStream() { - return new ByteArrayOutputStream(); - } - -} diff --git a/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java b/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java new file mode 100644 index 00000000000..53a449d1128 --- /dev/null +++ b/core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java @@ -0,0 +1,22 @@ +package org.testcontainers.utility; + +import org.junit.Test; + +import java.io.IOException; +import java.util.AbstractMap.SimpleEntry; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; + +public class ResourceReaperTest { + + @Test + public void toQueryUrlEncodesFilters() { + String query = ResourceReaper.toQuery(Arrays.asList( + new SimpleEntry<>("key1!", "value2?"), + new SimpleEntry<>("key2#", "value2%") + )); + + assertEquals("key1%21=value2%3F&key2%23=value2%25", query); + } +} diff --git a/examples/linked-container/build.gradle b/examples/linked-container/build.gradle index f5f21a57d21..83e11e50682 100644 --- a/examples/linked-container/build.gradle +++ b/examples/linked-container/build.gradle @@ -7,7 +7,7 @@ repositories { } dependencies { compileOnly 'org.slf4j:slf4j-api:1.7.30' - implementation 'com.squareup.okhttp3:okhttp:4.9.0' + implementation 'com.squareup.okhttp3:okhttp:3.14.9' implementation 'org.json:json:20180813' testImplementation 'org.postgresql:postgresql:42.2.18' testImplementation 'ch.qos.logback:logback-classic:1.2.3'