How to use DockerClientProviderStrategy class of org.testcontainers.dockerclient package

Best Testcontainers-java code snippet using org.testcontainers.dockerclient.DockerClientProviderStrategy

Source:DockerClientFactory.java Github

copy

Full Screen

...12import lombok.extern.slf4j.Slf4j;13import org.hamcrest.BaseMatcher;14import org.hamcrest.Description;15import org.rnorth.visibleassertions.VisibleAssertions;16import org.testcontainers.dockerclient.DockerClientProviderStrategy;17import org.testcontainers.dockerclient.DockerMachineClientProviderStrategy;18import org.testcontainers.utility.ComparableVersion;19import org.testcontainers.utility.ResourceReaper;20import org.testcontainers.utility.TestcontainersConfiguration;21import java.io.ByteArrayOutputStream;22import java.io.InputStream;23import java.util.ArrayList;24import java.util.List;25import java.util.Map;26import java.util.Optional;27import java.util.ServiceLoader;28import java.util.UUID;29import java.util.function.BiFunction;30import java.util.function.Consumer;31/**32 * Singleton class that provides initialized Docker clients.33 * <p>34 * The correct client configuration to use will be determined on first use, and cached thereafter.35 */36@Slf4j37public class DockerClientFactory {38 public static final ThreadGroup TESTCONTAINERS_THREAD_GROUP = new ThreadGroup("testcontainers");39 public static final String TESTCONTAINERS_LABEL = DockerClientFactory.class.getPackage().getName();40 public static final String TESTCONTAINERS_SESSION_ID_LABEL = TESTCONTAINERS_LABEL + ".sessionId";41 public static final String SESSION_ID = UUID.randomUUID().toString();42 public static final Map<String, String> DEFAULT_LABELS = ImmutableMap.of(43 TESTCONTAINERS_LABEL, "true",44 TESTCONTAINERS_SESSION_ID_LABEL, SESSION_ID45 );46 private static final String TINY_IMAGE = TestcontainersConfiguration.getInstance().getTinyImage();47 private static DockerClientFactory instance;48 // Cached client configuration49 private DockerClientProviderStrategy strategy;50 private boolean initialized = false;51 private String activeApiVersion;52 private String activeExecutionDriver;53 static {54 System.setProperty("org.testcontainers.shaded.io.netty.packagePrefix", "org.testcontainers.shaded.");55 }56 /**57 * Private constructor58 */59 private DockerClientFactory() {60 }61 /**62 * Obtain an instance of the DockerClientFactory.63 *64 * @return the singleton instance of DockerClientFactory65 */66 public synchronized static DockerClientFactory instance() {67 if (instance == null) {68 instance = new DockerClientFactory();69 }70 return instance;71 }72 /**73 *74 * @return a new initialized Docker client75 */76 @Synchronized77 public DockerClient client() {78 if (strategy != null) {79 return strategy.getClient();80 }81 List<DockerClientProviderStrategy> configurationStrategies = new ArrayList<DockerClientProviderStrategy>();82 ServiceLoader.load(DockerClientProviderStrategy.class).forEach( cs -> configurationStrategies.add( cs ) );83 strategy = DockerClientProviderStrategy.getFirstValidStrategy(configurationStrategies);84 String hostIpAddress = strategy.getDockerHostIpAddress();85 log.info("Docker host IP address is {}", hostIpAddress);86 DockerClient client = strategy.getClient();87 if (!initialized) {88 Info dockerInfo = client.infoCmd().exec();89 Version version = client.versionCmd().exec();90 activeApiVersion = version.getApiVersion();91 activeExecutionDriver = dockerInfo.getExecutionDriver();92 log.info("Connected to docker: \n" +93 " Server Version: " + dockerInfo.getServerVersion() + "\n" +94 " API Version: " + activeApiVersion + "\n" +95 " Operating System: " + dockerInfo.getOperatingSystem() + "\n" +96 " Total Memory: " + dockerInfo.getMemTotal() / (1024 * 1024) + " MB");97 boolean checksEnabled = !TestcontainersConfiguration.getInstance().isDisableChecks();98 String ryukContainerId = ResourceReaper.start(hostIpAddress, client, checksEnabled);99 log.info("Ryuk started - will monitor and terminate Testcontainers containers on JVM exit");100 VisibleAssertions.info("Checking the system...");101 checkDockerVersion(version.getVersion());102 if (checksEnabled) {103 checkDiskSpace(client, ryukContainerId);104 checkMountableFile(client, ryukContainerId);105 }106 initialized = true;107 }108 return client;109 }110 private void checkDockerVersion(String dockerVersion) {111 VisibleAssertions.assertThat("Docker version", dockerVersion, new BaseMatcher<String>() {112 @Override113 public boolean matches(Object o) {114 return new ComparableVersion(o.toString()).compareTo(new ComparableVersion("1.6.0")) >= 0;115 }116 @Override117 public void describeTo(Description description) {118 description.appendText("should be at least 1.6.0");119 }120 });121 }122 private void checkDiskSpace(DockerClient dockerClient, String id) {123 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();124 try {125 dockerClient126 .execStartCmd(dockerClient.execCreateCmd(id).withAttachStdout(true).withCmd("df", "-P").exec().getId())127 .exec(new ExecStartResultCallback(outputStream, null))128 .awaitCompletion();129 } catch (Exception e) {130 log.debug("Can't exec disk checking command", e);131 }132 DiskSpaceUsage df = parseAvailableDiskSpace(outputStream.toString());133 VisibleAssertions.assertTrue(134 "Docker environment should have more than 2GB free disk space",135 df.availableMB.map(it -> it >= 2048).orElse(true)136 );137 }138 private void checkMountableFile(DockerClient dockerClient, String id) {139 try (InputStream stream = dockerClient.copyArchiveFromContainerCmd(id, "/dummy").exec()) {140 stream.read();141 VisibleAssertions.pass("File should be mountable");142 } catch (Exception e) {143 VisibleAssertions.fail("File should be mountable but fails with " + e.getMessage());144 }145 }146 /**147 * Check whether the image is available locally and pull it otherwise148 */149 public void checkAndPullImage(DockerClient client, String image) {150 List<Image> images = client.listImagesCmd().withImageNameFilter(image).exec();151 if (images.isEmpty()) {152 client.pullImageCmd(image).exec(new PullImageResultCallback()).awaitSuccess();153 }154 }155 /**156 * @return the IP address of the host running Docker157 */158 public String dockerHostIpAddress() {159 return strategy.getDockerHostIpAddress();160 }161 public <T> T runInsideDocker(Consumer<CreateContainerCmd> createContainerCmdConsumer, BiFunction<DockerClient, String, T> block) {162 if (strategy == null) {163 client();164 }165 // We can't use client() here because it might create an infinite loop166 return runInsideDocker(strategy.getClient(), createContainerCmdConsumer, block);167 }168 private <T> T runInsideDocker(DockerClient client, Consumer<CreateContainerCmd> createContainerCmdConsumer, BiFunction<DockerClient, String, T> block) {169 checkAndPullImage(client, TINY_IMAGE);170 CreateContainerCmd createContainerCmd = client.createContainerCmd(TINY_IMAGE)171 .withLabels(DEFAULT_LABELS);172 createContainerCmdConsumer.accept(createContainerCmd);173 String id = createContainerCmd.exec().getId();174 try {175 client.startContainerCmd(id).exec();176 return block.apply(client, id);177 } finally {178 try {179 client.removeContainerCmd(id).withRemoveVolumes(true).withForce(true).exec();180 } catch (NotFoundException | InternalServerErrorException ignored) {181 log.debug("", ignored);182 }183 }184 }185 @VisibleForTesting186 static class DiskSpaceUsage {187 Optional<Long> availableMB = Optional.empty();188 Optional<Integer> usedPercent = Optional.empty();189 }190 @VisibleForTesting191 DiskSpaceUsage parseAvailableDiskSpace(String dfOutput) {192 DiskSpaceUsage df = new DiskSpaceUsage();193 String[] lines = dfOutput.split("\n");194 for (String line : lines) {195 String[] fields = line.split("\\s+");196 if (fields.length > 5 && fields[5].equals("/")) {197 long availableKB = Long.valueOf(fields[3]);198 df.availableMB = Optional.of(availableKB / 1024L);199 df.usedPercent = Optional.of(Integer.valueOf(fields[4].replace("%", "")));200 break;201 }202 }203 return df;204 }205 /**206 * @return the docker API version of the daemon that we have connected to207 */208 public String getActiveApiVersion() {209 if (!initialized) {210 client();211 }212 return activeApiVersion;213 }214 /**215 * @return the docker execution driver of the daemon that we have connected to216 */217 public String getActiveExecutionDriver() {218 if (!initialized) {219 client();220 }221 return activeExecutionDriver;222 }223 /**224 * @param providerStrategyClass a class that extends {@link DockerMachineClientProviderStrategy}225 * @return whether or not the currently active strategy is of the provided type226 */227 public boolean isUsing(Class<? extends DockerClientProviderStrategy> providerStrategyClass) {228 return providerStrategyClass.isAssignableFrom(this.strategy.getClass());229 }230 private static class NotEnoughDiskSpaceException extends RuntimeException {231 NotEnoughDiskSpaceException(String message) {232 super(message);233 }234 }235}...

Full Screen

Full Screen

Source:DockerClientProviderStrategy.java Github

copy

Full Screen

...22import java.util.stream.Stream;23/**24 * Mechanism to find a viable Docker client configuration according to the host system environment.25 */26public abstract class DockerClientProviderStrategy {27 protected DockerClient client;28 protected DockerClientConfig config;29 private static final RateLimiter PING_RATE_LIMITER = RateLimiterBuilder.newBuilder()30 .withRate(2, TimeUnit.SECONDS)31 .withConstantThroughput()32 .build();33 private static final AtomicBoolean FAIL_FAST_ALWAYS = new AtomicBoolean(false);34 /**35 * @throws InvalidConfigurationException if this strategy fails36 */37 public abstract void test() throws InvalidConfigurationException;38 /**39 * @return a short textual description of the strategy40 */41 public abstract String getDescription();42 protected boolean isApplicable() {43 return true;44 }45 protected boolean isPersistable() {46 return true;47 }48 /**49 * @return highest to lowest priority value50 */51 protected int getPriority() {52 return 0;53 }54 protected static final Logger LOGGER = LoggerFactory.getLogger(DockerClientProviderStrategy.class);55 /**56 * Determine the right DockerClientConfig to use for building clients by trial-and-error.57 *58 * @return a working DockerClientConfig, as determined by successful execution of a ping command59 */60 public static DockerClientProviderStrategy getFirstValidStrategy(List<DockerClientProviderStrategy> strategies) {61 if (FAIL_FAST_ALWAYS.get()) {62 throw new IllegalStateException("Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration");63 }64 List<String> configurationFailures = new ArrayList<>();65 return Stream66 .concat(67 Stream68 .of(TestcontainersConfiguration.getInstance().getDockerClientStrategyClassName())69 .filter(Objects::nonNull)70 .flatMap(it -> {71 try {72 Class<? extends DockerClientProviderStrategy> strategyClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(it);73 return Stream.of(strategyClass.newInstance());74 } catch (ClassNotFoundException e) {75 LOGGER.warn("Can't instantiate a strategy from {} (ClassNotFoundException). " +76 "This probably means that cached configuration refers to a client provider " +77 "class that is not available in this version of Testcontainers. Other " +78 "strategies will be tried instead.", it);79 return Stream.empty();80 } catch (InstantiationException | IllegalAccessException e) {81 LOGGER.warn("Can't instantiate a strategy from {}", it, e);82 return Stream.empty();83 }84 })85 // Ignore persisted strategy if it's not persistable anymore86 .filter(DockerClientProviderStrategy::isPersistable)87 .peek(strategy -> LOGGER.info("Loaded {} from ~/.testcontainers.properties, will try it first", strategy.getClass().getName())),88 strategies89 .stream()90 .filter(DockerClientProviderStrategy::isApplicable)91 .sorted(Comparator.comparing(DockerClientProviderStrategy::getPriority).reversed())92 )93 .flatMap(strategy -> {94 try {95 strategy.test();96 LOGGER.info("Found Docker environment with {}", strategy.getDescription());97 if (strategy.isPersistable()) {98 TestcontainersConfiguration.getInstance().updateGlobalConfig("docker.client.strategy", strategy.getClass().getName());99 }100 return Stream.of(strategy);101 } catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) {102 @Nullable String throwableMessage = e.getMessage();103 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")104 Throwable rootCause = Throwables.getRootCause(e);105 @Nullable String rootCauseMessage = rootCause.getMessage();...

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1import java.io.IOException;2import org.testcontainers.DockerClientFactory;3import org.testcontainers.dockerclient.DockerClientProviderStrategy;4import org.testcontainers.dockerclient.DockerMachineClientProviderStrategy;5import org.testcontainers.dockerclient.EnvironmentAndSystemPropertyClientProviderStrategy;6public class DockerClientProviderStrategyTest {7 public static void main(String[] args) throws IOException {8 DockerClientProviderStrategy strategy = DockerClientFactory.instance().getStrategy();9 DockerClientProviderStrategy[] strategies = DockerClientFactory.instance().getStrategies();10 DockerClientProviderStrategy[] allStrategies = DockerClientFactory.instance().getAllStrategies();11 DockerClientProviderStrategy strategy1 = DockerClientFactory.instance().getStrategy("DockerMachineClientProviderStrategy");12 DockerClientProviderStrategy strategy2 = DockerClientFactory.instance().getStrategy(DockerMachineClientProviderStrategy.class);13 DockerClientProviderStrategy strategy3 = DockerClientFactory.instance().getStrategy(EnvironmentAndSystemPropertyClientProviderStrategy.class);14 DockerClientProviderStrategy strategy4 = DockerClientFactory.instance().getStrategy("EnvironmentAndSystemPropertyClientProviderStrategy");15 DockerClientProviderStrategy strategy5 = DockerClientFactory.instance().getStrategy("org.testcontainers.dockerclient.EnvironmentAndSystemPropertyClientProviderStrategy");16 DockerClientProviderStrategy strategy6 = DockerClientFactory.instance().getStrategy("org.testcontainers.dockerclient.DockerMachineClientProviderStrategy");17 DockerClientProviderStrategy strategy7 = DockerClientFactory.instance().getStrategy("DockerMachineClientProviderStrategy");18 DockerClientProviderStrategy strategy8 = DockerClientFactory.instance().getStrategy(DockerMachineClientProviderStrategy.class);

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientProviderStrategy;2import org.testcontainers.dockerclient.DockerClientConfigUtils;3import org.testcontainers.utility.DockerImageName;4import org.testcontainers.containers.GenericContainer;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.testcontainers.containers.wait.strategy.Wait;7import org.slf4j.Logger;8import org.slf4j.LoggerFactory;9import org.testcontainers.utility.MountableFile;10public class Test {11 public static void main(String[] args) {12 Logger logger = LoggerFactory.getLogger(Test.class);13 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();14 strategy.getClient();15 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:3.13.5"))16 .withExposedPorts(80)17 .withLogConsumer(new Slf4jLogConsumer(logger))18 .waitingFor(Wait.forLogMessage(".*", 1));19 container.start();20 System.out.println("Container started");21 container.stop();22 }23}

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.dockerclient.DockerClientProviderStrategy;2import org.testcontainers.DockerClientFactory;3import org.testcontainers.utility.DockerImageName;4import org.testcontainers.containers.GenericContainer;5import org.testcontainers.containers.output.Slf4jLogConsumer;6import org.slf4j.Logger;7import org.slf4j.LoggerFactory;8public class 1 {9 public static void main(String[] args) throws InterruptedException {10 Logger logger = LoggerFactory.getLogger(1.class);11 DockerClientProviderStrategy dockerClientProviderStrategy = new DockerClientProviderStrategy();12 DockerClientFactory dockerClientFactory = new DockerClientFactory();13 DockerImageName dockerImageName = new DockerImageName("alpine:3.14");14 GenericContainer genericContainer = new GenericContainer(dockerImageName);15 genericContainer.withCommand("sh", "-c", "while true; do echo 'Hello'; sleep 1; done");16 genericContainer.withLogConsumer(new Slf4jLogConsumer(logger));17 genericContainer.start();18 System.out.println("Container ID: " + genericContainer.get

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientProviderStrategy;2import org.testcontainers.utility.DockerMachineClientProviderStrategy;3import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineDetails;4import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineNotFoundException;5import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineReadableException;6import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineRunningException;7import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineStoppedException;8import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineUnavailableException;9import org.testcontainers.utility.DockerMachineClientProviderStrategy.MachineVersionException;10import org.testcontainers.utility.DockerMachineClientProviderStrategy.MalformedMachineException;11import org.testcontainers.utility.DockerMachineClientProviderStrategy.MalformedMachineNameException;12import org.testcontainers.utility.DockerMachineClientProviderStrategy.MalformedMachineUrlException;13import org.testcontainers.utility.DockerMachineClientProviderStrategy.MalformedMachineVersionException;14import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnexpectedDockerConfigException;15import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnexpectedDockerInfoException;16import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnexpectedMachineStateException;17import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnexpectedResponseException;18import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnexpectedVersionException;19import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnknownDockerHostException;20import org.testcontainers.utility.DockerMachineClientProviderStrategy.UnknownProviderException;21import org.testcontainers.utility.DockerMachineClientProviderStrategy.WrongMachineNameException;22import org.testcontainers.utility.DockerMachineClientProviderStrategy.WrongMachineSshKeyException;23import org.testcontainers.utility.DockerMachineClientProviderStrategy.WrongMachineSshUserException;24import com.github.dockerjava.api.DockerClient;25import com.github.dockerjava.api.model.Version;26public class TestDockerClientProviderStrategy {27 public static void main(String[] args) throws Exception {28 DockerMachineClientProviderStrategy dockerMachineClientProviderStrategy = new DockerMachineClientProviderStrategy();29 DockerClient dockerClient = dockerMachineClientProviderStrategy.getDockerClient();30 System.out.println("Docker client version: " + dockerClient.versionCmd().exec().getVersion());31 }32}33import org.test

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientFactory;2import org.testcontainers.dockerclient.DockerClientProviderStrategy;3import org.testcontainers.utility.DockerImageName;4import org.testcontainers.containers.GenericContainer;5import java.io.IOException;6public class TestContainer {7 public static void main(String[] args) throws IOException {8 DockerClientProviderStrategy dockerClientProviderStrategy = DockerClientFactory.instance().clientProviderStrategy;9 DockerImageName dockerImageName = DockerImageName.parse("postgres:9.6.8");10 GenericContainer genericContainer = new GenericContainer(dockerImageName);11 genericContainer.start();12 String containerId = genericContainer.getContainerId();13 String containerIp = genericContainer.getContainerIpAddress();14 Integer containerPort = genericContainer.getMappedPort(5432);15 System.out.println("Container ID: "+contai

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientProviderStrategy;2public class TestContainer {3 public static void main(String[] args) {4 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();5 System.out.println(strategy.getDockerHostIpAddress());6 }7}

Full Screen

Full Screen

DockerClientProviderStrategy

Using AI Code Generation

copy

Full Screen

1package org.testcontainers.dockerclient;2import java.io.IOException;3import org.testcontainers.DockerClientFactory;4import org.testcontainers.dockerclient.transport.okhttp.OkHttpDockerCmdExecFactory;5import org.testcontainers.utility.DockerMachineClient;6import org.testcontainers.utility.MountableFile;7import com.github.dockerjava.api.DockerClient;8import com.github.dockerjava.api.command.CreateContainerCmd;9import com.github.dockerjava.api.command.CreateContainerResponse;10import com.github.dockerjava.api.model.Bind;11import com.github.dockerjava.api.model.ExposedPort;12import com.github.dockerjava.api.model.HostConfig;13import com.github.dockerjava.api.model.Ports;14import com.github.dockerjava.api.model.Volume;15import com.github.dockerjava.core.DockerClientBuilder;16import com.github.dockerjava.core.command.PullImageResultCallback;17import com.github.dockerjava.core.command.PushImageResultCallback;18import com.github.dockerjava.core.command.WaitContainerResultCallback;19import com.github.dockerjava.jaxrs.JerseyDockerCmdExecFactory;20public class DockerClientProviderStrategy {21 public static void main(String[] args) throws IOException, InterruptedException {22 DockerClient dockerClient = DockerClientFactory.instance().client();23 String image = "alpine";24 dockerClient.pullImageCmd(image).exec(new PullImageResultCallback()).awaitSuccess();25 CreateContainerResponse container = dockerClient.createContainerCmd(image).withCmd("echo", "hello world")26 .exec();27 dockerClient.startContainerCmd(container.getId()).exec();28 dockerClient.waitContainerCmd(container.getId()).exec(new WaitContainerResultCallback()).awaitStatusCode();29 System.out.println(dockerClient.logContainerCmd(container.getId()).exec());30 dockerClient.removeContainerCmd(container.getId()).exec();31 }32}33package org.testcontainers.dockerclient;34import java.io.IOException;35import org.testcontainers.DockerClientFactory;36import org.testcontainers.dockerclient.transport.okhttp.OkHttpDockerCmdExecFactory;37import org.testcontainers.utility.DockerMachineClient;38import org.testcontainers.utility.MountableFile;39import com.github.dockerjava.api.DockerClient;40import com.github.dockerjava.api.command.CreateContainerCmd;41import com.github.dockerjava.api.command.CreateContainerResponse;42import com.github.dockerjava.api.model.Bind;43import com.github.dockerjava.api.model.ExposedPort;44import com.github.dockerjava.api.model.HostConfig;45import com.github.dockerjava.api

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful