How to use getOrInitializeStrategy method of org.testcontainers.DockerClientFactory class

Best Testcontainers-java code snippet using org.testcontainers.DockerClientFactory.getOrInitializeStrategy

Source:DockerClientFactory.java Github

copy

Full Screen

...97 return false;98 }99 }100 @Synchronized101 private DockerClientProviderStrategy getOrInitializeStrategy() {102 if (strategy != null) {103 return strategy;104 }105 List<DockerClientProviderStrategy> configurationStrategies = new ArrayList<>();106 ServiceLoader.load(DockerClientProviderStrategy.class).forEach(configurationStrategies::add);107 strategy = DockerClientProviderStrategy.getFirstValidStrategy(configurationStrategies);108 return strategy;109 }110 @UnstableAPI111 public TransportConfig getTransportConfig() {112 return getOrInitializeStrategy().getTransportConfig();113 }114 @UnstableAPI115 public String getRemoteDockerUnixSocketPath() {116 String dockerSocketOverride = System.getenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE");117 if (!StringUtils.isBlank(dockerSocketOverride)) {118 return dockerSocketOverride;119 }120 URI dockerHost = getTransportConfig().getDockerHost();121 String path = "unix".equals(dockerHost.getScheme())122 ? dockerHost.getRawPath()123 : "/var/run/docker.sock";124 return SystemUtils.IS_OS_WINDOWS125 ? "/" + path126 : path;127 }128 /**129 *130 * @return a new initialized Docker client131 */132 @Synchronized133 public DockerClient client() {134 if (dockerClient != null) {135 return dockerClient;136 }137 // fail-fast if checks have failed previously138 if (cachedClientFailure != null) {139 log.debug("There is a cached checks failure - throwing", cachedClientFailure);140 throw cachedClientFailure;141 }142 final DockerClientProviderStrategy strategy = getOrInitializeStrategy();143 log.info("Docker host IP address is {}", strategy.getDockerHostIpAddress());144 final DockerClient client = new DockerClientDelegate() {145 @Getter146 final DockerClient dockerClient = strategy.getDockerClient();147 @Override148 public void close() {149 throw new IllegalStateException("You should never close the global DockerClient!");150 }151 };152 Info dockerInfo = client.infoCmd().exec();153 Version version = client.versionCmd().exec();154 activeApiVersion = version.getApiVersion();155 activeExecutionDriver = dockerInfo.getExecutionDriver();156 log.info("Connected to docker: \n" +157 " Server Version: " + dockerInfo.getServerVersion() + "\n" +158 " API Version: " + activeApiVersion + "\n" +159 " Operating System: " + dockerInfo.getOperatingSystem() + "\n" +160 " Total Memory: " + dockerInfo.getMemTotal() / (1024 * 1024) + " MB");161 final String ryukContainerId;162 boolean useRyuk = !Boolean.parseBoolean(System.getenv("TESTCONTAINERS_RYUK_DISABLED"));163 if (useRyuk) {164 log.debug("Ryuk is enabled");165 try {166 //noinspection deprecation167 ryukContainerId = ResourceReaper.start(client);168 } catch (RuntimeException e) {169 cachedClientFailure = e;170 throw e;171 }172 log.info("Ryuk started - will monitor and terminate Testcontainers containers on JVM exit");173 } else {174 log.debug("Ryuk is disabled");175 ryukContainerId = null;176 }177 boolean checksEnabled = !TestcontainersConfiguration.getInstance().isDisableChecks();178 if (checksEnabled) {179 log.debug("Checks are enabled");180 try {181 log.info("Checking the system...");182 checkDockerVersion(version.getVersion());183 if (ryukContainerId != null) {184 checkDiskSpace(client, ryukContainerId);185 } else {186 runInsideDocker(187 client,188 createContainerCmd -> {189 createContainerCmd.withName("testcontainers-checks-" + SESSION_ID);190 createContainerCmd.getHostConfig().withAutoRemove(true);191 createContainerCmd.withCmd("tail", "-f", "/dev/null");192 },193 (__, containerId) -> {194 checkDiskSpace(client, containerId);195 return "";196 }197 );198 }199 } catch (RuntimeException e) {200 cachedClientFailure = e;201 throw e;202 }203 } else {204 log.debug("Checks are disabled");205 }206 dockerClient = client;207 return dockerClient;208 }209 private void checkDockerVersion(String dockerVersion) {210 boolean versionIsSufficient = new ComparableVersion(dockerVersion).compareTo(new ComparableVersion("1.6.0")) >= 0;211 check("Docker server version should be at least 1.6.0", versionIsSufficient);212 }213 private void checkDiskSpace(DockerClient dockerClient, String id) {214 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();215 try {216 dockerClient217 .execStartCmd(dockerClient.execCreateCmd(id).withAttachStdout(true).withCmd("df", "-P").exec().getId())218 .exec(new ResultCallback.Adapter<Frame>() {219 @Override220 public void onNext(Frame frame) {221 if (frame == null) {222 return;223 }224 switch (frame.getStreamType()) {225 case RAW:226 case STDOUT:227 try {228 outputStream.write(frame.getPayload());229 outputStream.flush();230 } catch (IOException e) {231 onError(e);232 }233 }234 }235 })236 .awaitCompletion();237 } catch (Exception e) {238 log.debug("Can't exec disk checking command", e);239 }240 DiskSpaceUsage df = parseAvailableDiskSpace(outputStream.toString());241 check(242 "Docker environment should have more than 2GB free disk space",243 df.availableMB.map(it -> it >= 2048).orElse(true)244 );245 }246 private void check(String message, boolean isSuccessful) {247 if (isSuccessful) {248 log.info("\u2714\ufe0e {}", message);249 } else {250 log.error("\u274c {}", message);251 throw new IllegalStateException("Check failed: " + message);252 }253 }254 private boolean checkMountableFile() {255 DockerClient dockerClient = client();256 MountableFile mountableFile = MountableFile.forClasspathResource(ResourceReaper.class.getName().replace(".", "/") + ".class");257 Volume volume = new Volume("/dummy");258 try {259 return runInsideDocker(260 createContainerCmd -> createContainerCmd.withBinds(new Bind(mountableFile.getResolvedPath(), volume, AccessMode.ro)),261 (__, containerId) -> {262 try (InputStream stream = dockerClient.copyArchiveFromContainerCmd(containerId, volume.getPath()).exec()) {263 stream.read();264 return true;265 } catch (Exception e) {266 return false;267 }268 }269 );270 } catch (Exception e) {271 log.debug("Failure while checking for mountable file support", e);272 return false;273 }274 }275 /**276 * Check whether the image is available locally and pull it otherwise277 */278 @SneakyThrows279 public void checkAndPullImage(DockerClient client, String image) {280 try {281 client.inspectImageCmd(image).exec();282 } catch (NotFoundException notFoundException) {283 PullImageCmd pullImageCmd = client.pullImageCmd(image);284 try {285 pullImageCmd.exec(new TimeLimitedLoggedPullImageResultCallback(log)).awaitCompletion();286 } catch (DockerClientException e) {287 // Try to fallback to x86288 pullImageCmd289 .withPlatform("linux/amd64")290 .exec(new TimeLimitedLoggedPullImageResultCallback(log))291 .awaitCompletion();292 }293 }294 }295 /**296 * @return the IP address of the host running Docker297 */298 public String dockerHostIpAddress() {299 return getOrInitializeStrategy().getDockerHostIpAddress();300 }301 public <T> T runInsideDocker(Consumer<CreateContainerCmd> createContainerCmdConsumer, BiFunction<DockerClient, String, T> block) {302 // We can't use client() here because it might create an infinite loop303 return runInsideDocker(getOrInitializeStrategy().getDockerClient(), createContainerCmdConsumer, block);304 }305 private <T> T runInsideDocker(DockerClient client, Consumer<CreateContainerCmd> createContainerCmdConsumer, BiFunction<DockerClient, String, T> block) {306 final String tinyImage = ImageNameSubstitutor.instance().apply(TINY_IMAGE).asCanonicalNameString();307 checkAndPullImage(client, tinyImage);308 CreateContainerCmd createContainerCmd = client.createContainerCmd(tinyImage)309 .withLabels(DEFAULT_LABELS);310 createContainerCmdConsumer.accept(createContainerCmd);311 String id = createContainerCmd.exec().getId();312 try {313 client.startContainerCmd(id).exec();314 return block.apply(client, id);315 } finally {316 try {317 client.removeContainerCmd(id).withRemoveVolumes(true).withForce(true).exec();...

Full Screen

Full Screen

getOrInitializeStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientFactory;2import org.testcontainers.containers.GenericContainer;3import org.testcontainers.utility.DockerImageName;4public class TestContainerDemo {5 public static void main(String[] args) {6 GenericContainer container = new GenericContainer(DockerImageName.parse("alpine:3.12.0"))7 .withCommand("sh", "-c", "while true; do sleep 1; done");8 container.start();9 System.out.println("Container ID: " + container.getContainerId());10 System.out.println("Container Hostname: " + container.getContainerInfo().getConfig().getHostname());11 System.out.println("Container Hostname: " + conta

Full Screen

Full Screen

getOrInitializeStrategy

Using AI Code Generation

copy

Full Screen

1DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();2String dockerHostIpAddress = strategy.getDockerHostIpAddress();3getDockerHostIpAddress()4DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();5String dockerHostIpAddress = strategy.getDockerHostIpAddress();6getDockerHostIpAddress()7DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();8String dockerHostIpAddress = strategy.getDockerHostIpAddress();9getDockerHostIpAddress()10DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();11String dockerHostIpAddress = strategy.getDockerHostIpAddress();12getDockerHostIpAddress()13DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();14String dockerHostIpAddress = strategy.getDockerHostIpAddress();15getDockerHostIpAddress()16DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();17String dockerHostIpAddress = strategy.getDockerHostIpAddress();18getDockerHostIpAddress()19DockerClientStrategy strategy = DockerClientFactory.instance().getOrInitializeStrategy();20String dockerHostIpAddress = strategy.getDockerHostIpAddress();21getDockerHostIpAddress()

Full Screen

Full Screen

getOrInitializeStrategy

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.DockerClientFactory;2import org.testcontainers.utility.DockerImageName;3import org.testcontainers.utility.ResourceReaper;4DockerImageName imageName = DockerImageName.parse("alpine:3.12.0");5DockerClientFactory.instance().getOrInitializeStrategy(imageName);6import org.testcontainers.DockerClientFactory;7import org.testcontainers.utility.DockerImageName;8import org.testcontainers.utility.ResourceReaper;9DockerImageName imageName = DockerImageName.parse("alpine:3.12.0");10DockerClientFactory.instance().getOrInitializeStrategy(imageName);11import org.testcontainers.DockerClientFactory;12import org.testcontainers.utility.DockerImageName;13import org.testcontainers.utility.ResourceReaper;14DockerImageName imageName = DockerImageName.parse("alpine:3.12.0");15DockerClientFactory.instance().getOrInitializeStrategy(imageName);16import org.testcontainers.DockerClientFactory;17import org.testcontainers.utility.DockerImageName;18import org.testcontainers.utility.ResourceReaper;19DockerImageName imageName = DockerImageName.parse("alpine:3.12.0");20DockerClientFactory.instance().getOrInitializeStrategy(imageName);21import org.testcontainers.DockerClientFactory;22import org.testcontainers.utility.DockerImageName;23import org.testcontainers.utility.ResourceReaper;24DockerImageName imageName = DockerImageName.parse("alpine:3.12.0");25DockerClientFactory.instance().getOrInitializeStrategy(imageName);26import org.testcontainers.DockerClientFactory;27import org.testcontainers.utility.DockerImageName;28import org.testcontainers.utility.ResourceReaper;

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful