Search in sources :

Example 6 with Image

use of com.github.dockerjava.api.model.Image in project testcontainers-java by testcontainers.

the class RemoteDockerImage method resolve.

@Override
protected final String resolve() {
    Profiler profiler = new Profiler("Rule creation - prefetch image");
    Logger logger = DockerLoggerFactory.getLogger(imageName.toString());
    profiler.setLogger(logger);
    Profiler nested = profiler.startNested("Obtaining client");
    DockerClient dockerClient = DockerClientFactory.instance().client();
    try {
        nested.stop();
        profiler.start("Check local images");
        int attempts = 0;
        DockerClientException lastException = null;
        while (true) {
            // Does our cache already know the image?
            if (AVAILABLE_IMAGE_NAME_CACHE.contains(imageName)) {
                logger.trace("{} is already in image name cache", imageName);
                break;
            }
            // Update the cache
            ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
            if (Boolean.parseBoolean(System.getProperty("useFilter"))) {
                listImagesCmd = listImagesCmd.withImageNameFilter(imageName.toString());
            }
            List<Image> updatedImages = listImagesCmd.exec();
            updatedImages.stream().map(Image::getRepoTags).filter(Objects::nonNull).flatMap(Stream::of).map(DockerImageName::new).collect(Collectors.toCollection(() -> AVAILABLE_IMAGE_NAME_CACHE));
            // And now?
            if (AVAILABLE_IMAGE_NAME_CACHE.contains(imageName)) {
                logger.trace("{} is in image name cache following listing of images", imageName);
                break;
            }
            // Log only on first attempt
            if (attempts == 0) {
                logger.info("Pulling docker image: {}. Please be patient; this may take some time but only needs to be done once.", imageName);
                profiler.start("Pull image");
            }
            if (attempts++ >= 3) {
                logger.error("Retry limit reached while trying to pull image: {}. Please check output of `docker pull {}`", imageName, imageName);
                throw new ContainerFetchException("Retry limit reached while trying to pull image: " + imageName, lastException);
            }
            // The image is not available locally - pull it
            try {
                final PullImageResultCallback callback = new PullImageResultCallback();
                dockerClient.pullImageCmd(imageName.getUnversionedPart()).withTag(imageName.getVersionPart()).exec(callback);
                callback.awaitSuccess();
                AVAILABLE_IMAGE_NAME_CACHE.add(imageName);
                break;
            } catch (DockerClientException e) {
                lastException = e;
            }
        }
        return imageName.toString();
    } catch (DockerClientException e) {
        throw new ContainerFetchException("Failed to get Docker client for " + imageName, e);
    } finally {
        profiler.stop().log();
    }
}
Also used : Profiler(org.slf4j.profiler.Profiler) DockerClient(com.github.dockerjava.api.DockerClient) DockerClientException(com.github.dockerjava.api.exception.DockerClientException) PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) ListImagesCmd(com.github.dockerjava.api.command.ListImagesCmd) Stream(java.util.stream.Stream) Logger(org.slf4j.Logger) Image(com.github.dockerjava.api.model.Image) ContainerFetchException(org.testcontainers.containers.ContainerFetchException)

Example 7 with Image

use of com.github.dockerjava.api.model.Image in project dockerunit by qzagarese.

the class DefaultServiceBuilder method createAndStartContainer.

private String createAndStartContainer(CreateContainerCmd cmd, PullStrategy pullStrategy, DockerClient client) {
    CompletableFuture<String> respFut = new CompletableFuture<>();
    ListImagesCmd imagesCmd = client.listImagesCmd().withImageNameFilter(cmd.getImage());
    List<Image> imagesList = imagesCmd.exec();
    boolean imageAbsent = imagesList == null || imagesList.size() == 0;
    CompletableFuture<Void> pullFut;
    if (imageAbsent || pullStrategy.equals(PullStrategy.ALWAYS)) {
        pullFut = pullImage(cmd, client);
    } else {
        pullFut = CompletableFuture.completedFuture(null);
    }
    pullFut.exceptionally(ex -> {
        logger.warning("An error occurred while executing a docker pull operation: " + ex.getMessage());
        return null;
    }).thenRun(() -> {
        String containerId = startContainer(cmd, client);
        respFut.complete(containerId);
    }).exceptionally(ex -> {
        respFut.completeExceptionally(ex.getCause());
        return null;
    });
    respFut.exceptionally(ex -> {
        logger.severe("Cannot create container. Reason: " + ex.getMessage());
        return null;
    });
    return respFut.join();
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) ListImagesCmd(com.github.dockerjava.api.command.ListImagesCmd) Image(com.github.dockerjava.api.model.Image)

Example 8 with Image

use of com.github.dockerjava.api.model.Image in project tutorials by eugenp.

the class ImageLiveTest method givenListOfImages_whenInspectImage_thenMustReturnObject.

@Test
public void givenListOfImages_whenInspectImage_thenMustReturnObject() {
    // given
    List<Image> images = dockerClient.listImagesCmd().exec();
    Image image = images.get(0);
    // when
    InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();
    // then
    assertThat(imageResponse.getId(), is(image.getId()));
}
Also used : InspectImageResponse(com.github.dockerjava.api.command.InspectImageResponse) Image(com.github.dockerjava.api.model.Image) Test(org.junit.Test)

Example 9 with Image

use of com.github.dockerjava.api.model.Image in project tutorials by eugenp.

the class ImageLiveTest method whenRemovingImage_thenImageListDecrease.

@Test
public void whenRemovingImage_thenImageListDecrease() {
    // when
    List<Image> images = dockerClient.listImagesCmd().exec();
    Image image = images.get(0);
    dockerClient.removeImageCmd(image.getId()).exec();
    // then
    List<Image> imagesNow = dockerClient.listImagesCmd().exec();
    assertThat(imagesNow.size(), is(lessThan(images.size())));
}
Also used : Image(com.github.dockerjava.api.model.Image) Test(org.junit.Test)

Example 10 with Image

use of com.github.dockerjava.api.model.Image in project vespa by vespa-engine.

the class DockerImpl method pullImageAsyncIfNeeded.

@Override
public boolean pullImageAsyncIfNeeded(final DockerImage image) {
    try {
        synchronized (monitor) {
            if (scheduledPulls.contains(image))
                return true;
            if (imageIsDownloaded(image))
                return false;
            scheduledPulls.add(image);
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image.asString());
            dockerRegistryCredentialsSupplier.flatMap(credentialsSupplier -> credentialsSupplier.getCredentials(image)).map(credentials -> new AuthConfig().withRegistryAddress(credentials.registry.toString()).withUsername(credentials.username).withPassword(credentials.password)).ifPresent(pullImageCmd::withAuthConfig);
            logger.log(LogLevel.INFO, "Starting download of " + image.asString());
            pullImageCmd.exec(new ImagePullCallback(image));
            return true;
        }
    } catch (RuntimeException e) {
        numberOfDockerDaemonFails.add();
        throw new DockerException("Failed to pull image '" + image.asString() + "'", e);
    }
}
Also used : Arrays(java.util.Arrays) NotModifiedException(com.github.dockerjava.api.exception.NotModifiedException) Dimensions(com.yahoo.vespa.hosted.dockerapi.metrics.Dimensions) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ExecStartResultCallback(com.github.dockerjava.core.command.ExecStartResultCallback) Inject(com.google.inject.Inject) HashMap(java.util.HashMap) ExecCreateCmdResponse(com.github.dockerjava.api.command.ExecCreateCmdResponse) DockerClientException(com.github.dockerjava.api.exception.DockerClientException) DockerClient(com.github.dockerjava.api.DockerClient) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) MetricReceiverWrapper(com.yahoo.vespa.hosted.dockerapi.metrics.MetricReceiverWrapper) ResultCallbackTemplate(com.github.dockerjava.core.async.ResultCallbackTemplate) DockerClientConfig(com.github.dockerjava.core.DockerClientConfig) DockerClientImpl(com.github.dockerjava.core.DockerClientImpl) NetworkAddressInterface(com.yahoo.vespa.hosted.dockerapi.DockerNetworkCreator.NetworkAddressInterface) Duration(java.time.Duration) Map(java.util.Map) LogLevel(com.yahoo.log.LogLevel) CounterWrapper(com.yahoo.vespa.hosted.dockerapi.metrics.CounterWrapper) InspectImageResponse(com.github.dockerjava.api.command.InspectImageResponse) DefaultDockerClientConfig(com.github.dockerjava.core.DefaultDockerClientConfig) PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) PullImageCmd(com.github.dockerjava.api.command.PullImageCmd) AuthConfig(com.github.dockerjava.api.model.AuthConfig) InspectExecResponse(com.github.dockerjava.api.command.InspectExecResponse) ExecStartCmd(com.github.dockerjava.api.command.ExecStartCmd) Set(java.util.Set) Statistics(com.github.dockerjava.api.model.Statistics) IOException(java.io.IOException) GuardedBy(javax.annotation.concurrent.GuardedBy) Logger(java.util.logging.Logger) InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) Collectors(java.util.stream.Collectors) Defaults.getDefaults(com.yahoo.vespa.defaults.Defaults.getDefaults) Image(com.github.dockerjava.api.model.Image) Network(com.github.dockerjava.api.model.Network) TimeUnit(java.util.concurrent.TimeUnit) Inet6Address(java.net.Inet6Address) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) InspectContainerCmd(com.github.dockerjava.api.command.InspectContainerCmd) JerseyDockerCmdExecFactory(com.github.dockerjava.jaxrs.JerseyDockerCmdExecFactory) Optional(java.util.Optional) Collections(java.util.Collections) PullImageCmd(com.github.dockerjava.api.command.PullImageCmd) AuthConfig(com.github.dockerjava.api.model.AuthConfig)

Aggregations

Image (com.github.dockerjava.api.model.Image)10 DockerClient (com.github.dockerjava.api.DockerClient)3 PullImageResultCallback (com.github.dockerjava.core.command.PullImageResultCallback)3 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 InspectImageResponse (com.github.dockerjava.api.command.InspectImageResponse)2 ListImagesCmd (com.github.dockerjava.api.command.ListImagesCmd)2 PullImageCmd (com.github.dockerjava.api.command.PullImageCmd)2 DockerClientException (com.github.dockerjava.api.exception.DockerClientException)2 NotFoundException (com.github.dockerjava.api.exception.NotFoundException)2 Stream (java.util.stream.Stream)2 HubIntegrationException (com.blackducksoftware.integration.hub.exception.HubIntegrationException)1 ExecCreateCmdResponse (com.github.dockerjava.api.command.ExecCreateCmdResponse)1 ExecStartCmd (com.github.dockerjava.api.command.ExecStartCmd)1 InspectContainerCmd (com.github.dockerjava.api.command.InspectContainerCmd)1 InspectContainerResponse (com.github.dockerjava.api.command.InspectContainerResponse)1 InspectExecResponse (com.github.dockerjava.api.command.InspectExecResponse)1 NotModifiedException (com.github.dockerjava.api.exception.NotModifiedException)1 AuthConfig (com.github.dockerjava.api.model.AuthConfig)1 Container (com.github.dockerjava.api.model.Container)1