Search in sources :

Example 1 with PullImageResultCallback

use of com.github.dockerjava.core.command.PullImageResultCallback in project hub-docker-inspector by blackducksoftware.

the class DockerClientManager method pullImage.

public String pullImage(final String imageName, final String tagName) throws HubIntegrationException {
    logger.info(String.format("Pulling image %s:%s", imageName, tagName));
    final DockerClient dockerClient = hubDockerClient.getDockerClient();
    final Image alreadyPulledImage = getLocalImage(dockerClient, imageName, tagName);
    if (alreadyPulledImage == null) {
        // Only pull if we dont already have it
        final PullImageCmd pull = dockerClient.pullImageCmd(imageName).withTag(tagName);
        try {
            pull.exec(new PullImageResultCallback()).awaitSuccess();
        } catch (final NotFoundException e) {
            final String msg = String.format("Pull failed: Image %s:%s not found. Please check the image name/tag", imageName, tagName);
            logger.error(msg);
            throw new HubIntegrationException(msg, e);
        }
        final Image justPulledImage = getLocalImage(dockerClient, imageName, tagName);
        if (justPulledImage == null) {
            final String msg = String.format("Pulled image %s:%s not found in image list.", imageName, tagName);
            logger.error(msg);
            throw new HubIntegrationException(msg);
        }
        return justPulledImage.getId();
    } else {
        logger.info("Image already pulled");
        return alreadyPulledImage.getId();
    }
}
Also used : DockerClient(com.github.dockerjava.api.DockerClient) PullImageCmd(com.github.dockerjava.api.command.PullImageCmd) PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) Image(com.github.dockerjava.api.model.Image) HubIntegrationException(com.blackducksoftware.integration.hub.exception.HubIntegrationException)

Example 2 with PullImageResultCallback

use of com.github.dockerjava.core.command.PullImageResultCallback in project elastest-torm by elastest.

the class DockerService2 method pullETExecImage.

public void pullETExecImage(String image, String name) throws TJobStoppedException {
    DockerClient dockerClient = this.getDockerClient();
    try {
        logger.debug("Try to Pulling {} Image ({})", name, image);
        dockerClient.pullImageCmd(image).exec(new PullImageResultCallback()).awaitCompletion();
        logger.debug("{} image pulled succesfully!", name);
    } catch (InternalServerErrorException | NotFoundException | InterruptedException e) {
        if (imageExistsLocally(image, dockerClient)) {
            logger.info("Docker image exits locally.");
        } else {
            logger.error("Error pulling the {} image: {}", name, image, e.getMessage());
        }
    } catch (DockerClientException e) {
        logger.info("Error on Pulling {} image ({}). Probably because the user has stopped the execution", name, image);
        throw new TJobStoppedException();
    }
}
Also used : DockerClient(com.github.dockerjava.api.DockerClient) DockerClientException(com.github.dockerjava.api.exception.DockerClientException) PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) InternalServerErrorException(com.github.dockerjava.api.exception.InternalServerErrorException) NotFoundException(com.github.dockerjava.api.exception.NotFoundException)

Example 3 with PullImageResultCallback

use of com.github.dockerjava.core.command.PullImageResultCallback in project elastest-torm by elastest.

the class DockerServiceItTest method readLogInRabbit.

@Test
public void readLogInRabbit() throws Exception {
    String imageId = "alpine";
    if (!existsImage(imageId)) {
        log.info("Pulling image '{}'", imageId);
        dockerClient.pullImageCmd(imageId).exec(new PullImageResultCallback()).awaitSuccess();
    }
    String queueId = "test.default_log.1.log";
    String tag = "test_1_exec";
    WaitForMessagesHandler handler = connectToRabbitQueue(queueId);
    LogConfig logConfig = getLogConfig(tag);
    log.info("Creating container");
    CreateContainerResponse container = dockerClient.createContainerCmd(imageId).withCmd("/bin/sh", "-c", "while true; do echo hello; sleep 1; done").withTty(false).withLogConfig(logConfig).withNetworkMode("bridge").exec();
    String containerId = container.getId();
    try {
        log.info("Created container: {}", container.toString());
        long start = System.currentTimeMillis();
        dockerClient.startContainerCmd(containerId).exec();
        log.info("Waiting for logs messages in Rabbit");
        handler.waitForCompletion(5, TimeUnit.SECONDS);
        long duration = System.currentTimeMillis() - start;
        log.info("Log received in Rabbit in {} millis", duration);
    } catch (Exception ex) {
        log.info("Log NOT received in Rabbit");
        throw ex;
    } finally {
        log.info("Cleaning up resources");
        try {
            log.info("Removing container " + containerId);
            try {
                dockerClient.stopContainerCmd(containerId).exec();
            } catch (Exception ex) {
                log.warn("Error stopping container {}", containerId, ex);
            }
            dockerClient.removeContainerCmd(containerId).exec();
        } catch (Exception ex) {
            log.warn("Error on ending test execution {}", containerId, ex);
        }
    }
}
Also used : PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) CreateContainerResponse(com.github.dockerjava.api.command.CreateContainerResponse) WaitForMessagesHandler(io.elastest.etm.test.util.StompTestUtils.WaitForMessagesHandler) TimeoutException(java.util.concurrent.TimeoutException) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) LogConfig(com.github.dockerjava.api.model.LogConfig) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 4 with PullImageResultCallback

use of com.github.dockerjava.core.command.PullImageResultCallback in project camel by apache.

the class AsyncDockerProducer method process.

@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    try {
        Message message = exchange.getIn();
        DockerClient client = DockerClientFactory.getDockerClient(component, configuration, message);
        DockerOperation operation = configuration.getOperation();
        Object result = null;
        switch(operation) {
            /** Images **/
            case BUILD_IMAGE:
                // result contain an image id value
                result = executeBuildImageRequest(client, message).exec(new BuildImageResultCallback() {

                    @Override
                    public void onNext(BuildResponseItem item) {
                        log.trace("build image callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    String imageId = ((BuildImageResultCallback) result).awaitImageId();
                    ((BuildImageResultCallback) result).close();
                    result = imageId;
                }
                break;
            case PULL_IMAGE:
                result = executePullImageRequest(client, message).exec(new PullImageResultCallback() {

                    @Override
                    public void onNext(PullResponseItem item) {
                        log.trace("pull image callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    result = ((PullImageResultCallback) result).awaitCompletion();
                    ((PullImageResultCallback) result).close();
                }
                break;
            case PUSH_IMAGE:
                result = executePushImageRequest(client, message).exec(new PushImageResultCallback() {

                    @Override
                    public void onNext(PushResponseItem item) {
                        log.trace("push image callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    result = ((PushImageResultCallback) result).awaitCompletion();
                    ((PushImageResultCallback) result).close();
                }
                break;
            /** Containers **/
            case ATTACH_CONTAINER:
                result = executeAttachContainerRequest(client, message).exec(new AttachContainerResultCallback() {

                    @Override
                    public void onNext(Frame item) {
                        log.trace("attach container callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    result = ((AttachContainerResultCallback) result).awaitCompletion();
                    ((AttachContainerResultCallback) result).close();
                }
                break;
            case LOG_CONTAINER:
                result = executeLogContainerRequest(client, message).exec(new LogContainerResultCallback() {

                    @Override
                    public void onNext(Frame item) {
                        log.trace("log container callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    result = ((LogContainerResultCallback) result).awaitCompletion();
                    ((LogContainerResultCallback) result).close();
                }
                break;
            case WAIT_CONTAINER:
                // result contain a status code value
                result = executeWaitContainerRequest(client, message).exec(new WaitContainerResultCallback() {

                    @Override
                    public void onNext(WaitResponse item) {
                        log.trace("wait contanier callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    Integer statusCode = ((WaitContainerResultCallback) result).awaitStatusCode();
                    ((WaitContainerResultCallback) result).close();
                    result = statusCode;
                }
                break;
            case EXEC_START:
                result = executeExecStartRequest(client, message).exec(new ExecStartResultCallback() {

                    @Override
                    public void onNext(Frame item) {
                        log.trace("exec start callback {}", item);
                        super.onNext(item);
                    }
                });
                if (result != null) {
                    result = ((ExecStartResultCallback) result).awaitCompletion();
                    ((ExecStartResultCallback) result).close();
                }
                break;
            default:
                throw new DockerException("Invalid operation: " + operation);
        }
        // If request included a response, set as body
        if (result != null) {
            exchange.getIn().setBody(result);
            return true;
        }
    } catch (DockerException | InterruptedException | IOException e) {
        log.error(e.getMessage(), e);
        return false;
    }
    return false;
}
Also used : DockerException(org.apache.camel.component.docker.exception.DockerException) BuildResponseItem(com.github.dockerjava.api.model.BuildResponseItem) Frame(com.github.dockerjava.api.model.Frame) Message(org.apache.camel.Message) DockerClient(com.github.dockerjava.api.DockerClient) ExecStartResultCallback(com.github.dockerjava.core.command.ExecStartResultCallback) PushResponseItem(com.github.dockerjava.api.model.PushResponseItem) PushImageResultCallback(com.github.dockerjava.core.command.PushImageResultCallback) IOException(java.io.IOException) WaitResponse(com.github.dockerjava.api.model.WaitResponse) AttachContainerResultCallback(com.github.dockerjava.core.command.AttachContainerResultCallback) BuildImageResultCallback(com.github.dockerjava.core.command.BuildImageResultCallback) WaitContainerResultCallback(com.github.dockerjava.core.command.WaitContainerResultCallback) PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) LogContainerResultCallback(com.github.dockerjava.core.command.LogContainerResultCallback) DockerOperation(org.apache.camel.component.docker.DockerOperation) PullResponseItem(com.github.dockerjava.api.model.PullResponseItem)

Example 5 with PullImageResultCallback

use of com.github.dockerjava.core.command.PullImageResultCallback in project elastest-torm by elastest.

the class DockerService2 method runDockerContainer.

/**
 **************************
 */
/**
 *** Container Methods ****
 */
/**
 **************************
 */
public String runDockerContainer(DockerClient dockerClient, String imageName, List<String> envs, String containerName, String networkName, Ports portBindings, int listenPort) throws TJobStoppedException {
    try {
        dockerClient.pullImageCmd(imageName).exec(new PullImageResultCallback()).awaitSuccess();
    } catch (InternalServerErrorException | NotFoundException ie) {
        if (imageExistsLocally(imageName, dockerClient)) {
            logger.info("Docker image exits locally.");
        } else {
            throw ie;
        }
    } catch (DockerClientException e) {
        logger.info("Error on Pulling " + imageName + " image. Probably because the user has stopped the execution");
        throw new TJobStoppedException();
    }
    CreateContainerResponse container = dockerClient.createContainerCmd(imageName).withName(containerName).withEnv(envs).withNetworkMode(networkName).withExposedPorts(ExposedPort.tcp(listenPort)).withPortBindings(portBindings).withPublishAllPorts(true).exec();
    dockerClient.startContainerCmd(container.getId()).exec();
    this.insertCreatedContainer(container.getId(), containerName);
    logger.info("Id del contenedor:" + container.getId());
    return container.getId();
}
Also used : DockerClientException(com.github.dockerjava.api.exception.DockerClientException) PullImageResultCallback(com.github.dockerjava.core.command.PullImageResultCallback) InternalServerErrorException(com.github.dockerjava.api.exception.InternalServerErrorException) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) CreateContainerResponse(com.github.dockerjava.api.command.CreateContainerResponse)

Aggregations

PullImageResultCallback (com.github.dockerjava.core.command.PullImageResultCallback)7 DockerClient (com.github.dockerjava.api.DockerClient)4 NotFoundException (com.github.dockerjava.api.exception.NotFoundException)4 CreateContainerResponse (com.github.dockerjava.api.command.CreateContainerResponse)3 DockerClientException (com.github.dockerjava.api.exception.DockerClientException)3 InternalServerErrorException (com.github.dockerjava.api.exception.InternalServerErrorException)2 Image (com.github.dockerjava.api.model.Image)2 IOException (java.io.IOException)2 HubIntegrationException (com.blackducksoftware.integration.hub.exception.HubIntegrationException)1 ListContainersCmd (com.github.dockerjava.api.command.ListContainersCmd)1 ListImagesCmd (com.github.dockerjava.api.command.ListImagesCmd)1 PullImageCmd (com.github.dockerjava.api.command.PullImageCmd)1 BuildResponseItem (com.github.dockerjava.api.model.BuildResponseItem)1 Frame (com.github.dockerjava.api.model.Frame)1 LogConfig (com.github.dockerjava.api.model.LogConfig)1 PullResponseItem (com.github.dockerjava.api.model.PullResponseItem)1 PushResponseItem (com.github.dockerjava.api.model.PushResponseItem)1 WaitResponse (com.github.dockerjava.api.model.WaitResponse)1 AttachContainerResultCallback (com.github.dockerjava.core.command.AttachContainerResultCallback)1 BuildImageResultCallback (com.github.dockerjava.core.command.BuildImageResultCallback)1