Search in sources :

Example 16 with DockerConnection

use of org.eclipse.che.plugin.docker.client.connection.DockerConnection 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 DockerConnection

use of org.eclipse.che.plugin.docker.client.connection.DockerConnection 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 DockerConnection

use of org.eclipse.che.plugin.docker.client.connection.DockerConnection 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 DockerConnection

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

the class DockerConnector method buildImage.

/**
     * Builds new image.
     *
     * @param progressMonitor
     *         ProgressMonitor for images creation process
     * @return image id
     * @throws IOException
     */
public String buildImage(final BuildImageParams params, final ProgressMonitor progressMonitor) throws IOException {
    if (params.getRemote() != null) {
        // build context provided by remote URL
        DockerConnection dockerConnection = connectionFactory.openConnection(dockerDaemonUri).query("remote", params.getRemote());
        return buildImage(dockerConnection, params, progressMonitor);
    }
    // build context is set of files
    final File tar = Files.createTempFile(null, ".tar").toFile();
    try {
        File[] files = new File[params.getFiles().size()];
        files = params.getFiles().toArray(files);
        createTarArchive(tar, files);
        try (InputStream tarInput = new FileInputStream(tar)) {
            DockerConnection dockerConnection = connectionFactory.openConnection(dockerDaemonUri).header("Content-Type", "application/x-compressed-tar").header("Content-Length", tar.length()).entity(tarInput);
            return buildImage(dockerConnection, params, progressMonitor);
        }
    } finally {
        FileCleaner.addFile(tar);
    }
}
Also used : DockerConnection(org.eclipse.che.plugin.docker.client.connection.DockerConnection) BufferedInputStream(java.io.BufferedInputStream) CloseConnectionInputStream(org.eclipse.che.plugin.docker.client.connection.CloseConnectionInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 20 with DockerConnection

use of org.eclipse.che.plugin.docker.client.connection.DockerConnection 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)

Aggregations

DockerConnection (org.eclipse.che.plugin.docker.client.connection.DockerConnection)23 DockerResponse (org.eclipse.che.plugin.docker.client.connection.DockerResponse)22 CloseConnectionInputStream (org.eclipse.che.plugin.docker.client.connection.CloseConnectionInputStream)10 BufferedInputStream (java.io.BufferedInputStream)9 FileInputStream (java.io.FileInputStream)9 InputStream (java.io.InputStream)9 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 File (java.io.File)2 ImageNotFoundException (org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException)2 Filters (org.eclipse.che.plugin.docker.client.json.Filters)2 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