diff --git a/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java b/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java index 4adf28406b6..5521fcd2643 100644 --- a/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java +++ b/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java @@ -3,6 +3,7 @@ import lombok.NonNull; import org.rnorth.ducttape.ratelimits.RateLimiter; import org.rnorth.ducttape.ratelimits.RateLimiterBuilder; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.time.Duration; import java.util.Set; @@ -15,16 +16,18 @@ public abstract class AbstractWaitStrategy implements WaitStrategy { static final ExecutorService EXECUTOR = Executors.newCachedThreadPool( - new ThreadFactory() { - private final AtomicLong COUNTER = new AtomicLong(0); + ThreadFactoryCustomizers.customize( + new ThreadFactory() { + private final AtomicLong COUNTER = new AtomicLong(0); - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r, "testcontainers-wait-" + COUNTER.getAndIncrement()); - thread.setDaemon(true); - return thread; + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r, "testcontainers-wait-" + COUNTER.getAndIncrement()); + thread.setDaemon(true); + return thread; + } } - } + ) ); private static final RateLimiter DOCKER_CLIENT_RATE_LIMITER = RateLimiterBuilder diff --git a/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java b/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java new file mode 100644 index 00000000000..bc9e910b3e6 --- /dev/null +++ b/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java @@ -0,0 +1,27 @@ +package org.testcontainers.core; + +import java.util.concurrent.ThreadFactory; + +/** + * Callback interface that can be used to customize the {@link ThreadFactory} of threads Testcontainers creates + * for its own use: the threads that run wait strategy port checks, start containers in parallel, watch image pulls, + * keep the connection to Ryuk open, or start containers for the R2DBC module. Threads created by the + * {@code duct-tape} library, and by {@code docker-java} for streaming calls, are not covered. + *

+ * Implementations are discovered via the Service Provider Interface (SPI) mechanism and must be registered in + * {@code META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer}. + *

+ * Most of these threads belong to pools that are shared across the JVM and that create their threads lazily, on + * whichever thread happens to need one. A customizer lets tooling that tracks state per thread, such as a test + * framework that attributes output to the test that produced it, keep such state from leaking into these shared + * threads. + */ +public interface ThreadFactoryCustomizer { + /** + * Callback to customize a {@link ThreadFactory}. + * + * @param threadFactory the factory Testcontainers would otherwise use; it names the threads and makes them daemon threads + * @return the factory to use instead, typically one that delegates to {@code threadFactory} + */ + ThreadFactory customize(ThreadFactory threadFactory); +} diff --git a/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java b/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java index 88b8804dd8a..4337e6046e7 100644 --- a/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java +++ b/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java @@ -5,6 +5,7 @@ import org.slf4j.Logger; import org.testcontainers.DockerClientFactory; import org.testcontainers.utility.TestcontainersConfiguration; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.io.Closeable; import java.io.IOException; @@ -27,12 +28,12 @@ public class TimeLimitedLoggedPullImageResultCallback extends LoggedPullImageRes private static final ScheduledExecutorService PROGRESS_WATCHDOG_EXECUTOR = Executors.newScheduledThreadPool( 0, - runnable -> { + ThreadFactoryCustomizers.customize(runnable -> { Thread t = new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, runnable); t.setDaemon(true); t.setName("testcontainers-pull-watchdog-" + THREAD_ID.incrementAndGet()); return t; - } + }) ); private static final Duration PULL_PAUSE_TOLERANCE = Duration.ofSeconds( diff --git a/core/src/main/java/org/testcontainers/lifecycle/Startables.java b/core/src/main/java/org/testcontainers/lifecycle/Startables.java index d61919af346..5aadd4ce5d0 100644 --- a/core/src/main/java/org/testcontainers/lifecycle/Startables.java +++ b/core/src/main/java/org/testcontainers/lifecycle/Startables.java @@ -1,6 +1,7 @@ package org.testcontainers.lifecycle; import lombok.experimental.UtilityClass; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.util.Arrays; import java.util.Collection; @@ -18,16 +19,18 @@ public class Startables { private static final Executor EXECUTOR = Executors.newCachedThreadPool( - new ThreadFactory() { - private final AtomicLong COUNTER = new AtomicLong(0); + ThreadFactoryCustomizers.customize( + new ThreadFactory() { + private final AtomicLong COUNTER = new AtomicLong(0); - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r, "testcontainers-lifecycle-" + COUNTER.getAndIncrement()); - thread.setDaemon(true); - return thread; + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r, "testcontainers-lifecycle-" + COUNTER.getAndIncrement()); + thread.setDaemon(true); + return thread; + } } - } + ) ); /** diff --git a/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java b/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java index 999b1cbbffb..a62bef580fe 100644 --- a/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java @@ -81,9 +81,11 @@ private synchronized void maybeStart() { String host = ryukContainer.getHost(); Integer ryukPort = ryukContainer.getFirstMappedPort(); - Thread kiraThread = new Thread( - DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, - () -> { + Thread kiraThread = ThreadFactoryCustomizers + .customize(runnable -> { + return new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, runnable, "testcontainers-ryuk"); + }) + .newThread(() -> { while (true) { RYUK_ACK_RATE_LIMITER.doWhenReady(() -> { int index = 0; @@ -121,9 +123,7 @@ private synchronized void maybeStart() { } }); } - }, - "testcontainers-ryuk" - ); + }); kiraThread.setDaemon(true); kiraThread.start(); // We need to wait before we can start any containers to make sure that we delete them diff --git a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java new file mode 100644 index 00000000000..2d87ea2169c --- /dev/null +++ b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java @@ -0,0 +1,83 @@ +package org.testcontainers.utility; + +import lombok.extern.slf4j.Slf4j; +import org.testcontainers.UnstableAPI; +import org.testcontainers.core.ThreadFactoryCustomizer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.concurrent.ThreadFactory; + +/** + * Applies the {@link ThreadFactoryCustomizer}s registered via SPI to the thread factories Testcontainers uses + * for its own threads. + */ +@UnstableAPI +@Slf4j +public final class ThreadFactoryCustomizers { + + private ThreadFactoryCustomizers() {} + + /** + * Returns {@code threadFactory} customized by every registered {@link ThreadFactoryCustomizer}, in the order + * they are found. A customizer that throws, including a {@link LinkageError} such as a missing class, or returns + * {@code null} is skipped. + */ + public static ThreadFactory customize(ThreadFactory threadFactory) { + return customize(threadFactory, Holder.CUSTOMIZERS); + } + + static ThreadFactory customize(ThreadFactory threadFactory, Iterable customizers) { + ThreadFactory customized = threadFactory; + for (ThreadFactoryCustomizer customizer : customizers) { + try { + ThreadFactory next = customizer.customize(customized); + if (next != null) { + customized = next; + } else { + log.warn("Ignoring null ThreadFactory returned by {}", customizer.getClass().getName()); + } + } catch (Exception | LinkageError e) { + log.warn("Ignoring ThreadFactoryCustomizer {} that failed", customizer.getClass().getName(), e); + } + } + return customized; + } + + /** + * Collects the customizers from {@code providers}, in order. If a provider can't be loaded, or the providers can't + * be listed any further, loading stops with a warning and the customizers loaded so far are kept. It stops rather + * than skipping to the next provider because {@link ServiceLoader} doesn't guarantee that its iterator recovers + * after an error. Besides {@link ServiceConfigurationError}, a provider that can't be linked, for example because a + * class it needs is missing, makes {@link ServiceLoader} throw a {@link LinkageError}, from {@code next()} on Java 8 + * and from {@code hasNext()} on later versions, so that is handled the same way. This never throws, since it runs + * while the shared pools are being initialized. + */ + static List load(Iterator providers) { + List customizers = new ArrayList<>(); + try { + while (providers.hasNext()) { + customizers.add(providers.next()); + } + } catch (ServiceConfigurationError | LinkageError e) { + log.warn( + "Stopped loading ThreadFactoryCustomizers after an error, keeping the {} loaded", + customizers.size(), + e + ); + } + return Collections.unmodifiableList(customizers); + } + + // loaded once, on first use, so that customizers are in place before the first shared pool is created + private static final class Holder { + + private static final List CUSTOMIZERS = load( + ServiceLoader.load(ThreadFactoryCustomizer.class).iterator() + ); + } +} diff --git a/core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java b/core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java new file mode 100644 index 00000000000..25dab4ff345 --- /dev/null +++ b/core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java @@ -0,0 +1,18 @@ +package org.testcontainers.containers.wait.strategy; + +import org.junit.jupiter.api.Test; +import org.testcontainers.custom.TestThreadFactoryCustomizer; + +import static org.assertj.core.api.Assertions.assertThat; + +class AbstractWaitStrategyExecutorTest { + + @Test + void waitStrategyThreadsAreCreatedByTheCustomizedFactory() throws Exception { + Thread thread = AbstractWaitStrategy.EXECUTOR.submit(Thread::currentThread).get(); + + assertThat(thread.getName()).startsWith("testcontainers-wait-"); + assertThat(thread.isDaemon()).isTrue(); + assertThat(TestThreadFactoryCustomizer.CREATED).contains(thread); + } +} diff --git a/core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java b/core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java new file mode 100644 index 00000000000..cbe5d8c505c --- /dev/null +++ b/core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java @@ -0,0 +1,24 @@ +package org.testcontainers.custom; + +import org.testcontainers.core.ThreadFactoryCustomizer; + +import java.util.Collections; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.concurrent.ThreadFactory; + +public class TestThreadFactoryCustomizer implements ThreadFactoryCustomizer { + + public static final Set CREATED = Collections.synchronizedSet( + Collections.newSetFromMap(new WeakHashMap<>()) + ); + + @Override + public ThreadFactory customize(ThreadFactory threadFactory) { + return runnable -> { + Thread thread = threadFactory.newThread(runnable); + CREATED.add(thread); + return thread; + }; + } +} diff --git a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java new file mode 100644 index 00000000000..634fdb9b47e --- /dev/null +++ b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java @@ -0,0 +1,188 @@ +package org.testcontainers.utility; + +import org.junit.jupiter.api.Test; +import org.testcontainers.core.ThreadFactoryCustomizer; +import org.testcontainers.custom.TestThreadFactoryCustomizer; +import org.testcontainers.lifecycle.Startable; +import org.testcontainers.lifecycle.Startables; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.ServiceConfigurationError; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +import static org.assertj.core.api.Assertions.assertThat; + +class ThreadFactoryCustomizersTest { + + @Test + void appliesRegisteredCustomizersToSharedPools() { + AtomicReference startedOn = new AtomicReference<>(); + Startable startable = new Startable() { + @Override + public void start() { + startedOn.set(Thread.currentThread()); + } + + @Override + public void stop() {} + }; + + Startables.deepStart(startable).join(); + + assertThat(startedOn.get().getName()).startsWith("testcontainers-lifecycle-"); + assertThat(TestThreadFactoryCustomizer.CREATED).contains(startedOn.get()); + } + + @Test + void appliesCustomizersInOrder() { + ThreadFactory base = runnable -> new Thread(runnable, "base"); + ThreadFactoryCustomizer first = factory -> runnable -> rename(factory.newThread(runnable), "-first"); + ThreadFactoryCustomizer second = factory -> runnable -> rename(factory.newThread(runnable), "-second"); + + Thread thread = ThreadFactoryCustomizers.customize(base, Arrays.asList(first, second)).newThread(() -> {}); + + assertThat(thread.getName()).isEqualTo("base-first-second"); + } + + @Test + void skipsCustomizersThatFailOrReturnNull() { + ThreadFactory base = runnable -> new Thread(runnable, "base"); + ThreadFactoryCustomizer failing = factory -> { + throw new IllegalStateException("boom"); + }; + ThreadFactoryCustomizer returningNull = factory -> null; + + assertThat(ThreadFactoryCustomizers.customize(base, Arrays.asList(failing, returningNull))).isSameAs(base); + assertThat(ThreadFactoryCustomizers.customize(base, Collections.emptyList())).isSameAs(base); + } + + @Test + void stopsAtAProviderThatCannotBeLoaded() { + ThreadFactoryCustomizer loaded = factory -> factory; + ThreadFactoryCustomizer afterTheError = factory -> factory; + Iterator providers = Arrays + .>asList( + () -> loaded, + () -> { + throw new ServiceConfigurationError("provider could not be instantiated"); + }, + () -> afterTheError + ) + .stream() + .map(Supplier::get) + .iterator(); + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void doesNotRetryAProviderAfterAnError() { + // an iterator that never moves past the failing provider, which ServiceLoader's contract allows; + // a retry fails the test immediately, since load only catches ServiceConfigurationError + AtomicInteger attempts = new AtomicInteger(); + Iterator providers = new Iterator() { + @Override + public boolean hasNext() { + return true; + } + + @Override + public ThreadFactoryCustomizer next() { + if (attempts.incrementAndGet() > 1) { + throw new AssertionError("retried the failing provider"); + } + throw new ServiceConfigurationError("provider could not be instantiated"); + } + }; + + assertThat(ThreadFactoryCustomizers.load(providers)).isEmpty(); + assertThat(attempts).hasValue(1); + } + + @Test + void stopsWhenTheProvidersCannotBeListed() { + ThreadFactoryCustomizer loaded = factory -> factory; + Iterator providers = new Iterator() { + private boolean returned = false; + + @Override + public boolean hasNext() { + if (returned) { + throw new ServiceConfigurationError("unreadable provider configuration"); + } + return true; + } + + @Override + public ThreadFactoryCustomizer next() { + returned = true; + return loaded; + } + }; + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void stopsWhenAProviderCannotBeLinkedInNext() { + // Java 8's ServiceLoader lets a provider's linkage failure, such as a missing superclass, escape from next() + ThreadFactoryCustomizer loaded = factory -> factory; + Iterator providers = Arrays + .>asList( + () -> loaded, + () -> { + throw new NoClassDefFoundError("com/example/MissingSuperclass"); + } + ) + .stream() + .map(Supplier::get) + .iterator(); + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void stopsWhenAProviderCannotBeLinkedInHasNext() { + // later versions load the provider class ahead of time, so the same failure escapes from hasNext() + ThreadFactoryCustomizer loaded = factory -> factory; + Iterator providers = new Iterator() { + private boolean returned = false; + + @Override + public boolean hasNext() { + if (returned) { + throw new NoClassDefFoundError("com/example/MissingSuperclass"); + } + return true; + } + + @Override + public ThreadFactoryCustomizer next() { + returned = true; + return loaded; + } + }; + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void skipsCustomizersThatCannotBeLinked() { + ThreadFactory base = runnable -> new Thread(runnable, "base"); + ThreadFactoryCustomizer unlinkable = factory -> { + throw new NoClassDefFoundError("com/example/MissingDependency"); + }; + + assertThat(ThreadFactoryCustomizers.customize(base, Collections.singletonList(unlinkable))).isSameAs(base); + } + + private static Thread rename(Thread thread, String suffix) { + thread.setName(thread.getName() + suffix); + return thread; + } +} diff --git a/core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer b/core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer new file mode 100644 index 00000000000..087ee96f35b --- /dev/null +++ b/core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer @@ -0,0 +1 @@ +org.testcontainers.custom.TestThreadFactoryCustomizer diff --git a/docs/features/advanced_options.md b/docs/features/advanced_options.md index e979da9ecdf..a25e8c6c4d7 100644 --- a/docs/features/advanced_options.md +++ b/docs/features/advanced_options.md @@ -86,6 +86,37 @@ The previous implementation should be registered in `META-INF/services/org.testc !!! warning `CreateContainerCmdModifier` implementation will apply to all containers created by Testcontainers. +## Customizing Testcontainers' own threads + +Testcontainers runs some of its work on threads it creates itself. Most of them belong to pools that are shared by +the whole JVM and that create their threads lazily. + +Tools that track state per thread, such as a test framework that attributes output to the test that produced it, +can customize how these threads are created with a `ThreadFactoryCustomizer`, via the Service Provider Interface (SPI) mechanism. +The customizer receives the factory Testcontainers would otherwise use, and returns the factory to use instead. +It applies to the threads that: + +* run port checks for wait strategies (`testcontainers-wait-*`) +* start containers in parallel with `Startables.deepStart` (`testcontainers-lifecycle-*`) +* watch image pulls (`testcontainers-pull-watchdog-*`) +* keep the connection to Ryuk open (`testcontainers-ryuk`) +* start containers for the R2DBC module (`testcontainers-r2dbc-*`) + +It does not apply to the threads of the `duct-tape` library (`ducttape-*`), on which most wait strategies and startup +checks run their retries with a timeout, nor to the threads `docker-java` starts for streaming calls, such as following +a container's logs. + + +[ThreadFactoryCustomizer example implementation](../../core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java) + + +The previous implementation should be registered in `META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer` file. + +!!! warning + A `ThreadFactoryCustomizer` applies to all of the threads listed above, and is loaded once, + when the first of them is created. The factory it returns should delegate to the one it receives, + so that the threads keep their names and remain daemon threads. + ## Parallel Container Startup Usually, containers are started sequentially when more than one container is used. diff --git a/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java b/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java index bada076eec9..f0843c9ba3f 100644 --- a/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java +++ b/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java @@ -8,6 +8,7 @@ import io.r2dbc.spi.ConnectionFactoryOptions; import org.reactivestreams.Publisher; import org.testcontainers.lifecycle.Startable; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.util.ServiceLoader; import java.util.concurrent.CompletableFuture; @@ -20,12 +21,14 @@ class TestcontainersR2DBCConnectionFactory implements ConnectionFactory, Closeab private static final AtomicLong THREAD_COUNT = new AtomicLong(); - private static final Executor EXECUTOR = Executors.newCachedThreadPool(r -> { - Thread thread = new Thread(r); - thread.setName("testcontainers-r2dbc-" + THREAD_COUNT.getAndIncrement()); - thread.setDaemon(true); - return thread; - }); + private static final Executor EXECUTOR = Executors.newCachedThreadPool( + ThreadFactoryCustomizers.customize(r -> { + Thread thread = new Thread(r); + thread.setName("testcontainers-r2dbc-" + THREAD_COUNT.getAndIncrement()); + thread.setDaemon(true); + return thread; + }) + ); private final ConnectionFactoryOptions options;