Support parallel initialization of Testcontainers

Add support for a `spring.testcontainers.startup` property that can
be set to "sequential" or "parallel" to change how containers are
started.

Closes gh-37073
This commit is contained in:
Phillip Webb
2023-10-14 23:44:45 -07:00
parent 1edd1d5078
commit 4c3a0f09d7
11 changed files with 293 additions and 16 deletions

View File

@@ -47,7 +47,8 @@ public class TestcontainersLifecycleApplicationContextInitializer
}
ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
applicationContext.addBeanFactoryPostProcessor(new TestcontainersLifecycleBeanFactoryPostProcessor());
beanFactory.addBeanPostProcessor(new TestcontainersLifecycleBeanPostProcessor(beanFactory));
TestcontainersStartup startup = TestcontainersStartup.get(applicationContext.getEnvironment());
beanFactory.addBeanPostProcessor(new TestcontainersLifecycleBeanPostProcessor(beanFactory, startup));
}
}

View File

@@ -16,9 +16,11 @@
package org.springframework.boot.testcontainers.lifecycle;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -58,48 +60,61 @@ class TestcontainersLifecycleBeanPostProcessor implements DestructionAwareBeanPo
private final ConfigurableListableBeanFactory beanFactory;
private final TestcontainersStartup startup;
private volatile boolean containersInitialized = false;
TestcontainersLifecycleBeanPostProcessor(ConfigurableListableBeanFactory beanFactory) {
TestcontainersLifecycleBeanPostProcessor(ConfigurableListableBeanFactory beanFactory,
TestcontainersStartup startup) {
this.beanFactory = beanFactory;
this.startup = startup;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Startable startable) {
startable.start();
}
if (this.beanFactory.isConfigurationFrozen()) {
if (!this.containersInitialized && this.beanFactory.isConfigurationFrozen()) {
initializeContainers();
}
return bean;
}
private void initializeContainers() {
if (this.containersInitialized) {
return;
}
this.containersInitialized = true;
Set<String> beanNames = new LinkedHashSet<>();
beanNames.addAll(List.of(this.beanFactory.getBeanNamesForType(ContainerState.class, false, false)));
beanNames.addAll(List.of(this.beanFactory.getBeanNamesForType(Startable.class, false, false)));
initializeContainers(beanNames);
}
private void initializeContainers(Set<String> beanNames) {
List<Object> beans = new ArrayList<>(beanNames.size());
for (String beanName : beanNames) {
try {
this.beanFactory.getBean(beanName);
beans.add(this.beanFactory.getBean(beanName));
}
catch (BeanCreationException ex) {
if (ex.contains(BeanCurrentlyInCreationException.class)) {
this.containersInitialized = false;
return;
}
throw ex;
}
}
if (!beanNames.isEmpty()) {
logger.debug(LogMessage.format("Initialized container beans '%s'", beanNames));
if (!this.containersInitialized) {
this.containersInitialized = true;
if (!beanNames.isEmpty()) {
logger.debug(LogMessage.format("Initialized container beans '%s'", beanNames));
}
start(beans);
}
}
private void start(List<Object> beans) {
Set<Startable> startables = beans.stream()
.filter(Startable.class::isInstance)
.map(Startable.class::cast)
.collect(Collectors.toCollection(LinkedHashSet::new));
this.startup.start(startables);
}
@Override
public boolean requiresDestruction(Object bean) {
return bean instanceof Startable;

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.testcontainers.lifecycle;
import java.util.Collection;
import org.testcontainers.lifecycle.Startable;
import org.testcontainers.lifecycle.Startables;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
/**
* Testcontainers startup strategies. The strategy to use can be configured in the Spring
* {@link Environment} with a {@value #PROPERTY} property.
*
* @author Phillip Webb
* @since 3.2.0
*/
public enum TestcontainersStartup {
/**
* Startup containers sequentially.
*/
SEQUENTIAL {
@Override
void start(Collection<? extends Startable> startables) {
startables.forEach(Startable::start);
}
},
/**
* Startup containers in parallel.
*/
PARALLEL {
@Override
void start(Collection<? extends Startable> startables) {
Startables.deepStart(startables).join();
}
};
/**
* The {@link Environment} property used to change the {@link TestcontainersStartup}
* strategy.
*/
public static final String PROPERTY = "spring.testcontainers.startup";
abstract void start(Collection<? extends Startable> startables);
static TestcontainersStartup get(ConfigurableEnvironment environment) {
return get((environment != null) ? environment.getProperty(PROPERTY) : null);
}
private static TestcontainersStartup get(String value) {
if (value == null) {
return SEQUENTIAL;
}
String canonicalName = getCanonicalName(value);
for (TestcontainersStartup candidate : values()) {
if (candidate.name().equalsIgnoreCase(canonicalName)) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown '%s' property value '%s'".formatted(PROPERTY, value));
}
private static String getCanonicalName(String name) {
StringBuilder canonicalName = new StringBuilder(name.length());
name.chars()
.filter(Character::isLetterOrDigit)
.map(Character::toLowerCase)
.forEach((c) -> canonicalName.append((char) c));
return canonicalName.toString();
}
}

View File

@@ -0,0 +1,10 @@
{
"properties": [
{
"name": "spring.testcontainers.startup",
"type": "org.springframework.boot.testcontainers.lifecycle.TestcontainersStartup",
"description": "Testcontainers startup modes.",
"defaultValue": "sequential"
}
]
}