Java Code Examples for com.spotify.docker.client.DockerClient#pull()

The following examples show how to use com.spotify.docker.client.DockerClient#pull() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DockerHelper.java    From just-ask with Apache License 2.0 6 votes vote down vote up
private static void predownloadImagesIfRequired() throws DockerException, InterruptedException {

        DockerClient client = getClient();
        LOG.warning("Commencing download of images.");
        Collection<MappingInfo> images = getInstance().getMapping().values();

        ProgressHandler handler = new LoggingBuildHandler();
        for (MappingInfo image : images) {
            List<Image> foundImages = client.listImages(DockerClient.ListImagesParam.byName(image.getTarget()));
            if (! foundImages.isEmpty()) {
                LOG.warning(String.format("Skipping download for Image [%s] because it's already available.",
                    image.getTarget()));
                continue;
            }
            client.pull(image.getTarget(), handler);
        }
    }
 
Example 2
Source File: RedisContainer.java    From pay-publicapi with MIT License 5 votes vote down vote up
private void failsafeDockerPull(DockerClient docker) {
    try {
        docker.pull(REDIS_IMAGE);
    } catch (Exception e) {
        logger.error("Docker image " + REDIS_IMAGE + " could not be pulled from DockerHub", e);
    }
}
 
Example 3
Source File: FetchArtifactExecutor.java    From docker-registry-artifact-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public GoPluginApiResponse execute() {
    try {
        final Map<String, String> artifactMap = fetchArtifactRequest.getMetadata();
        validateMetadata(artifactMap);
        FetchArtifactConfig fetchArtifactConfig = fetchArtifactRequest.getFetchArtifactConfig();

        final String artifactPrefix = fetchArtifactConfig.getEnvironmentVariablePrefix();
        final boolean skipImagePulling = fetchArtifactConfig.getSkipImagePulling();
        final String imageToPull = artifactMap.get("image");

        if (skipImagePulling) {
            consoleLogger.info(String.format("Not pulling docker image `%s` due to `Skip Image Pulling` configuration being set.", imageToPull));
            LOG.info(String.format("Not pulling docker image `%s` due to `Skip Image Pulling` configuration being set.", imageToPull));
        } else {
            consoleLogger.info(String.format("Pulling docker image `%s` from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));
            LOG.info(String.format("Pulling docker image `%s` from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));

            DockerClient docker = clientFactory.docker(fetchArtifactRequest.getArtifactStoreConfig());
            docker.pull(imageToPull, dockerProgressHandler);
            docker.close();

            consoleLogger.info(String.format("Image `%s` successfully pulled from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));

            if (!dockerProgressHandler.getDigest().equals(artifactMap.get("digest"))) {
                throw new RuntimeException(format("Expecting pulled image digest to be [%s] but it is [%s].", artifactMap.get("digest"), dockerProgressHandler.getDigest()));
            }
        }

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", StringUtils.isEmpty(artifactPrefix) ? "ARTIFACT_IMAGE" : String.format("%s_ARTIFACT_IMAGE", artifactPrefix));
        jsonObject.addProperty("value", imageToPull);

        JsonArray jsonElements = new JsonArray();
        jsonElements.add(jsonObject);

        return DefaultGoPluginApiResponse.success(jsonElements.toString());
    } catch (Exception e) {
        final String message = format("Failed pull docker image: %s", e);
        consoleLogger.error(message);
        LOG.error(message);
        return DefaultGoPluginApiResponse.error(message);
    }
}
 
Example 4
Source File: DockerSample.java    From just-ask with Apache License 2.0 4 votes vote down vote up
private static void foo() throws Exception {
    boolean debug = Boolean.parseBoolean(System.getProperty("debug", "false"));
    String dockerHost = String.format("http://%s:%d", CENTOS, 2375);
    DockerClient docker = null;
    try {
        docker = DefaultDockerClient.builder()
            .uri(dockerHost).build();
        Info info = docker.info();
        System.err.println("Information : " + info);
        if (debug) {
            docker.pull(SELENIUM_STANDALONE_CHROME, new LoggingBuildHandler());
        } else {
            docker.pull(SELENIUM_STANDALONE_CHROME);
        }
        final ImageInfo imageInfo = docker.inspectImage(SELENIUM_STANDALONE_CHROME);
        System.err.println("Information : " + imageInfo);
        // Bind container ports to host ports
        //            final String[] ports = {Integer.toString(PortProber.findFreePort())};
        final String[] ports = {"4444"};
        final Map<String, List<PortBinding>> portBindings = new HashMap<>();
        for (String port : ports) {
            List<PortBinding> hostPorts = new ArrayList<>();
            hostPorts.add(PortBinding.of("0.0.0.0", PortProber.findFreePort()));
            portBindings.put(port, hostPorts);
        }
        //            // Bind container port 443 to an automatically allocated available host port.
        //            List<PortBinding> randomPort = new ArrayList<>();
        //            randomPort.add(PortBinding.randomPort("0.0.0.0"));
        //            portBindings.put("443", randomPort);

        System.err.println("Printing the port mappings : " + portBindings);

        final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();

        final ContainerConfig containerConfig = ContainerConfig.builder()
            .hostConfig(hostConfig)
            .image(SELENIUM_STANDALONE_CHROME).exposedPorts(ports)
            .build();

        final ContainerCreation creation = docker.createContainer(containerConfig);
        final String id = creation.id();

        // Inspect container
        final ContainerInfo containerInfo = docker.inspectContainer(id);
        System.err.println("Container Information " + containerInfo);
        String msg = "Checking to see if the container with id [" + id + "] and name [" +
            containerInfo.name() + "]...";
        System.err.println(msg);
        if (! containerInfo.state().running()) {
            // Start container
            docker.startContainer(id);
            System.err.println(containerInfo.name() + " is now running.");
        } else {
            System.err.println(containerInfo.name() + " was already running.");
        }

        System.err.println("Lets wait here !!!");
    } finally {
        if (docker != null) {
            docker.close();
        }
    }
}
 
Example 5
Source File: DockerContainer.java    From docker-elastic-agents-plugin with Apache License 2.0 4 votes vote down vote up
public static DockerContainer create(CreateAgentRequest request, PluginSettings settings, DockerClient docker,
                                     ConsoleLogAppender consoleLogAppender) throws InterruptedException, DockerException {
    String containerName = UUID.randomUUID().toString();

    HashMap<String, String> labels = labelsFrom(request);
    String imageName = image(request.properties());
    List<String> env = environmentFrom(request, settings, containerName);

    try {
        docker.inspectImage(imageName);
        if (settings.pullOnContainerCreate()) {
            consoleLogAppender.accept("Pulling a fresh version of " + imageName + ".");
            LOG.info("Pulling a fresh version of " + imageName + ".");
            docker.pull(imageName);
        }
    } catch (ImageNotFoundException ex) {
        consoleLogAppender.accept("Image " + imageName + " not found, attempting to download.");
        LOG.info("Image " + imageName + " not found, attempting to download.");
        docker.pull(imageName);
    }

    ContainerConfig.Builder containerConfigBuilder = ContainerConfig.builder();
    if (StringUtils.isNotBlank(request.properties().get("Command"))) {
        containerConfigBuilder.cmd(splitIntoLinesAndTrimSpaces(request.properties().get("Command")).toArray(new String[]{}));
    }

    final String hostConfig = request.properties().get("Hosts");
    final String reservedMemory = request.properties().get("ReservedMemory");
    final String maxMemory = request.properties().get("MaxMemory");
    final String cpus = request.properties().get("Cpus");
    final String volumeMounts = request.properties().get("Mounts");

    HostConfig.Builder hostBuilder = HostConfig.builder()
            .privileged(privileged(request.properties()))
            .extraHosts(new Hosts(hostConfig))
            .memoryReservation(new MemorySpecification(reservedMemory).getMemory())
            .memory(new MemorySpecification(maxMemory).getMemory());

    CpusSpecification cpusValue = new CpusSpecification(cpus);
    if (cpusValue.getCpus() != null) {
        hostBuilder
                .cpuPeriod(cpusValue.getCpuPeriod())
                .cpuQuota(cpusValue.getCpuQuota());
    }
    if (volumeMounts != null) {
        hostBuilder.appendBinds(Util.splitIntoLinesAndTrimSpaces(volumeMounts));
    }

    ContainerConfig containerConfig = containerConfigBuilder
            .image(imageName)
            .labels(labels)
            .env(env)
            .hostConfig(hostBuilder.build())
            .build();

    consoleLogAppender.accept(String.format("Creating container: %s", containerName));
    ContainerCreation container = docker.createContainer(containerConfig, containerName);
    String id = container.id();

    ContainerInfo containerInfo = docker.inspectContainer(id);

    LOG.debug("Created container " + containerName);
    consoleLogAppender.accept(String.format("Starting container: %s", containerName));
    docker.startContainer(containerName);
    consoleLogAppender.accept(String.format("Started container: %s", containerName));
    LOG.debug("container " + containerName + " started");
    return new DockerContainer(id, containerName, request.jobIdentifier(), containerInfo.created(), request.properties(), request.environment());
}