How to use getTransportConfig method of org.testcontainers.dockerclient.DockerClientProviderStrategy class

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

Source:DockerClientProviderStrategy.java Github

copy

Full Screen

...38 */39@Slf4j40public abstract class DockerClientProviderStrategy {41 @Getter(lazy = true)42 private final DockerClient dockerClient = getClientForConfig(getTransportConfig());43 private String dockerHostIpAddress;44 private final RateLimiter PING_RATE_LIMITER = RateLimiterBuilder.newBuilder()45 .withRate(10, TimeUnit.SECONDS)46 .withConstantThroughput()47 .build();48 private static final AtomicBoolean FAIL_FAST_ALWAYS = new AtomicBoolean(false);49 /**50 * @return a short textual description of the strategy51 */52 public abstract String getDescription();53 protected boolean isApplicable() {54 return true;55 }56 protected boolean isPersistable() {57 return true;58 }59 /**60 * @return highest to lowest priority value61 */62 protected int getPriority() {63 return 0;64 }65 /**66 * @throws InvalidConfigurationException if this strategy fails67 */68 public abstract TransportConfig getTransportConfig() throws InvalidConfigurationException;69 /**70 * @return a usable, tested, Docker client configuration for the host system environment71 *72 * @deprecated use {@link #getDockerClient()}73 */74 @Deprecated75 public DockerClient getClient() {76 DockerClient dockerClient = getDockerClient();77 try {78 Unreliables.retryUntilSuccess(30, TimeUnit.SECONDS, () -> {79 return PING_RATE_LIMITER.getWhenReady(() -> {80 log.debug("Pinging docker daemon...");81 dockerClient.pingCmd().exec();82 log.debug("Pinged");83 return true;84 });85 });86 } catch (TimeoutException e) {87 IOUtils.closeQuietly(dockerClient);88 throw e;89 }90 return dockerClient;91 }92 /**93 * Determine the right DockerClientConfig to use for building clients by trial-and-error.94 *95 * @return a working DockerClientConfig, as determined by successful execution of a ping command96 */97 public static DockerClientProviderStrategy getFirstValidStrategy(List<DockerClientProviderStrategy> strategies) {98 if (FAIL_FAST_ALWAYS.get()) {99 throw new IllegalStateException("Previous attempts to find a Docker environment failed. Will not retry. Please see logs and check configuration");100 }101 List<String> configurationFailures = new ArrayList<>();102 List<DockerClientProviderStrategy> allStrategies = new ArrayList<>();103 // The environment has the highest priority104 allStrategies.add(new EnvironmentAndSystemPropertyClientProviderStrategy());105 // Next strategy to try out is the one configured using the Testcontainers configuration mechanism106 loadConfiguredStrategy().ifPresent(allStrategies::add);107 // Finally, add all other strategies ordered by their internal priority108 strategies109 .stream()110 .sorted(Comparator.comparing(DockerClientProviderStrategy::getPriority).reversed())111 .collect(Collectors.toCollection(() -> allStrategies));112 Predicate<DockerClientProviderStrategy> distinctStrategyClassPredicate = new Predicate<DockerClientProviderStrategy>() {113 final Set<Class<? extends DockerClientProviderStrategy>> classes = new HashSet<>();114 @Override115 public boolean test(DockerClientProviderStrategy dockerClientProviderStrategy) {116 return classes.add(dockerClientProviderStrategy.getClass());117 }118 };119 return allStrategies120 .stream()121 .filter(distinctStrategyClassPredicate)122 .filter(DockerClientProviderStrategy::isApplicable)123 .filter(strategy -> tryOutStrategy(configurationFailures, strategy))124 .findFirst()125 .orElseThrow(() -> {126 log.error("Could not find a valid Docker environment. Please check configuration. Attempted configurations were:");127 for (String failureMessage : configurationFailures) {128 log.error(" " + failureMessage);129 }130 log.error("As no valid configuration was found, execution cannot continue");131 FAIL_FAST_ALWAYS.set(true);132 return new IllegalStateException("Could not find a valid Docker environment. Please see logs and check configuration");133 });134 }135 private static boolean tryOutStrategy(List<String> configurationFailures, DockerClientProviderStrategy strategy) {136 try {137 log.debug("Trying out strategy: {}", strategy.getClass().getSimpleName());138 DockerClient dockerClient = strategy.getDockerClient();139 Info info;140 try {141 info = Unreliables.retryUntilSuccess(TestcontainersConfiguration.getInstance().getClientPingTimeout(), TimeUnit.SECONDS, () -> {142 return strategy.PING_RATE_LIMITER.getWhenReady(() -> {143 log.debug("Pinging docker daemon...");144 return dockerClient.infoCmd().exec();145 });146 });147 } catch (TimeoutException e) {148 IOUtils.closeQuietly(dockerClient);149 throw e;150 }151 log.info("Found Docker environment with {}", strategy.getDescription());152 log.debug(153 "Transport type: '{}', Docker host: '{}'",154 TestcontainersConfiguration.getInstance().getTransportType(),155 strategy.getTransportConfig().getDockerHost()156 );157 log.debug("Checking Docker OS type for {}", strategy.getDescription());158 String osType = info.getOsType();159 if (StringUtils.isBlank(osType)) {160 log.warn("Could not determine Docker OS type");161 } else if (!osType.equals("linux")) {162 log.warn("{} is currently not supported", osType);163 throw new InvalidConfigurationException(osType + " containers are currently not supported");164 }165 if (strategy.isPersistable()) {166 TestcontainersConfiguration.getInstance().updateUserConfig("docker.client.strategy", strategy.getClass().getName());167 }168 return true;169 } catch (Exception | ExceptionInInitializerError | NoClassDefFoundError e) {170 @Nullable String throwableMessage = e.getMessage();171 @SuppressWarnings("ThrowableResultOfMethodCallIgnored")172 Throwable rootCause = Throwables.getRootCause(e);173 @Nullable String rootCauseMessage = rootCause.getMessage();174 String failureDescription;175 if (throwableMessage != null && throwableMessage.equals(rootCauseMessage)) {176 failureDescription = String.format("%s: failed with exception %s (%s)",177 strategy.getClass().getSimpleName(),178 e.getClass().getSimpleName(),179 throwableMessage);180 } else {181 failureDescription = String.format("%s: failed with exception %s (%s). Root cause %s (%s)",182 strategy.getClass().getSimpleName(),183 e.getClass().getSimpleName(),184 throwableMessage,185 rootCause.getClass().getSimpleName(),186 rootCauseMessage187 );188 }189 configurationFailures.add(failureDescription);190 log.debug(failureDescription);191 return false;192 }193 }194 private static Optional<? extends DockerClientProviderStrategy> loadConfiguredStrategy() {195 String configuredDockerClientStrategyClassName = TestcontainersConfiguration.getInstance().getDockerClientStrategyClassName();196 return Stream197 .of(configuredDockerClientStrategyClassName)198 .filter(Objects::nonNull)199 .flatMap(it -> {200 try {201 Class<? extends DockerClientProviderStrategy> strategyClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(it);202 return Stream.of(strategyClass.newInstance());203 } catch (ClassNotFoundException e) {204 log.warn("Can't instantiate a strategy from {} (ClassNotFoundException). " +205 "This probably means that cached configuration refers to a client provider " +206 "class that is not available in this version of Testcontainers. Other " +207 "strategies will be tried instead.", it);208 return Stream.empty();209 } catch (InstantiationException | IllegalAccessException e) {210 log.warn("Can't instantiate a strategy from {}", it, e);211 return Stream.empty();212 }213 })214 // Ignore persisted strategy if it's not persistable anymore215 .filter(DockerClientProviderStrategy::isPersistable)216 .peek(strategy -> log.info("Loaded {} from ~/.testcontainers.properties, will try it first", strategy.getClass().getName()))217 .findFirst();218 }219 public static DockerClient getClientForConfig(TransportConfig transportConfig) {220 final DockerHttpClient dockerHttpClient;221 String transportType = TestcontainersConfiguration.getInstance().getTransportType();222 switch (transportType) {223 case "okhttp":224 dockerHttpClient = new OkDockerHttpClient.Builder()225 .dockerHost(transportConfig.getDockerHost())226 .sslConfig(transportConfig.getSslConfig())227 .build();228 break;229 case "httpclient5":230 dockerHttpClient = new ZerodepDockerHttpClient.Builder()231 .dockerHost(transportConfig.getDockerHost())232 .sslConfig(transportConfig.getSslConfig())233 .build();234 break;235 default:236 throw new IllegalArgumentException("Unknown transport type '" + transportType + "'");237 }238 DefaultDockerClientConfig.Builder configBuilder = DefaultDockerClientConfig.createDefaultConfigBuilder();239 if (configBuilder.build().getApiVersion() == RemoteApiVersion.UNKNOWN_VERSION) {240 configBuilder.withApiVersion(RemoteApiVersion.VERSION_1_32);241 }242 return DockerClientImpl.getInstance(243 new AuthDelegatingDockerClientConfig(244 configBuilder245 .withDockerHost(transportConfig.getDockerHost().toString())246 .build()247 ),248 dockerHttpClient249 );250 }251 public synchronized String getDockerHostIpAddress() {252 if (dockerHostIpAddress == null) {253 dockerHostIpAddress = resolveDockerHostIpAddress(getDockerClient(), getTransportConfig().getDockerHost());254 }255 return dockerHostIpAddress;256 }257 @VisibleForTesting258 static String resolveDockerHostIpAddress(DockerClient client, URI dockerHost) {259 String hostOverride = System.getenv("TESTCONTAINERS_HOST_OVERRIDE");260 if (!StringUtils.isBlank(hostOverride)) {261 return hostOverride;262 }263 switch (dockerHost.getScheme()) {264 case "http":265 case "https":266 case "tcp":267 return dockerHost.getHost();...

Full Screen

Full Screen

getTransportConfig

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientFactory;2import org.testcontainers.dockerclient.DockerClientConfigUtils;3import org.testcontainers.dockerclient.DockerClientProviderStrategy;4import org.testcontainers.utility.Base58;5import java.io.IOException;6import java.util.Optional;7public class DockerClientProviderStrategyTest {8 public static void main(String[] args) throws IOException {9 String dockerHost = System.getenv("DOCKER_HOST");10 String dockerCertPath = System.getenv("DOCKER_CERT_PATH");11 String dockerConfig = System.getenv("DOCKER_CONFIG");12 String dockerMachineName = System.getenv("DOCKER_MACHINE_NAME");13 String dockerConfigPath = System.getenv("DOCKER_CONFIG_PATH");14 String dockerTlsVerify = System.getenv("DOCKER_TLS_VERIFY");15 String dockerApiVersion = System.getenv("DOCKER_API_VERSION");16 String dockerHostFromEnv = DockerClientConfigUtils.getDockerHostIpAddress();17 String dockerCertPathFromEnv = DockerClientConfigUtils.getDockerCertPath();18 String dockerConfigFromEnv = DockerClientConfigUtils.getDockerConfig();19 String dockerMachineNameFromEnv = DockerClientConfigUtils.getDockerMachineName();20 String dockerConfigPathFromEnv = DockerClientConfigUtils.getDockerConfigPath();21 String dockerTlsVerifyFromEnv = DockerClientConfigUtils.getDockerTlsVerify();22 String dockerApiVersionFromEnv = DockerClientConfigUtils.getDockerApiVersion();23 System.out.println("DOCKER_HOST: " + dockerHost);24 System.out.println("DOCKER_CERT_PATH: " + dockerCertPath);25 System.out.println("DOCKER_CONFIG: " + dockerConfig);26 System.out.println("DOCKER_MACHINE_NAME: " + dockerMachineName);27 System.out.println("DOCKER_CONFIG_PATH: " + dockerConfigPath);28 System.out.println("DOCKER_TLS_VERIFY: " + dockerTlsVerify);29 System.out.println("DOCKER_API_VERSION: " + dockerApiVersion);30 System.out.println("DOCKER_HOST from env: " + dockerHostFromEnv);31 System.out.println("DOCKER_CERT_PATH from env: " + dockerCertPathFromEnv);32 System.out.println("DOCKER_CONFIG from env: " + dockerConfigFromEnv);33 System.out.println("DOCKER_MACHINE_NAME from env: " + dockerMachineNameFromEnv);34 System.out.println("DOCKER_CONFIG_PATH from env: " + dockerConfigPathFromEnv);35 System.out.println("DOCKER_TLS_VERIFY from env: " + dockerTlsVerifyFromEnv);36 System.out.println("DOCKER_API_VERSION

Full Screen

Full Screen

getTransportConfig

Using AI Code Generation

copy

Full Screen

1DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();2DockerClientConfig config = strategy.getTransportConfig();3String ipAddress = strategy.getDockerHostIpAddress();4package org.kodejava.example.docker;5import com.github.dockerjava.api.DockerClient;6import com.github.dockerjava.api.command.CreateContainerResponse;7import com.github.dockerjava.api.model.Bind;8import com.github.dockerjava.api.model.ExposedPort;9import com.github.dockerjava.api.model.Ports;10import com.github.dockerjava.core.DockerClientBuilder;11import com.github.dockerjava.core.DockerClientConfig;12import org.testcontainers.DockerClientFactory;13import org.testcontainers.dockerclient.DockerClientProviderStrategy;14import java.io.File;15public class DockerClientProviderStrategyDemo {16 public static void main(String[] args) {17 new DockerClientProviderStrategy();18 DockerClientConfig config = strategy.getTransportConfig();19 DockerClient client = DockerClientBuilder.getInstance(config)20 .build();21 CreateContainerResponse container = client.createContainerCmd("busybox")22 .withName("test-container")23 .withCmd("sh", "-c", "while true; do sleep 1; done")24 .exec();25 client.startContainerCmd(container.getId()).exec();26 String ipAddress = strategy.getDockerHostIpAddress();27 ExposedPort tcp80 = ExposedPort.tcp(80);28 Ports portBindings = new Ports();29 portBindings.bind(tcp80, Ports.Binding.bindPort(8080));30 ExposedPort tcp443 = ExposedPort.tcp(443);31 portBindings.bind(tcp

Full Screen

Full Screen

getTransportConfig

Using AI Code Generation

copy

Full Screen

1public void getTransportConfig() {2 DockerClientConfig dockerClientConfig = new DockerClientConfigBuilder()3 .withDockerTlsVerify(false)4 .withDockerCertPath("/home/user/.docker")5 .withDockerConfig("/home/user/.docker")6 .withApiVersion("1.35")7 .withRegistryUsername("user")8 .withRegistryPassword("pass")9 .withRegistryEmail("

Full Screen

Full Screen

getTransportConfig

Using AI Code Generation

copy

Full Screen

1public void testGetTransportConfig() throws IOException {2 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();3 TransportConfig transportConfig = strategy.getTransportConfig();4}5public void testGetDockerHostIpAddress() throws IOException {6 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();7 String dockerHostIpAddress = strategy.getDockerHostIpAddress();8}9public void testGetDockerHostIpAddress() throws IOException {10 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();11 String dockerHostIpAddress = strategy.getDockerHostIpAddress();12}13public void testGetDockerHostIpAddress() throws IOException {14 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();15 String dockerHostIpAddress = strategy.getDockerHostIpAddress();16}17public void testGetDockerHostIpAddress() throws IOException {18 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();19 String dockerHostIpAddress = strategy.getDockerHostIpAddress();20}21public void testGetDockerHostIpAddress() throws IOException {22 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();23 String dockerHostIpAddress = strategy.getDockerHostIpAddress();24}25public void testGetDockerHostIpAddress() throws IOException {26 DockerClientProviderStrategy strategy = new DockerClientProviderStrategy();27 String dockerHostIpAddress = strategy.getDockerHostIpAddress();28}29public void testGetDockerHostIpAddress() throws IOException {

Full Screen

Full Screen

getTransportConfig

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientFactory2import org.testcontainers.dockerclient.DockerClientProviderStrategy3import org.testcontainers.utility.DockerImageName4import com.github.dockerjava.api.DockerClient5import com.github.dockerjava.api.command.InspectContainerResponse6import com.github.dockerjava.api.model.Bind7import com.github.dockerjava.api.model.Capability8import com.github.dockerjava.api.model.ExposedPort9import com.github.dockerjava.api.model.HostConfig10import com.github.dockerjava.api.model.Ports11import com.github.dockerjava.api.model.Volume12import com.github.dockerjava.core.DefaultDockerClientConfig13import com.github.dockerjava.core.DockerClientConfig14import com.github.dockerjava.core.DockerClientImpl15import com.github.dockerjava.core.command.PullImageResultCallback16import com.github.dockerjava.transport.DockerHttpClient17import com.github.dockerjava.transport.DockerHttpClientBuilder18import com.github.dockerjava.transport.DockerHttpClientConfig19import java.io.File

Full Screen

Full Screen

getTransportConfig

Using AI Code Generation

copy

Full Screen

1 public DockerClientConfig getTransportConfig() {2 return transportConfig;3 }4}5@ExtendWith(RepeaterExtension.class)6public class TestContainersTest {7 @Repetition(repetitions = 100)8 void testContainers() throws IOException {9 DockerClientConfig config = new DockerClientConfigUtils().getTransportConfig();10 DockerClient client = DockerClientFactory.instance().client();11 List<Container> containers = client.listContainersCmd().exec();12 System.out.println("Containers count: " + containers.size());13 }14}15org.testcontainers.shaded.com.github.dockerjava.api.exception.DockerClientException: Could not pull image: failed to register layer: Error processing tar file(exit status 1): operation not permitted

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful