com.github.dockerjava.core.command.PullImageResultCallback Java Examples

The following examples show how to use com.github.dockerjava.core.command.PullImageResultCallback. 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: DockerImageManagementService.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Override
public ResourceItem createItem(ResourceItem item) {
    Map<String, String> additionalProperties = item.getAdditionalPropertiesMap();
    String repository = additionalProperties.get("repository");
    String tag = additionalProperties.get("tag");
    try {
        DockerClient dockerClient = newDockerClient(item.getResourceServer().getHost(), item.getResourceServer().getPort());
        dockerClient.pullImageCmd(repository)
                .withTag(tag)
                .exec(new PullImageResultCallback())
                .awaitCompletion(resourceProperties.getDockerPullImageTimeout(), TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new WecubeCoreException(String.format("Failed to pull repository [%s] with tag [%s].", repository, tag), e);
    }
    return item;
}
 
Example #2
Source File: PullImageCommand.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws DockerException {
	AuthConfig authConfig = new AuthConfig()
		       .withUsername("docker")
		       .withPassword("docker")
		       .withEmail("[email protected]")
		       .withRegistryAddress("nexus3.acumos.org");
	String imageFullName = "nexus3.acumos.org:10004/onboarding-base-r";
	logger.debug("Full Image Name: " + imageFullName);
	final DockerClient client = getClient();

	logger.debug("Auth Config started: " + authConfig.toString());
	client.authCmd().withAuthConfig(authConfig).exec(); // WORKS

	logger.debug("Pull Command started");
	client.pullImageCmd(imageFullName) // FAILS
	        .withTag("1.0")
	        .withAuthConfig(authConfig)
	        .exec(new PullImageResultCallback()).awaitSuccess();
	logger.debug("Pull Command end");

}
 
Example #3
Source File: DockerBuilderControlOptionRun.java    From docker-plugin with MIT License 6 votes vote down vote up
private void executePullOnDocker(Run<?, ?> build, PrintStream llog, String xImage, DockerClient client)
        throws DockerException {
    PullImageResultCallback resultCallback = new PullImageResultCallback() {
        @Override
        public void onNext(PullResponseItem item) {
            if (item.getStatus() != null && item.getProgress() == null) {
                llog.print(item.getId() + ":" + item.getStatus());
                LOG.info("{} : {}", item.getId(), item.getStatus());
            }
            super.onNext(item);
        }
    };

    PullImageCmd cmd = client.pullImageCmd(xImage);
    DockerCloud.setRegistryAuthentication(cmd, getRegistry(), build.getParent().getParent());
    try {
        cmd.exec(resultCallback).awaitCompletion();
    } catch (InterruptedException e) {
        throw new DockerClientException("Interrupted while pulling image", e);
    }
}
 
Example #4
Source File: DockerImageServiceImpl.java    From Dolphin with Apache License 2.0 6 votes vote down vote up
public void pull(InstanceStartRequest request, InstanceStartResponse response) {
    try {
        dockerClient.pullImageCmd(request.getRepository()).exec(new PullImageResultCallback() {
            @Override
            public void onNext(PullResponseItem item) {
                super.onNext(item);
                if (logger.isDebugEnabled()) {
                    logger.debug(item);
                }
            }
        }).awaitSuccess();
        response.success();
    } catch (Exception e) {
        response.fail(e.toString());
        logger.error(String.format("error pullImage: %s", request), e);
    }
}
 
Example #5
Source File: Docker.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public void pullImageIfNecessary(String imageId, boolean force) {
  if (imageId.isEmpty()) {
    return;
  }
  if (force || !existsImage(imageId)) {
    log.debug("Pulling Docker image {} ... please be patient until the process finishes",
        imageId);
    try {
      getClient().pullImageCmd(imageId).exec(new PullImageResultCallback()).awaitCompletion();
    }
    catch (Exception e) {
      log.warn("Exception pulling image {}", imageId, e);
    }
    log.debug("Image {} downloaded", imageId);

  } else {
    log.debug("Image {} already exists", imageId);
  }
}
 
Example #6
Source File: ImagePullPolicyTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception {
    String testRegistryAddress = registry.getHost() + ":" + registry.getFirstMappedPort();
    String testImageName = testRegistryAddress + "/image-pull-policy-test";
    String tag = UUID.randomUUID().toString();
    imageName = testImageName + ":" + tag;

    DockerClient client = DockerClientFactory.instance().client();
    String dummySourceImage = "hello-world:latest";
    client.pullImageCmd(dummySourceImage).exec(new PullImageResultCallback()).awaitCompletion();

    String dummyImageId = client.inspectImageCmd(dummySourceImage).exec().getId();

    // push the image to the registry
    client.tagImageCmd(dummyImageId, testImageName, tag).exec();

    client.pushImageCmd(imageName)
        .exec(new PushImageResultCallback())
        .awaitCompletion(1, TimeUnit.MINUTES);
}
 
Example #7
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {

    // when
    dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS);

    // then
    List<Image> images = dockerClient.listImagesCmd().exec();
    assertThat(images.size(), is(not(0)));
}
 
Example #8
Source File: BesuNode.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private void pullBesuImage() {
  final PullImageResultCallback callback = new PullImageResultCallback();
  docker.pullImageCmd(BESU_IMAGE).exec(callback);

  try {
    LOG.info("Pulling the Besu Docker image...");
    callback.awaitCompletion();
    LOG.info("Pulled the Besu Docker image: " + BESU_IMAGE);
  } catch (final InterruptedException e) {
    LOG.error(e);
  }
}
 
Example #9
Source File: DockerTemplate.java    From docker-plugin with MIT License 5 votes vote down vote up
@Nonnull
InspectImageResponse pullImage(DockerAPI api, TaskListener listener) throws IOException, InterruptedException {
    final String image = getFullImageId();

    final boolean shouldPullImage;
    try(final DockerClient client = api.getClient()) {
        shouldPullImage = getPullStrategy().shouldPullImage(client, image);
    }
    if (shouldPullImage) {
        // TODO create a FlyWeightTask so end-user get visibility on pull operation progress
        LOGGER.info("Pulling image '{}'. This may take awhile...", image);

        long startTime = System.currentTimeMillis();

        try(final DockerClient client = api.getClient(pullTimeout)) {
            final PullImageCmd cmd =  client.pullImageCmd(image);
            final DockerRegistryEndpoint registry = getRegistry();
            DockerCloud.setRegistryAuthentication(cmd, registry, Jenkins.getInstance());
            cmd.exec(new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    super.onNext(item);
                    listener.getLogger().println(item.getStatus());
                }
            }).awaitCompletion();
        }

        long pullTime = System.currentTimeMillis() - startTime;
        LOGGER.info("Finished pulling image '{}', took {} ms", image, pullTime);
    }

    final InspectImageResponse result;
    try(final DockerClient client = api.getClient()) {
        result = client.inspectImageCmd(image).exec();
    } catch (NotFoundException e) {
        throw new DockerClientException("Could not pull image: " + image, e);
    }
    return result;
}
 
Example #10
Source File: DockerContainersUtil.java    From minimesos with Apache License 2.0 5 votes vote down vote up
/**
 * Pulls a Docker image with given name and version. Throws exception when it times out after given timeout.
 *
 * @param imageName    image to pull
 * @param imageVersion image version to pull
 * @param timeoutSecs  pulling timeout in seconds
 */
public static void pullImage(String imageName, String imageVersion, long timeoutSecs) {
    try {
        final CompletableFuture<Void> result = new CompletableFuture<>();
        DockerClientFactory.build().pullImageCmd(imageName).withTag(imageVersion).exec(new PullImageResultCallback()).awaitCompletion();
    } catch (InterruptedException | RuntimeException e) {
        throw new MinimesosException("Error pulling image or image not found in registry: " + imageName + ":" + imageVersion, e);
    }
}
 
Example #11
Source File: DockerImageExecutor.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> run(TestEnvironment testEnvironment) {
    String hostOsMountDir = System.getProperties().getProperty("buildDirectory");


    CreateContainerCmd containerBuilder = dockerClient.createContainerCmd(testEnvironment.getImage())
            .withBinds(new Bind(hostOsMountDir, new Volume(Constants.HAWKULAR_APM_AGENT_DIRECTORY),
                            AccessMode.ro, SELContext.shared),
                new Bind(scenarioDirectory, new Volume(Constants.HAWKULAR_APM_TEST_DIRECTORY),
                        AccessMode.ro, SELContext.shared))
            .withExtraHosts(Constants.HOST_ADDED_TO_ETC_HOSTS + ":" + apmBindAddress);

    if (userDefinedNetwork) {
        if (network == null) {
            throw new IllegalStateException("Create network before running environment");
        }
        containerBuilder.withNetworkMode(network.getName());
    }

    containerBuilder.withEnv(apmEnvVariables(testEnvironment.getType()));

    if (testEnvironment.isPull()) {
        log.info("Pulling image...");
        dockerClient.pullImageCmd(testEnvironment.getImage()).exec(new PullImageResultCallback()).awaitSuccess();
    }

    CreateContainerResponse containerResponse = containerBuilder.exec();
    log.info(String.format("Starting docker container: %s", containerResponse));

    try {
        dockerClient.startContainerCmd(containerResponse.getId()).exec();
    } catch (DockerException ex) {
        log.severe(String.format("Could not create or start docker container: %s", containerResponse));
        throw new EnvironmentException("Could not create or start docker container.", ex);
    }

    return Arrays.asList(containerResponse.getId());
}
 
Example #12
Source File: DefaultDockerClientIT.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
private void ensureImageExists(String wantedImage) {
    try {
        dockerClient.inspectImageCmd(wantedImage).exec();
    } catch (NotFoundException e) {
        dockerClient.pullImageCmd(wantedImage).exec(new PullImageResultCallback()).awaitSuccess();
    }
}
 
Example #13
Source File: DefaultDockerClient.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
private void ensureImageExists(String wantedImage) {
    try {
        dockerClient.inspectImageCmd(wantedImage).exec();
    } catch (NotFoundException e) {
        dockerClient.pullImageCmd(wantedImage).exec(new PullImageResultCallback()).awaitSuccess();
    }
}
 
Example #14
Source File: DockerClientOperation.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
/**
 * @param ip
 * @param repository
 * @param tag
 * @return
 * @throws InterruptedException
 */
public boolean pullImage(String ip, String repository, String tag) throws InterruptedException {
    DockerClient dockerClient = getDockerClient(ip);
    PullImageCmd pullImageCmd = dockerClient.pullImageCmd(repository);
    if (!Strings.isNullOrEmpty(tag)) {
        pullImageCmd.withTag(tag);
    }
    pullImageCmd.exec(new PullImageResultCallback()).awaitCompletion();
    return true;
}
 
Example #15
Source File: DockerComposeLocalImageTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
private void tagImage(String sourceImage, String targetImage, String targetTag) throws InterruptedException {
    DockerClient client = DockerClientFactory.instance().client();
    client.pullImageCmd(sourceImage).exec(new PullImageResultCallback()).awaitCompletion();
    client.tagImageCmd(sourceImage, targetImage, targetTag).exec();
}
 
Example #16
Source File: DeploymentSystemTest.java    From logstash with Apache License 2.0 4 votes vote down vote up
@Test
public void willForwardDataToElasticsearchInDockerMode() throws Exception {
    final ElasticsearchContainer elasticsearchInstance = new ElasticsearchContainer(dockerClient);
    cluster.addAndStartContainer(elasticsearchInstance);

    Client elasticsearchClient = elasticsearchInstance.createClient();

    deployScheduler("logstash", elasticsearchInstance.getIpAddress() + ":9200", true, null, true);

    final String sysLogPort = "514";
    final String randomLogLine = "Hello " + RandomStringUtils.randomAlphanumeric(32);

    dockerClient.pullImageCmd("ubuntu:15.10").exec(new PullImageResultCallback()).awaitSuccess();
    final String logstashSlave = dockerClient.listContainersCmd().withSince(cluster.getAgents().get(0).getContainerId()).exec().stream().filter(container -> container.getImage().endsWith("/logstash-executor:latest")).findFirst().map(Container::getId).orElseThrow(() -> new AssertionError("Unable to find logstash container"));

    assertTrue("logstash slave is expected to be running", dockerClient.inspectContainerCmd(logstashSlave).exec().getState().isRunning());

    final CreateContainerResponse loggerContainer = dockerClient.createContainerCmd("ubuntu:15.10").withLinks(new Link(logstashSlave, "logstash")).withCmd("logger", "--server=logstash", "--port=" + sysLogPort, "--udp", "--rfc3164", randomLogLine).exec();
    dockerClient.startContainerCmd(loggerContainer.getId()).exec();

    await().atMost(5, SECONDS).pollDelay(1, SECONDS).until(() -> {
        final String finishedAt = dockerClient.inspectContainerCmd(loggerContainer.getId()).exec().getState().getFinishedAt();
        assertNotEquals("", finishedAt.trim());
        assertNotEquals("0001-01-01T00:00:00Z", finishedAt);
    });

    final int exitCode = dockerClient.inspectContainerCmd(loggerContainer.getId()).exec().getState().getExitCode();
    dockerClient.removeContainerCmd(loggerContainer.getId()).exec();
    assertEquals(0, exitCode);

    await().atMost(10, SECONDS).pollDelay(1, SECONDS).until(() -> {
        final SearchHits hits = elasticsearchClient.prepareSearch("logstash-*").setQuery(QueryBuilders.simpleQueryStringQuery("Hello")).addField("message").addField("mesos_agent_id").execute().actionGet().getHits();
        assertEquals(1, hits.totalHits());
        Map<String, SearchHitField> fields = hits.getAt(0).fields();

        String esMessage = fields.get("message").getValue();
        assertEquals(randomLogLine, esMessage.trim());

        String esMesosSlaveId = fields.get("mesos_agent_id").getValue();

        String trueSlaveId;
        try {
            trueSlaveId = cluster.getClusterStateInfo().getJSONArray("slaves").getJSONObject(0).getString("id");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        assertEquals(trueSlaveId, esMesosSlaveId.trim());
    });
}
 
Example #17
Source File: DeploymentSystemTest.java    From logstash with Apache License 2.0 4 votes vote down vote up
@Test
public void willForwardDataToElasticsearchInJarMode() throws Exception {
    final ElasticsearchContainer elasticsearchInstance = new ElasticsearchContainer(dockerClient);
    cluster.addAndStartContainer(elasticsearchInstance);

    Client elasticsearchClient = elasticsearchInstance.createClient();

    deployScheduler("logstash", elasticsearchInstance.getIpAddress() + ":9200", false, null, true);

    final String sysLogPort = "514";
    final String randomLogLine = "Hello " + RandomStringUtils.randomAlphanumeric(32);

    dockerClient.pullImageCmd("ubuntu:15.10").exec(new PullImageResultCallback()).awaitSuccess();
    final String logstashSlave = cluster.getAgents().get(0).getContainerId();

    assertTrue(dockerClient.inspectContainerCmd(logstashSlave).exec().getState().isRunning());

    final CreateContainerResponse loggerContainer = dockerClient.createContainerCmd("ubuntu:15.10").withLinks(new Link(logstashSlave, "logstash")).withCmd("logger", "--server=logstash", "--port=" + sysLogPort, "--udp", "--rfc3164", randomLogLine).exec();
    dockerClient.startContainerCmd(loggerContainer.getId()).exec();

    await().atMost(5, SECONDS).pollDelay(1, SECONDS).until(() -> {
        final String finishedAt = dockerClient.inspectContainerCmd(loggerContainer.getId()).exec().getState().getFinishedAt();
        assertNotEquals("", finishedAt.trim());
        assertNotEquals("0001-01-01T00:00:00Z", finishedAt);
    });


    final int exitCode = dockerClient.inspectContainerCmd(loggerContainer.getId()).exec().getState().getExitCode();
    dockerClient.removeContainerCmd(loggerContainer.getId()).exec();
    assertEquals(0, exitCode);

    await().atMost(10, SECONDS).pollDelay(1, SECONDS).until(() -> {
        final SearchHits hits = elasticsearchClient.prepareSearch("logstash-*").setQuery(QueryBuilders.simpleQueryStringQuery("Hello")).addField("message").addField("mesos_agent_id").execute().actionGet().getHits();
        assertEquals(1, hits.totalHits());
        Map<String, SearchHitField> fields = hits.getAt(0).fields();

        String esMessage = fields.get("message").getValue();
        assertEquals(randomLogLine, esMessage.trim());

        String esMesosSlaveId = fields.get("mesos_agent_id").getValue();

        String trueSlaveId;
        try {
            trueSlaveId = cluster.getClusterStateInfo().getJSONArray("slaves").getJSONObject(0).getString("id");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        assertEquals(trueSlaveId, esMesosSlaveId.trim());
    });
}