Search in sources :

Example 16 with DockerResponse

use of org.eclipse.che.plugin.docker.client.connection.DockerResponse in project che by eclipse.

the class DockerConnector method listContainers.

/**
     * Method returns list of docker containers which was filtered by {@link ListContainersParams}
     *
     * @throws IOException
     *         when problems occurs with docker api calls
     */
public List<ContainerListEntry> listContainers(ListContainersParams params) throws IOException {
    final Filters filters = params.getFilters();
    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("GET").path(apiVersionPathPrefix + "/containers/json")) {
        addQueryParamIfNotNull(connection, "all", params.isAll());
        addQueryParamIfNotNull(connection, "size", params.isSize());
        addQueryParamIfNotNull(connection, "limit", params.getLimit());
        addQueryParamIfNotNull(connection, "since", params.getSince());
        addQueryParamIfNotNull(connection, "before", params.getBefore());
        if (filters != null) {
            connection.query("filters", urlPathSegmentEscaper().escape(toJson(filters.getFilters())));
        }
        DockerResponse response = connection.request();
        final int status = response.getStatus();
        if (OK.getStatusCode() != status) {
            throw getDockerException(response);
        }
        return parseResponseStreamAndClose(response.getInputStream(), new TypeToken<List<ContainerListEntry>>() {
        });
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) Filters(org.eclipse.che.plugin.docker.client.json.Filters) DockerResponse(org.eclipse.che.plugin.docker.client.connection.DockerResponse) List(java.util.List)

Example 17 with DockerResponse

use of org.eclipse.che.plugin.docker.client.connection.DockerResponse in project che by eclipse.

the class DockerConnector method buildImage.

private String buildImage(final DockerConnection dockerConnection, final BuildImageParams params, final ProgressMonitor progressMonitor) throws IOException {
    final String repository = params.getRepository();
    try (DockerConnection connection = dockerConnection.method("POST").path(apiVersionPathPrefix + "/build").header("X-Registry-Config", authResolver.getXRegistryConfigHeaderValue(params.getAuthConfigs()))) {
        addQueryParamIfNotNull(connection, "rm", params.isRemoveIntermediateContainer());
        addQueryParamIfNotNull(connection, "forcerm", params.isForceRemoveIntermediateContainers());
        addQueryParamIfNotNull(connection, "memory", params.getMemoryLimit());
        addQueryParamIfNotNull(connection, "memswap", params.getMemorySwapLimit());
        addQueryParamIfNotNull(connection, "pull", params.isDoForcePull());
        addQueryParamIfNotNull(connection, "dockerfile", params.getDockerfile());
        addQueryParamIfNotNull(connection, "nocache", params.isNoCache());
        addQueryParamIfNotNull(connection, "q", params.isQuiet());
        addQueryParamIfNotNull(connection, "cpusetcpus", params.getCpusetCpus());
        addQueryParamIfNotNull(connection, "cpuperiod", params.getCpuPeriod());
        addQueryParamIfNotNull(connection, "cpuquota", params.getCpuQuota());
        if (params.getTag() == null) {
            addQueryParamIfNotNull(connection, "t", repository);
        } else {
            addQueryParamIfNotNull(connection, "t", repository == null ? null : repository + ':' + params.getTag());
        }
        if (params.getBuildArgs() != null) {
            addQueryParamIfNotNull(connection, "buildargs", URLEncoder.encode(GSON.toJson(params.getBuildArgs()), "UTF-8"));
        }
        final DockerResponse response = connection.request();
        if (OK.getStatusCode() != response.getStatus()) {
            throw getDockerException(response);
        }
        try (InputStream responseStream = response.getInputStream()) {
            JsonMessageReader<ProgressStatus> progressReader = new JsonMessageReader<>(responseStream, ProgressStatus.class);
            // Here do some trick to be able interrupt output streaming process.
            // Current unix socket implementation of DockerConnection doesn't react to interruption.
            // So to be able to close unix socket connection and free resources we use main thread.
            // In case of any exception main thread cancels future and close connection.
            // If Docker connection implementation supports interrupting it will stop streaming on interruption,
            // if not it will be stopped by closure of unix socket
            Future<String> imageIdFuture = executor.submit(() -> {
                ProgressStatus progressStatus;
                while ((progressStatus = progressReader.next()) != null) {
                    if (progressStatus.getError() != null) {
                        String errorMessage = progressStatus.getError();
                        if (errorMessage.matches("Error: image .+ not found")) {
                            throw new ImageNotFoundException(errorMessage);
                        }
                    }
                    final String buildImageId = getBuildImageId(progressStatus);
                    if (buildImageId != null) {
                        return buildImageId;
                    }
                    progressMonitor.updateProgress(progressStatus);
                }
                throw new DockerException("Docker image build failed. Image id not found in build output.", 500);
            });
            return imageIdFuture.get();
        } catch (ExecutionException e) {
            // unwrap exception thrown by task with .getCause()
            if (e.getCause() instanceof ImageNotFoundException) {
                throw new ImageNotFoundException(e.getCause().getLocalizedMessage());
            } else {
                throw new DockerException(e.getCause().getLocalizedMessage(), 500);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new DockerException("Docker image build was interrupted", 500);
        }
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) DockerException(org.eclipse.che.plugin.docker.client.exception.DockerException) ProgressStatus(org.eclipse.che.plugin.docker.client.json.ProgressStatus) DockerResponse(org.eclipse.che.plugin.docker.client.connection.DockerResponse) BufferedInputStream(java.io.BufferedInputStream) CloseConnectionInputStream(org.eclipse.che.plugin.docker.client.connection.CloseConnectionInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ImageNotFoundException(org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException) ExecutionException(java.util.concurrent.ExecutionException)

Example 18 with DockerResponse

use of org.eclipse.che.plugin.docker.client.connection.DockerResponse in project che by eclipse.

the class DockerConnector method top.

/**
     * List processes running inside the container.
     *
     * @return processes running inside the container
     * @throws IOException
     *          when a problem occurs with docker api calls
     */
public ContainerProcesses top(final TopParams params) throws IOException {
    final String[] psArgs = params.getPsArgs();
    try (final DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("GET").path(apiVersionPathPrefix + "/containers/" + params.getContainer() + "/top")) {
        if (psArgs != null && psArgs.length != 0) {
            StringBuilder psArgsQueryBuilder = new StringBuilder();
            for (int i = 0, l = psArgs.length; i < l; i++) {
                if (i > 0) {
                    psArgsQueryBuilder.append('+');
                }
                psArgsQueryBuilder.append(URLEncoder.encode(psArgs[i], "UTF-8"));
            }
            connection.query("ps_args", psArgsQueryBuilder.toString());
        }
        final DockerResponse response = connection.request();
        if (OK.getStatusCode() != response.getStatus()) {
            throw getDockerException(response);
        }
        return parseResponseStreamAndClose(response.getInputStream(), ContainerProcesses.class);
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) DockerResponse(org.eclipse.che.plugin.docker.client.connection.DockerResponse)

Example 19 with DockerResponse

use of org.eclipse.che.plugin.docker.client.connection.DockerResponse in project che by eclipse.

the class DockerConnector method push.

/**
     * Push docker image to the registry.
     *
     * @param progressMonitor
     *         ProgressMonitor for images pushing process
     * @return digest of just pushed image
     * @throws IOException
     *          when a problem occurs with docker api calls
     */
public String push(final PushParams params, final ProgressMonitor progressMonitor) throws IOException {
    final String fullRepo = params.getFullRepo();
    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("POST").path(apiVersionPathPrefix + "/images/" + fullRepo + "/push").header("X-Registry-Auth", authResolver.getXRegistryAuthHeaderValue(params.getRegistry(), params.getAuthConfigs()))) {
        addQueryParamIfNotNull(connection, "tag", params.getTag());
        final DockerResponse response = connection.request();
        if (OK.getStatusCode() != response.getStatus()) {
            throw getDockerException(response);
        }
        try (InputStream responseStream = response.getInputStream()) {
            JsonMessageReader<ProgressStatus> progressReader = new JsonMessageReader<>(responseStream, ProgressStatus.class);
            // Here do some trick to be able interrupt output streaming process.
            // Current unix socket implementation of DockerConnection doesn't react to interruption.
            // So to be able to close unix socket connection and free resources we use main thread.
            // In case of any exception main thread cancels future and close connection.
            // If Docker connection implementation supports interrupting it will stop streaming on interruption,
            // if not it will be stopped by closure of unix socket
            Future<String> digestFuture = executor.submit(() -> {
                String digestPrefix = firstNonNull(params.getTag(), "latest") + ": digest: ";
                ProgressStatus progressStatus;
                while ((progressStatus = progressReader.next()) != null) {
                    progressMonitor.updateProgress(progressStatus);
                    if (progressStatus.getError() != null) {
                        throw new DockerException(progressStatus.getError(), 500);
                    }
                    String status = progressStatus.getStatus();
                    // latest: digest: sha256:9a70e6222ded459fde37c56af23887467c512628eb8e78c901f3390e49a800a0 size: 62189
                    if (status != null && status.startsWith(digestPrefix)) {
                        return status.substring(digestPrefix.length(), status.indexOf(" ", digestPrefix.length()));
                    }
                }
                LOG.error("Docker image {}:{} was successfully pushed, but its digest wasn't obtained", fullRepo, firstNonNull(params.getTag(), "latest"));
                throw new DockerException("Docker push response doesn't contain image digest", 500);
            });
            return digestFuture.get();
        } catch (ExecutionException e) {
            // unwrap exception thrown by task with .getCause()
            throw new DockerException("Docker image pushing failed. Cause: " + e.getCause().getLocalizedMessage(), 500);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new DockerException("Docker image pushing was interrupted", 500);
        }
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) DockerException(org.eclipse.che.plugin.docker.client.exception.DockerException) ProgressStatus(org.eclipse.che.plugin.docker.client.json.ProgressStatus) DockerResponse(org.eclipse.che.plugin.docker.client.connection.DockerResponse) BufferedInputStream(java.io.BufferedInputStream) CloseConnectionInputStream(org.eclipse.che.plugin.docker.client.connection.CloseConnectionInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ExecutionException(java.util.concurrent.ExecutionException)

Example 20 with DockerResponse

use of org.eclipse.che.plugin.docker.client.connection.DockerResponse in project che by eclipse.

the class DockerConnector method removeContainer.

/**
     * Removes docker container.
     *
     * @throws IOException
     *          when a problem occurs with docker api calls
     */
public void removeContainer(final RemoveContainerParams params) throws IOException {
    try (DockerConnection connection = connectionFactory.openConnection(dockerDaemonUri).method("DELETE").path(apiVersionPathPrefix + "/containers/" + params.getContainer())) {
        addQueryParamIfNotNull(connection, "force", params.isForce());
        addQueryParamIfNotNull(connection, "v", params.isRemoveVolumes());
        final DockerResponse response = connection.request();
        if (NO_CONTENT.getStatusCode() != response.getStatus()) {
            throw getDockerException(response);
        }
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) DockerResponse(org.eclipse.che.plugin.docker.client.connection.DockerResponse)

Aggregations

DockerConnection (org.eclipse.che.plugin.docker.client.connection.DockerConnection)22 DockerResponse (org.eclipse.che.plugin.docker.client.connection.DockerResponse)22 CloseConnectionInputStream (org.eclipse.che.plugin.docker.client.connection.CloseConnectionInputStream)9 BufferedInputStream (java.io.BufferedInputStream)8 FileInputStream (java.io.FileInputStream)8 InputStream (java.io.InputStream)8 DockerException (org.eclipse.che.plugin.docker.client.exception.DockerException)4 ExecutionException (java.util.concurrent.ExecutionException)3 ProgressStatus (org.eclipse.che.plugin.docker.client.json.ProgressStatus)3 ImageNotFoundException (org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException)2 Filters (org.eclipse.che.plugin.docker.client.json.Filters)2 File (java.io.File)1 IOException (java.io.IOException)1 Path (java.nio.file.Path)1 List (java.util.List)1 ContainerNotFoundException (org.eclipse.che.plugin.docker.client.exception.ContainerNotFoundException)1 NetworkNotFoundException (org.eclipse.che.plugin.docker.client.exception.NetworkNotFoundException)1 ContainerCommitted (org.eclipse.che.plugin.docker.client.json.ContainerCommitted)1 ExecConfig (org.eclipse.che.plugin.docker.client.json.ExecConfig)1 ExecStart (org.eclipse.che.plugin.docker.client.json.ExecStart)1