Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,21 @@ public class DockerClientFactory {
public static final ThreadGroup TESTCONTAINERS_THREAD_GROUP = new ThreadGroup("testcontainers");
public static final String TESTCONTAINERS_LABEL = DockerClientFactory.class.getPackage().getName();
public static final String TESTCONTAINERS_SESSION_ID_LABEL = TESTCONTAINERS_LABEL + ".sessionId";
public static final String TESTCONTAINERS_REUSABLE_LABLE = TESTCONTAINERS_LABEL + ".dontkillme";

public static final String SESSION_ID = UUID.randomUUID().toString();
public static final String MAGIC_WORD = "please";

public static final Map<String, String> DEFAULT_LABELS = ImmutableMap.of(
TESTCONTAINERS_LABEL, "true",
TESTCONTAINERS_SESSION_ID_LABEL, SESSION_ID
);

public static final Map<String, String> REUSABLE_LABELS = ImmutableMap.of(
TESTCONTAINERS_LABEL, "true",
TESTCONTAINERS_REUSABLE_LABLE, MAGIC_WORD
);

private static final String TINY_IMAGE = TestcontainersConfiguration.getInstance().getTinyImage();
private static DockerClientFactory instance;

Expand Down
24 changes: 24 additions & 0 deletions core/src/main/java/org/testcontainers/containers/Container.java
Original file line number Diff line number Diff line change
Expand Up @@ -503,4 +503,28 @@ ExecResult execInContainer(Charset outputCharset, String... command)
void setLinkedContainers(Map<String, LinkableContainer> linkedContainers);

void setWaitStrategy(WaitStrategy waitStrategy);

/**
* Allow TC reuse previously created container
* <p>
* With this mode all <strong>TC container settings will be applied only once</strong> - at the time of container creation.
* After JVM destruction created container continues to live unaffected.
* Subsequent starts of TC container will find previously created container by specified container name
* and reinitialize it. If container isn't found then new one will be created. If container is found but stopped,
* TC will start it and continue to use started container.
* <p>
* Previously created container should have exactly the same image and version as specified in TC container configuration.
* Otherwise {@link ContainerLaunchException} will be raised.
* <p>
* Reusing existing container allows to seriously reduce time consumed by container creation and starting
* although it should be used carefully.
* <p>
* For CI environments reusable mode can be disabled globally or at container's level:
* - by setting testcontainers.properties containers.is.reusing.enabled.when.reusable value to false
* - by setting ReusableContainerConfiguration.builder().isEnabled(false)
*
* @param configuration reusable configuration containing Docker container name
* @return this
*/
SELF withReuseExistingContainerStrategy(ReusableContainerConfiguration configuration);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.testcontainers.containers;

/**
* @author Eugeny Karpov
*/
public enum ContainerStrategyType {
DISPOSABLE,
REUSABLE
}
119 changes: 106 additions & 13 deletions core/src/main/java/org/testcontainers/containers/GenericContainer.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import lombok.Setter;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.runner.Description;
Expand Down Expand Up @@ -71,6 +72,7 @@
import static org.testcontainers.containers.output.OutputFrame.OutputType.STDERR;
import static org.testcontainers.containers.output.OutputFrame.OutputType.STDOUT;
import static org.testcontainers.utility.CommandLine.runShellCommand;
import static org.testcontainers.utility.DockerUtils.isContainerNameEqual;

/**
* Base class for that allows a container to be launched and controlled.
Expand Down Expand Up @@ -168,6 +170,12 @@ public class GenericContainer<SELF extends GenericContainer<SELF>>
@Setter(AccessLevel.NONE)
private InspectContainerResponse containerInfo;

@Setter(AccessLevel.NONE)
private ContainerStrategyType strategyType = ContainerStrategyType.DISPOSABLE;

@Setter(AccessLevel.NONE)
private boolean isReusingEnabledWhenReusable = false;

/**
* The approach to determine if the container is ready.
*/
Expand Down Expand Up @@ -237,19 +245,12 @@ protected void doStart() {
private void tryStart(Profiler profiler) {
try {
String dockerImageName = image.get();
logger().debug("Starting container: {}", dockerImageName);

logger().info("Creating container for image: {}", dockerImageName);
profiler.start("Create container");
CreateContainerCmd createCommand = dockerClient.createContainerCmd(dockerImageName);
applyConfiguration(createCommand);

containerId = createCommand.exec().getId();
copyToFileContainerPathMap.forEach(this::copyFileToContainer);

logger().info("Starting container with ID: {}", containerId);
profiler.start("Start container");
dockerClient.startContainerCmd(containerId).exec();
if (isReusingEnabledWhenReusable) {
tryUseReusableContainer(profiler, dockerImageName);

@AnkBurov AnkBurov Jul 15, 2018 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would extract tryUseReusableContainer() and tryStartDisposableContainer() methods into separate classes like ReusableContainerLaunchStrategy and also methods createContainer() (with applyConfiguration private method) and startContainer() to Command pattern classes but it would require moving a lot of existing code from GenericContainer so to keep diff as small as possible I wrote new code in a procedure way like the remaining code of GenericContainer.

} else {
tryStartDisposableContainer(profiler, dockerImageName);
}

// For all registered output consumers, start following as close to container startup as possible
this.logConsumers.forEach(this::followOutput);
Expand Down Expand Up @@ -300,6 +301,53 @@ private void tryStart(Profiler profiler) {
}
}

/**
* Try using reusable container with current container name
*/
private void tryUseReusableContainer(Profiler profiler, String dockerImageName) {
logger().debug("Using reusable container: {} with name: {}", dockerImageName, containerName);

if (StringUtils.isBlank(containerName)) {
logger().error("Container name cannot be blank when using REUSABLE strategy");
throw new ContainerLaunchException("Blank container name");
}

// find container with the specified name or create new one if none found
InspectContainerResponse createdContainer = dockerClient.listContainersCmd()
.withNameFilter(Collections.singletonList(containerName))
.withShowAll(true)
.exec()
.stream()
.filter(container -> isContainerNameEqual(container, containerName))
.map(container -> dockerClient.inspectContainerCmd(container.getId()).exec())
.findFirst()
.orElseGet(() -> createContainer(profiler, dockerImageName));

// check that found image is using exactly the same image
String createdContainerImage = createdContainer.getConfig().getImage();
if (!dockerImageName.equals(createdContainerImage)) {
logger().error("Found existing container with name {} has unexpected image {}",
createdContainer.getName(), createdContainerImage);
throw new ContainerLaunchException("Unexpected image");
}

containerId = createdContainer.getId();

// if container is stopped then start it
Boolean isRunning = createdContainer.getState().getRunning();
if (Boolean.FALSE.equals(isRunning)) {
startContainer(profiler);
}
}

private void tryStartDisposableContainer(Profiler profiler, String dockerImageName) {
logger().debug("Starting container: {}", dockerImageName);

createContainer(profiler, dockerImageName);

startContainer(profiler);
}

/**
* Stops the container.
*/
Expand Down Expand Up @@ -403,7 +451,28 @@ public Set<Integer> getLivenessCheckPortNumbers() {
return this.getLivenessCheckPorts();
}

private InspectContainerResponse createContainer(Profiler profiler, String dockerImageName) {
logger().info("Creating container for image: {}", dockerImageName);
profiler.start("Create container");

CreateContainerCmd createCommand = dockerClient.createContainerCmd(dockerImageName);
applyConfiguration(createCommand);

containerId = createCommand.exec().getId();
copyToFileContainerPathMap.forEach(this::copyFileToContainer);

return dockerClient.inspectContainerCmd(containerId).exec();
}

private void applyConfiguration(CreateContainerCmd createCommand) {
/*in reusable mode container should only start with specified name -
to prevent uncontrolled creation of unnamed containers*/
if (isReusingEnabledWhenReusable) {
if (StringUtils.isBlank(containerName)) {
throw new ContainerLaunchException("Container name must be specified when using REUSABLE strategy");
}
createCommand.withName(containerName);
}

// Set up exposed ports (where there are no host port bindings defined)
ExposedPort[] portArray = exposedPorts.stream()
Expand Down Expand Up @@ -499,11 +568,22 @@ private void applyConfiguration(CreateContainerCmd createCommand) {
if (createCommand.getLabels() != null) {
combinedLabels.putAll(createCommand.getLabels());
}
combinedLabels.putAll(DockerClientFactory.DEFAULT_LABELS);

if (isReusingEnabledWhenReusable) {
combinedLabels.putAll(DockerClientFactory.REUSABLE_LABELS);
} else {
combinedLabels.putAll(DockerClientFactory.DEFAULT_LABELS);
}

createCommand.withLabels(combinedLabels);
}

private void startContainer(Profiler profiler) {
logger().info("Starting container with ID: {}", containerId);
profiler.start("Start container");
dockerClient.startContainerCmd(containerId).exec();
}

private Set<Link> findLinksFromThisContainer(String alias, LinkableContainer linkableContainer) {
return dockerClient.listContainersCmd()
.withStatusFilter(Arrays.asList("running"))
Expand Down Expand Up @@ -1073,6 +1153,19 @@ public SELF withCreateContainerCmdModifier(Consumer<CreateContainerCmd> modifier
return self();
}

/**
* {@inheritDoc}
*/
@Override
public SELF withReuseExistingContainerStrategy(ReusableContainerConfiguration configuration) {
containerName = configuration.getContainerName();
strategyType = ContainerStrategyType.REUSABLE;
isReusingEnabledWhenReusable =
TestcontainersConfiguration.getInstance().isReusingEnabledWhenReusable() // check global configuration
&& configuration.isEnabled(); // check container configuration
return self();
}

/**
* Convenience class with access to non-public members of GenericContainer.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.testcontainers.containers;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;

/**
* @author Eugeny Karpov
*/
@Getter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class ReusableContainerConfiguration {

private final String containerName;
private final boolean isEnabled;

public static Builder builder() {
return new Builder();
}

public static class Builder {
private String containerName;
private Boolean isEnabled = true;

public Builder withContainerName(String containerName) {
this.containerName = containerName;
return this;
}

public Builder isEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
return this;
}

public ReusableContainerConfiguration build() {
if (StringUtils.isBlank(containerName)) {
throw new IllegalArgumentException("Container name must be specified with REUSABLE mode");
}
return new ReusableContainerConfiguration(containerName, isEnabled);
}
}
}
25 changes: 25 additions & 0 deletions core/src/main/java/org/testcontainers/utility/DockerUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package org.testcontainers.utility;

import com.github.dockerjava.api.model.Container;
import lombok.experimental.UtilityClass;

import java.util.Arrays;

/**
* @author Eugeny Karpov
*/
@UtilityClass
public class DockerUtils {

/**
* Check if container has specified name
*
* If container name starts with / (all names in com.github.dockerjava.api.model.Container.names are starting with /)
* then omit first letter
*/
public static boolean isContainerNameEqual(Container container, String containerName) {
return Arrays.stream(container.getNames())
.map(name -> name.startsWith("/") ? name.substring(1) : name)
.anyMatch(name -> name.equals(containerName));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ public String getTransportType() {
return properties.getProperty("transport.type", "netty");
}

public boolean isReusingEnabledWhenReusable() {
return Boolean.parseBoolean((String)
properties.getOrDefault("containers.is.reusing.enabled.when.reusable", "true"));
}

@Synchronized
public boolean updateGlobalConfig(@NonNull String prop, @NonNull String value) {
try {
Expand Down
Loading