From fa2404edb3bf35ba21d7b54fd3fca6d28ed09c06 Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Tue, 24 Nov 2020 20:18:00 +0100 Subject: [PATCH 1/8] Communicate with Ryuk over the Docker connection --- .../testcontainers/DockerClientFactory.java | 6 +- .../utility/ResourceReaper.java | 247 +++++++++--------- .../testcontainers/utility/RyukClient.java | 71 +++++ .../utility/FilterRegistryTest.java | 70 ----- .../utility/ResourceReaperTest.java | 22 ++ 5 files changed, 215 insertions(+), 201 deletions(-) create mode 100644 core/src/main/java/org/testcontainers/utility/RyukClient.java delete mode 100644 core/src/test/java/org/testcontainers/utility/FilterRegistryTest.java create mode 100644 core/src/test/java/org/testcontainers/utility/ResourceReaperTest.java 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..38a441c91f0 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -5,34 +5,27 @@ 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.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 +35,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. @@ -53,11 +45,6 @@ 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 final DockerClient dockerClient; @@ -70,51 +57,23 @@ private ResourceReaper() { dockerClient = DockerClientFactory.instance().client(); } - @SneakyThrows(InterruptedException.class) + /** + * + * @deprecated internal API + */ + @Deprecated public static String start(String hostIpAddress, DockerClient client) { - String ryukImage = ImageNameSubstitutor.instance() - .apply(DockerImageName.parse("testcontainers/ryuk:0.3.0")) - .asCanonicalNameString(); - DockerClientFactory.instance().checkAndPullImage(client, ryukImage); - - List binds = new ArrayList<>(); - binds.add(new Bind(DockerClientFactory.instance().getRemoteDockerUnixSocketPath(), new Volume("/var/run/docker.sock"))); - - 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(); - - StringBuilder ryukLog = new StringBuilder(); - - ResultCallback.Adapter logCallback = client.logContainerCmd(ryukContainerId) - .withSince(0) - .withFollowStream(true) - .withStdOut(true) - .withStdErr(true) - .exec(new ResultCallback.Adapter() { - @Override - public void onNext(Frame frame) { - ryukLog.append(new String(frame.getPayload(), StandardCharsets.UTF_8)); - } - }); - - InspectContainerResponse inspectedContainer = client.inspectContainerCmd(ryukContainerId).exec(); + return start(client); + } - Integer ryukPort = inspectedContainer.getNetworkSettings().getPorts().getBindings().values().stream() - .flatMap(Stream::of) - .findFirst() - .map(Ports.Binding::getHostPortSpec) - .map(Integer::parseInt) - .get(); + /** + * + * @deprecated internal API + */ + @Deprecated + @SneakyThrows(InterruptedException.class) + public static String start(DockerClient client) { + String ryukContainerId = startRyukContainer(client); CountDownLatch ryukScheduledLatch = new CountDownLatch(1); @@ -129,13 +88,20 @@ public void onNext(Frame frame) { Thread kiraThread = new Thread( DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> { + int index = 0; 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()); + try (RyukClient ryukClient = new RyukClient(client, ryukContainerId)) { + try { + log.debug("Connecting to Ryuk"); + ryukClient.connect(); + } catch (Exception e) { + log.warn("Can not connect to Ryuk", e); + continue; + } - synchronized (DEATH_NOTE) { + synchronized (DEATH_NOTE) { + String query = null; + try { while (true) { if (DEATH_NOTE.size() <= index) { try { @@ -145,43 +111,117 @@ public void onNext(Frame frame) { 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."); - } + query = toQuery(DEATH_NOTE.get(index)); + log.debug("Sending '{}' to Ryuk", query); + ryukClient.acknowledge(query); + log.debug("Received 'ACK' from Ryuk"); + ryukScheduledLatch.countDown(); + index++; } + } catch (Exception e) { + log.warn("Failed to send '{}' to Ryuk, reconnecting...", query); } - } catch (IOException e) { - log.warn("Can not connect to Ryuk at {}:{}", hostIpAddress, ryukPort, e); } - }); + } } }, "testcontainers-ryuk" ); kiraThread.setDaemon(true); kiraThread.start(); + + // 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 the default Ryuk filters to be registered"); + throw new IllegalStateException("Timed out waiting for the default Ryuk filters to be registered"); + } + + return ryukContainerId; + } + + @SneakyThrows(InterruptedException.class) + private static String startRyukContainer(DockerClient client) { + String ryukImage = ImageNameSubstitutor.instance() + .apply(DockerImageName.parse("testcontainers/ryuk:0.3.0")) + .asCanonicalNameString(); + DockerClientFactory.instance().checkAndPullImage(client, ryukImage); + + log.debug("Creating Ryuk container"); + String ryukContainerId = client.createContainerCmd(ryukImage) + .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(); + + CountDownLatch started = new CountDownLatch(1); + + log.debug("Attaching to the Ryuk container with id: '{}'", ryukContainerId); + ResultCallback.Adapter attachment = client.attachContainerCmd(ryukContainerId) + .withFollowStream(true) + .withLogs(true) + .withStdErr(true) + .withStdOut(true) + .exec(new ResultCallback.Adapter() { + @Override + public void onNext(Frame frame) { + 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); + } + }); + if (!attachment.awaitStarted(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { + log.error("Timed out waiting for Ryuk container's attach. Container id: '{}'", ryukContainerId); + throw new IllegalStateException("Failed to attack too Ryuk"); + } + + 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)) { + if (!started.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)); + throw new IllegalStateException("Could not connect to Ryuk"); } } 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(); @@ -391,53 +431,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..1860deecf9e --- /dev/null +++ b/core/src/main/java/org/testcontainers/utility/RyukClient.java @@ -0,0 +1,71 @@ +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.RequiredArgsConstructor; +import lombok.SneakyThrows; +import org.rnorth.ducttape.unreliables.Unreliables; + +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +@RequiredArgsConstructor +class RyukClient implements AutoCloseable { + + private final DockerClient dockerClient; + + private final String ryukContainerId; + + private final PipedOutputStream outputStream = new PipedOutputStream(); + + private final AtomicBoolean acked = new AtomicBoolean(true); + + private ResultCallback.Adapter listener; + + @SneakyThrows + public void connect() { + ExecCreateCmdResponse exec = dockerClient.execCreateCmd(ryukContainerId) + .withAttachStdin(true) + .withAttachStdout(true) + .withCmd("nc", "localhost", "8080") + .exec(); + + listener = dockerClient.execStartCmd(exec.getId()) + .withStdIn(new PipedInputStream(outputStream)) + .exec(new ResultCallback.Adapter() { + @Override + @SneakyThrows + public void onNext(Frame object) { + String payload = new String(object.getPayload(), StandardCharsets.UTF_8); + if ("ACK".equals(payload.trim())) { + acked.set(true); + } + } + }); + listener.awaitStarted(15, TimeUnit.SECONDS); + } + + @SneakyThrows + public synchronized void acknowledge(String query) { + if (!acked.compareAndSet(true, false)) { + throw new IllegalStateException("ACK is in progress"); + } + outputStream.write((query + "\n").getBytes()); + outputStream.flush(); + + Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, acked::get); + } + + @Override + @SneakyThrows + public void close() { + if (listener != null) { + listener.close(); + } + } +} 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); + } +} From b6c1529700020a822e6aea8eade1c0d74652f532 Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Tue, 24 Nov 2020 20:39:18 +0100 Subject: [PATCH 2/8] simplify code --- .../utility/ResourceReaper.java | 77 ++++--------------- .../testcontainers/utility/RyukClient.java | 5 ++ .../java/org/testcontainers/DaemonTest.java | 5 +- 3 files changed, 23 insertions(+), 64 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 38a441c91f0..0e683ee9903 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -24,7 +24,6 @@ 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; @@ -44,9 +43,8 @@ public final class ResourceReaper { private static final Logger LOGGER = LoggerFactory.getLogger(ResourceReaper.class); - private static final List>> DEATH_NOTE = new ArrayList<>(); - private static ResourceReaper instance; + private static RyukClient ryukClient; private final DockerClient dockerClient; private Map registeredContainers = new ConcurrentHashMap<>(); private Set registeredNetworks = Sets.newConcurrentHashSet(); @@ -71,67 +69,25 @@ public static String start(String hostIpAddress, DockerClient client) { * @deprecated internal API */ @Deprecated - @SneakyThrows(InterruptedException.class) public static String start(DockerClient client) { String ryukContainerId = startRyukContainer(client); - CountDownLatch ryukScheduledLatch = new CountDownLatch(1); + ryukClient = new RyukClient(client, ryukContainerId); - synchronized (DEATH_NOTE) { - DEATH_NOTE.add( - DockerClientFactory.DEFAULT_LABELS.entrySet().stream() - .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) - .collect(Collectors.toList()) - ); + try { + log.debug("Connecting to Ryuk"); + ryukClient.connect(); + } catch (Exception e) { + throw new IllegalStateException("Can not connect to Ryuk", e); } - Thread kiraThread = new Thread( - DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, - () -> { - int index = 0; - while (true) { - try (RyukClient ryukClient = new RyukClient(client, ryukContainerId)) { - try { - log.debug("Connecting to Ryuk"); - ryukClient.connect(); - } catch (Exception e) { - log.warn("Can not connect to Ryuk", e); - continue; - } - - synchronized (DEATH_NOTE) { - String query = null; - try { - while (true) { - if (DEATH_NOTE.size() <= index) { - try { - DEATH_NOTE.wait(1_000); - continue; - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } - query = toQuery(DEATH_NOTE.get(index)); - log.debug("Sending '{}' to Ryuk", query); - ryukClient.acknowledge(query); - log.debug("Received 'ACK' from Ryuk"); - ryukScheduledLatch.countDown(); - index++; - } - } catch (Exception e) { - log.warn("Failed to send '{}' to Ryuk, reconnecting...", query); - } - } - } - } - }, - "testcontainers-ryuk" - ); - kiraThread.setDaemon(true); - kiraThread.start(); - - // 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)) { + try { + ryukClient.acknowledge(toQuery( + DockerClientFactory.DEFAULT_LABELS.entrySet().stream() + .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) + .collect(Collectors.toList()) + )); + } catch (Exception e) { log.error("Timed out waiting for the default Ryuk filters to be registered"); throw new IllegalStateException("Timed out waiting for the default Ryuk filters to be registered"); } @@ -245,10 +201,7 @@ public synchronized void performCleanup() { * @param filter the filter */ public void registerFilterForCleanup(List> filter) { - synchronized (DEATH_NOTE) { - DEATH_NOTE.add(filter); - DEATH_NOTE.notifyAll(); - } + ryukClient.acknowledge(toQuery(filter)); } /** diff --git a/core/src/main/java/org/testcontainers/utility/RyukClient.java b/core/src/main/java/org/testcontainers/utility/RyukClient.java index 1860deecf9e..0c4c14f2837 100644 --- a/core/src/main/java/org/testcontainers/utility/RyukClient.java +++ b/core/src/main/java/org/testcontainers/utility/RyukClient.java @@ -6,6 +6,7 @@ import com.github.dockerjava.api.model.Frame; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; import org.rnorth.ducttape.unreliables.Unreliables; import java.io.PipedInputStream; @@ -15,6 +16,7 @@ import java.util.concurrent.atomic.AtomicBoolean; @RequiredArgsConstructor +@Slf4j class RyukClient implements AutoCloseable { private final DockerClient dockerClient; @@ -55,10 +57,13 @@ public synchronized void acknowledge(String query) { if (!acked.compareAndSet(true, false)) { throw new IllegalStateException("ACK is in progress"); } + log.debug("Sending '{}' to Ryuk", query); outputStream.write((query + "\n").getBytes()); outputStream.flush(); Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, acked::get); + + log.debug("Received 'ACK' from Ryuk"); } @Override diff --git a/core/src/test/java/org/testcontainers/DaemonTest.java b/core/src/test/java/org/testcontainers/DaemonTest.java index f08614c8cdc..d63b6cf6da2 100644 --- a/core/src/test/java/org/testcontainers/DaemonTest.java +++ b/core/src/test/java/org/testcontainers/DaemonTest.java @@ -17,7 +17,7 @@ */ public class DaemonTest { - public static void main(String[] args) { + public static void main(String[] args) throws Exception { Thread mainThread = Thread.currentThread(); GenericContainer genericContainer = null; @@ -42,9 +42,10 @@ public static void main(String[] args) { } } finally { if (genericContainer != null) { - genericContainer.stop(); + // genericContainer.stop(); } } + Thread.currentThread().join(); } @Test From e80c52932145e5eca45c82c5b21fba06a9fd8086 Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Tue, 24 Nov 2020 20:40:32 +0100 Subject: [PATCH 3/8] revert unnecessary change --- core/src/test/java/org/testcontainers/DaemonTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/src/test/java/org/testcontainers/DaemonTest.java b/core/src/test/java/org/testcontainers/DaemonTest.java index d63b6cf6da2..f08614c8cdc 100644 --- a/core/src/test/java/org/testcontainers/DaemonTest.java +++ b/core/src/test/java/org/testcontainers/DaemonTest.java @@ -17,7 +17,7 @@ */ public class DaemonTest { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { Thread mainThread = Thread.currentThread(); GenericContainer genericContainer = null; @@ -42,10 +42,9 @@ public static void main(String[] args) throws Exception { } } finally { if (genericContainer != null) { - // genericContainer.stop(); + genericContainer.stop(); } } - Thread.currentThread().join(); } @Test From d1af8ebd7c8e6db21aae608d6cfc8a72618c35bc Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Tue, 24 Nov 2020 20:47:08 +0100 Subject: [PATCH 4/8] Update core/src/main/java/org/testcontainers/utility/ResourceReaper.java Co-authored-by: Richard North --- .../main/java/org/testcontainers/utility/ResourceReaper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 0e683ee9903..8d1eec039e8 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -143,7 +143,7 @@ public void onNext(Frame frame) { }); if (!attachment.awaitStarted(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { log.error("Timed out waiting for Ryuk container's attach. Container id: '{}'", ryukContainerId); - throw new IllegalStateException("Failed to attack too Ryuk"); + throw new IllegalStateException("Failed to attach to Ryuk"); } log.debug("Starting Ryuk container with id: '{}'", ryukContainerId); From ed7c897d158aba92d7fb9c150063bec6dd84e56d Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Fri, 27 Nov 2020 16:05:27 +0100 Subject: [PATCH 5/8] Retry Ryuk acknowledgment --- .../utility/ResourceReaper.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 8d1eec039e8..6019d9db5bb 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -15,6 +15,8 @@ import com.google.common.collect.Sets; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; +import org.rnorth.ducttape.TimeoutException; +import org.rnorth.ducttape.unreliables.Unreliables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.DockerClientFactory; @@ -81,15 +83,19 @@ public static String start(DockerClient client) { throw new IllegalStateException("Can not connect to Ryuk", e); } + String query = toQuery( + DockerClientFactory.DEFAULT_LABELS.entrySet().stream() + .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) + .collect(Collectors.toList()) + ); try { - ryukClient.acknowledge(toQuery( - DockerClientFactory.DEFAULT_LABELS.entrySet().stream() - .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) - .collect(Collectors.toList()) - )); - } catch (Exception e) { + Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS, () -> { + ryukClient.acknowledge(query); + return null; + }); + } catch (TimeoutException e) { log.error("Timed out waiting for the default Ryuk filters to be registered"); - throw new IllegalStateException("Timed out waiting for the default Ryuk filters to be registered"); + throw new IllegalStateException("Timed out waiting for the default Ryuk filters to be registered", e); } return ryukContainerId; From bf257861db3120cc095686d42917f76a459618e9 Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Fri, 27 Nov 2020 17:35:24 +0100 Subject: [PATCH 6/8] recreate `RyukClient` on failure --- .../utility/ResourceReaper.java | 26 +++++++++---------- .../testcontainers/utility/RyukClient.java | 2 +- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 6019d9db5bb..111d023a2ab 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -74,27 +74,27 @@ public static String start(String hostIpAddress, DockerClient client) { public static String start(DockerClient client) { String ryukContainerId = startRyukContainer(client); - ryukClient = new RyukClient(client, ryukContainerId); - - try { - log.debug("Connecting to Ryuk"); - ryukClient.connect(); - } catch (Exception e) { - throw new IllegalStateException("Can not connect to Ryuk", e); - } - String query = toQuery( DockerClientFactory.DEFAULT_LABELS.entrySet().stream() .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) .collect(Collectors.toList()) ); try { - Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS, () -> { - ryukClient.acknowledge(query); - return null; + ryukClient = Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS, () -> { + RyukClient ryukClient = new RyukClient(client, ryukContainerId); + + try { + log.debug("Connecting to the Ryuk watchdog container"); + ryukClient.connect(); + ryukClient.acknowledge(query); + return ryukClient; + } catch (Exception e) { + log.warn("Timed out waiting for the Ryuk watchdog container to start"); + ryukClient.close(); + throw new IllegalStateException("Timed out waiting for the Ryuk watchdog container to start", e); + } }); } catch (TimeoutException e) { - log.error("Timed out waiting for the default Ryuk filters to be registered"); throw new IllegalStateException("Timed out waiting for the default Ryuk filters to be registered", e); } diff --git a/core/src/main/java/org/testcontainers/utility/RyukClient.java b/core/src/main/java/org/testcontainers/utility/RyukClient.java index 0c4c14f2837..869f4ad7577 100644 --- a/core/src/main/java/org/testcontainers/utility/RyukClient.java +++ b/core/src/main/java/org/testcontainers/utility/RyukClient.java @@ -44,7 +44,7 @@ public void connect() { @SneakyThrows public void onNext(Frame object) { String payload = new String(object.getPayload(), StandardCharsets.UTF_8); - if ("ACK".equals(payload.trim())) { + if (payload.contains("ACK\n")) { acked.set(true); } } From aaed4f36c67ab819905f2b5161f636cc6b192238 Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Tue, 8 Dec 2020 15:52:59 +0100 Subject: [PATCH 7/8] test the latest Ryuk image --- .../utility/ResourceReaper.java | 71 ++++++++++++++----- .../testcontainers/utility/RyukClient.java | 61 +++------------- 2 files changed, 65 insertions(+), 67 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 111d023a2ab..65d97da6a25 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -79,20 +79,49 @@ public static String start(DockerClient client) { .>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())) .collect(Collectors.toList()) ); + + ryukClient = new RyukClient(client, ryukContainerId); + try { - ryukClient = Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS, () -> { - RyukClient ryukClient = new RyukClient(client, ryukContainerId); + 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(); - try { - log.debug("Connecting to the Ryuk watchdog container"); - ryukClient.connect(); - ryukClient.acknowledge(query); - return ryukClient; - } catch (Exception e) { - log.warn("Timed out waiting for the Ryuk watchdog container to start"); - ryukClient.close(); - throw new IllegalStateException("Timed out waiting for the Ryuk watchdog container to start", e); + if (!ack.await(10, 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); @@ -104,7 +133,7 @@ public static String start(DockerClient client) { @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); @@ -148,7 +177,7 @@ public void onNext(Frame frame) { } }); if (!attachment.awaitStarted(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { - log.error("Timed out waiting for Ryuk container's attach. Container id: '{}'", ryukContainerId); + log.error("Timed out waiting for the Ryuk watchdog container's attach. Container id: '{}'", ryukContainerId); throw new IllegalStateException("Failed to attach to Ryuk"); } @@ -157,8 +186,8 @@ public void onNext(Frame frame) { try { if (!started.await(TestcontainersConfiguration.getInstance().getRyukTimeout(), TimeUnit.SECONDS)) { - log.error("Timed out waiting for Ryuk container to start. Ryuk's logs:\n{}", ryukLog); - throw new IllegalStateException("Could not connect to Ryuk"); + 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 { @@ -206,8 +235,18 @@ public synchronized void performCleanup() { * * @param filter the filter */ + @SneakyThrows(InterruptedException.class) public void registerFilterForCleanup(List> filter) { - ryukClient.acknowledge(toQuery(filter)); + 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(); } /** diff --git a/core/src/main/java/org/testcontainers/utility/RyukClient.java b/core/src/main/java/org/testcontainers/utility/RyukClient.java index 869f4ad7577..41c02bc1745 100644 --- a/core/src/main/java/org/testcontainers/utility/RyukClient.java +++ b/core/src/main/java/org/testcontainers/utility/RyukClient.java @@ -4,73 +4,32 @@ import com.github.dockerjava.api.async.ResultCallback; import com.github.dockerjava.api.command.ExecCreateCmdResponse; import com.github.dockerjava.api.model.Frame; -import lombok.RequiredArgsConstructor; -import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -import org.rnorth.ducttape.unreliables.Unreliables; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; +import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -@RequiredArgsConstructor @Slf4j -class RyukClient implements AutoCloseable { +class RyukClient { private final DockerClient dockerClient; private final String ryukContainerId; - private final PipedOutputStream outputStream = new PipedOutputStream(); - - private final AtomicBoolean acked = new AtomicBoolean(true); - - private ResultCallback.Adapter listener; + public RyukClient(DockerClient dockerClient, String ryukContainerId) { + this.dockerClient = dockerClient; + this.ryukContainerId = ryukContainerId; + } - @SneakyThrows - public void connect() { + public > T acknowledge(String query, T callback) { ExecCreateCmdResponse exec = dockerClient.execCreateCmd(ryukContainerId) .withAttachStdin(true) .withAttachStdout(true) .withCmd("nc", "localhost", "8080") .exec(); - listener = dockerClient.execStartCmd(exec.getId()) - .withStdIn(new PipedInputStream(outputStream)) - .exec(new ResultCallback.Adapter() { - @Override - @SneakyThrows - public void onNext(Frame object) { - String payload = new String(object.getPayload(), StandardCharsets.UTF_8); - if (payload.contains("ACK\n")) { - acked.set(true); - } - } - }); - listener.awaitStarted(15, TimeUnit.SECONDS); - } - - @SneakyThrows - public synchronized void acknowledge(String query) { - if (!acked.compareAndSet(true, false)) { - throw new IllegalStateException("ACK is in progress"); - } - log.debug("Sending '{}' to Ryuk", query); - outputStream.write((query + "\n").getBytes()); - outputStream.flush(); - - Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, acked::get); - - log.debug("Received 'ACK' from Ryuk"); - } - - @Override - @SneakyThrows - public void close() { - if (listener != null) { - listener.close(); - } + return dockerClient.execStartCmd(exec.getId()) + .withStdIn(new ByteArrayInputStream((query + "\n").getBytes(StandardCharsets.UTF_8))) + .exec(callback); } } From 8394a1be2f8ca08591779e103393e0be21975ea9 Mon Sep 17 00:00:00 2001 From: Sergei Egorov Date: Tue, 8 Dec 2020 16:06:18 +0100 Subject: [PATCH 8/8] Downgrade OkHttp in `linked-container` example, configurable Ryuk timeout --- .../main/java/org/testcontainers/utility/ResourceReaper.java | 2 +- examples/linked-container/build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java index 65d97da6a25..56d682b3360 100644 --- a/core/src/main/java/org/testcontainers/utility/ResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/ResourceReaper.java @@ -117,7 +117,7 @@ public void onNext(Frame object) { kiraThread.setDaemon(true); kiraThread.start(); - if (!ack.await(10, TimeUnit.SECONDS)) { + 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"); } 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'