com.github.dockerjava.api.exception.DockerClientException Java Examples

The following examples show how to use com.github.dockerjava.api.exception.DockerClientException. 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: DefaultDockerClientConfig.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private String checkDockerCertPath(String dockerCertPath) {
    if (StringUtils.isEmpty(dockerCertPath)) {
        throw new DockerClientException(
                "Enabled TLS verification (DOCKER_TLS_VERIFY=1) but certifate path (DOCKER_CERT_PATH) is not defined.");
    }

    File certPath = new File(dockerCertPath);

    if (!certPath.exists()) {
        throw new DockerClientException(
                "Enabled TLS verification (DOCKER_TLS_VERIFY=1) but certificate path (DOCKER_CERT_PATH) '"
                        + dockerCertPath + "' doesn't exist.");
    } else if (!certPath.isDirectory()) {
        throw new DockerClientException(
                "Enabled TLS verification (DOCKER_TLS_VERIFY=1) but certificate path (DOCKER_CERT_PATH) '"
                        + dockerCertPath + "' doesn't point to a directory.");
    }

    return dockerCertPath;
}
 
Example #2
Source File: DockerBuilderControlOptionRun.java    From docker-plugin with MIT License 6 votes vote down vote up
private void executeOnDocker(Run<?, ?> build, PrintStream llog, String xImage, String xCommand, String xHostname, String xUser, DockerClient client)
        throws DockerException {
    try {
        client.inspectImageCmd(xImage).exec();
    } catch (NotFoundException e) {
        throw new DockerClientException("Failed to pull image: " + image, e);
    }

    DockerTemplateBase template = new DockerSimpleTemplate(
            xImage, pullCredentialsId, dnsString, network, xCommand, volumesString, volumesFrom,
            environmentsString, xHostname, xUser, extraGroupsString, memoryLimit, memorySwap, cpuShares,
            shmSize, bindPorts, bindAllPorts, privileged, tty, macAddress, null);

    LOG.info("Starting container for image {}", xImage);
    llog.println("Starting container for image " + xImage);
    String containerId = DockerCloud.runContainer(template, client);

    LOG.info("Started container {}", containerId);
    llog.println("Started container " + containerId);

    getLaunchAction(build).started(client, containerId);
}
 
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: NettyInvocationBuilder.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private void postChunkedStreamRequest(HttpRequestProvider requestProvider, Channel channel, InputStream body) {
    HttpRequest request = requestProvider.getHttpRequest(resource);

    // don't accept FullHttpRequest here
    if (request instanceof FullHttpRequest) {
        throw new DockerClientException("fatal: request is instance of FullHttpRequest");
    }

    request.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    request.headers().remove(HttpHeaderNames.CONTENT_LENGTH);

    channel.write(request);

    channel.write(new ChunkedStream(new BufferedInputStream(body, 1024 * 1024), 1024 * 1024));
    channel.write(LastHttpContent.EMPTY_LAST_CONTENT);
    channel.flush();
}
 
Example #5
Source File: PullImageResultCallback.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private void checkDockerSwarmPullSuccessful() {
    if (results.isEmpty()) {
        throw new DockerClientException("Could not pull image through Docker Swarm");
    } else {
        boolean pullFailed = false;
        StringBuilder sb = new StringBuilder();

        for (PullResponseItem pullResponseItem : results.values()) {
            if (!pullResponseItem.isPullSuccessIndicated()) {
                pullFailed = true;
                sb.append("[" + pullResponseItem.getId() + ":" + messageFromPullResult(pullResponseItem) + "]");
            }
        }

        if (pullFailed) {
            throw new DockerClientException("Could not pull image: " + sb.toString());
        }
    }
}
 
Example #6
Source File: Dockerfile.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all matching ignore patterns for the given file name.
 */
private List<String> matchingIgnorePatterns(String fileName) {
    List<String> matches = new ArrayList<>();

    int lineNumber = 0;
    for (String pattern : ignores) {
        String goLangPattern = pattern.startsWith("!") ? pattern.substring(1) : pattern;
        lineNumber++;
        try {
            if (GoLangFileMatch.match(goLangPattern, fileName)) {
                matches.add(pattern);
            }
        } catch (GoLangFileMatchException e) {
            throw new DockerClientException(String.format(
                    "Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber));
        }
    }

    return matches;
}
 
Example #7
Source File: Dockerfile.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * Adds all files found in <code>directory</code> and subdirectories to
 * <code>filesToAdd</code> collection. It also adds any empty directories
 * if found.
 *
 * @param directory directory
 * @throws DockerClientException when IO error occurs
 */
private void addFilesInDirectory(File directory) {
    File[] files = directory.listFiles();

    if (files == null) {
        throw new DockerClientException("Failed to read build context directory: " + baseDirectory.getAbsolutePath());
    }

    if (files.length != 0) {
        for (File f : files) {
            if (f.isDirectory()) {
                addFilesInDirectory(f);
            } else if (effectiveMatchingIgnorePattern(f) == null) {
                filesToAdd.add(f);
            }
        }
        // base directory should at least contains Dockerfile, but better check
    } else if (!isBaseDirectory(directory)) {
        // add empty directory
        filesToAdd.add(directory);
    }
}
 
Example #8
Source File: Dockerfile.java    From docker-java with Apache License 2.0 6 votes vote down vote up
public List<String> getIgnores() throws IOException {
    List<String> ignores = new ArrayList<>();
    File dockerIgnoreFile = new File(baseDirectory, ".dockerignore");
    if (dockerIgnoreFile.exists()) {
        int lineNumber = 0;
        List<String> dockerIgnoreFileContent = FileUtils.readLines(dockerIgnoreFile);
        for (String pattern : dockerIgnoreFileContent) {
            lineNumber++;
            pattern = pattern.trim();
            if (pattern.isEmpty()) {
                continue; // skip empty lines
            }
            pattern = FilenameUtils.normalize(pattern);
            try {
                ignores.add(pattern);
            } catch (GoLangFileMatchException e) {
                throw new DockerClientException(String.format(
                        "Invalid pattern '%s' on line %s in .dockerignore file", pattern, lineNumber));
            }
        }
    }
    return ignores;
}
 
Example #9
Source File: PushImageCmd.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
default ResultCallback.Adapter<PushResponseItem> start() {
    return exec(new ResultCallback.Adapter<PushResponseItem>() {

        @Nullable
        private PushResponseItem latestItem = null;

        @Override
        public void onNext(PushResponseItem item) {
            this.latestItem = item;
        }

        @Override
        protected void throwFirstError() {
            super.throwFirstError();

            if (latestItem == null) {
                throw new DockerClientException("Could not push image");
            } else if (latestItem.isErrorIndicated()) {
                throw new DockerClientException("Could not push image: " + latestItem.getError());
            }
        }
    });
}
 
Example #10
Source File: PullImageResultCallback.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private void checkDockerSwarmPullSuccessful() {
    if (results.isEmpty()) {
        throw new DockerClientException("Could not pull image through Docker Swarm");
    } else {
        boolean pullFailed = false;
        StringBuilder sb = new StringBuilder();

        for (PullResponseItem pullResponseItem : results.values()) {
            if (!pullResponseItem.isPullSuccessIndicated()) {
                pullFailed = true;
                sb.append("[" + pullResponseItem.getId() + ":" + messageFromPullResult(pullResponseItem) + "]");
            }
        }

        if (pullFailed) {
            throw new DockerClientException("Could not pull image: " + sb.toString());
        }
    }
}
 
Example #11
Source File: PushImageCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPushImageWithInvalidAuth() throws Exception {
    AuthConfig invalidAuthConfig = new AuthConfig()
            .withUsername("testuser")
            .withPassword("testwrongpassword")
            .withEmail("[email protected]")
            .withRegistryAddress(authConfig.getRegistryAddress());

    String imgName = REGISTRY.createTestImage("push-image-with-invalid-auth");

    exception.expect(DockerClientException.class);

    // stream needs to be fully read in order to close the underlying connection
    dockerRule.getClient().pushImageCmd(imgName)
            .withAuthConfig(invalidAuthConfig)
            .start()
            .awaitCompletion(30, TimeUnit.SECONDS);
}
 
Example #12
Source File: WaitContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWaitContainerTimeout() throws Exception {

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "10").exec();

    LOG.info("Created container: {}", container.toString());
    assertThat(container.getId(), not(is(emptyString())));

    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    WaitContainerResultCallback callback = dockerRule.getClient().waitContainerCmd(container.getId()).exec(
            new WaitContainerResultCallback());
    try {
        callback.awaitStatusCode(100, TimeUnit.MILLISECONDS);
        throw new AssertionError("Should throw exception on timeout.");
    } catch (DockerClientException e) {
        LOG.info(e.getMessage());
    }
}
 
Example #13
Source File: Docker.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public String getContainerId() {
  try {

    BufferedReader br =
        Files.newBufferedReader(Paths.get("/proc/self/cgroup"), StandardCharsets.UTF_8);

    String line = null;
    while ((line = br.readLine()) != null) {
      log.debug(line);
      if (line.contains("docker")) {
        return line.substring(line.lastIndexOf('/') + 1, line.length());
      }
    }

    throw new DockerClientException("Exception obtaining containerId. "
        + "The file /proc/self/cgroup doesn't contain a line with 'docker'");

  } catch (IOException e) {
    throw new DockerClientException(
        "Exception obtaining containerId. " + "Exception reading file /proc/self/cgroup", e);
  }
}
 
Example #14
Source File: PullImageCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPullImageWithInvalidAuth() throws Exception {
    AuthConfig authConfig = REGISTRY.getAuthConfig();
    AuthConfig invalidAuthConfig = new AuthConfig()
            .withUsername("testuser")
            .withPassword("testwrongpassword")
            .withEmail("[email protected]")
            .withRegistryAddress(authConfig.getRegistryAddress());

    String imgName = REGISTRY.createPrivateImage("pull-image-with-invalid-auth");

    if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
            .isGreaterOrEqual(RemoteApiVersion.VERSION_1_30)) {
        exception.expect(DockerException.class);
    } else {
        exception.expect(DockerClientException.class);
    }

    // stream needs to be fully read in order to close the underlying connection
    dockerRule.getClient().pullImageCmd(imgName)
            .withAuthConfig(invalidAuthConfig)
            .start()
            .awaitCompletion(30, TimeUnit.SECONDS);
}
 
Example #15
Source File: PullImageCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPullImageWithNoAuth() throws Exception {
    AuthConfig authConfig = REGISTRY.getAuthConfig();

    String imgName = REGISTRY.createPrivateImage("pull-image-with-no-auth");

    if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
            .isGreaterOrEqual(RemoteApiVersion.VERSION_1_30)) {
        exception.expect(DockerException.class);
    } else {
        exception.expect(DockerClientException.class);
    }

    // stream needs to be fully read in order to close the underlying connection
    dockerRule.getClient().pullImageCmd(imgName)
            .start()
            .awaitCompletion(30, TimeUnit.SECONDS);
}
 
Example #16
Source File: WaitContainerResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Awaits the status code from the container.
 *
 * @throws DockerClientException
 *             if the wait operation fails.
 */
public Integer awaitStatusCode() {
    try {
        awaitCompletion();
    } catch (InterruptedException e) {
        throw new DockerClientException("", e);
    }

    return getStatusCode();
}
 
Example #17
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public Map<String, ContainerNetwork> getContainerNetworks() {
    if (isRunningInContainer()) {
        Map<String, ContainerNetwork> networks = inspectContainer(getContainerName()).getNetworkSettings()
            .getNetworks();
        log.trace("Docker container networks {}", networks);
        return networks;
    } else {
        throw new DockerClientException(
            "Can't obtain container ip address if not running in container");
    }
}
 
Example #18
Source File: DockerfileStatement.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Createa an Add if it matches, or missing if not.
 *
 * @param statement
 *            statement that may be an ADD or a COPY
 * @return optional typed item.
 */
public static Optional<Add> create(String statement) {
    Matcher argumentMatcher = ARGUMENT_TOKENIZER.matcher(statement.trim());

    if (!argumentMatcher.find()) {
        return Optional.absent();
    }

    String commandName = argumentMatcher.group();
    if (!(StringUtils.equals(commandName, "ADD") || StringUtils.equals(commandName, "COPY"))) {
        return Optional.absent();
    }

    String lastToken = null;
    Collection<String> sources = new ArrayList<>();

    while (argumentMatcher.find()) {
        if (lastToken != null) {
            sources.add(lastToken);
        }
        lastToken = argumentMatcher.group().replaceAll("(^\")|(\"$)", "");
    }

    if (sources.isEmpty()) {
        throw new DockerClientException("Wrong ADD or COPY format");
    }

    return Optional.of(new Add(sources, lastToken));
}
 
Example #19
Source File: DockerfileStatement.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public static Optional<Env> create(String statement) {
    Matcher matcher = ENV_PATTERN.matcher(statement.trim());
    if (!matcher.find()) {
        return Optional.absent();
    }

    if (matcher.groupCount() != 2) {
        throw new DockerClientException("Wrong ENV format");
    }

    return Optional.of(new Env(matcher));
}
 
Example #20
Source File: FilePathUtil.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Return the relative path. Path elements are separated with / char.
 *
 * @param baseDir
 *            a parent directory of {@code file}
 * @param file
 *            the file to get the relative path
 * @return the relative path
 */
public static String relativize(File baseDir, File file) {
    try {
        baseDir = baseDir.getCanonicalFile();
        file = file.getCanonicalFile();

        return baseDir.toURI().relativize(file.toURI()).getPath();
    } catch (IOException e) {
        throw new DockerClientException(e.getMessage(), e);
    }
}
 
Example #21
Source File: BuildImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Awaits the image id from the response stream.
 *
 * @throws DockerClientException
 *             if the build fails.
 */
public String awaitImageId() {
    try {
        awaitCompletion();
    } catch (InterruptedException e) {
        throw new DockerClientException("", e);
    }

    return getImageId();
}
 
Example #22
Source File: BuildImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Awaits the image id from the response stream.
 *
 * @throws DockerClientException
 *             if the build fails or the timeout occurs.
 */
public String awaitImageId(long timeout, TimeUnit timeUnit) {
    try {
        awaitCompletion(timeout, timeUnit);
    } catch (InterruptedException e) {
        throw new DockerClientException("Awaiting image id interrupted: ", e);
    }

    return getImageId();
}
 
Example #23
Source File: BuildImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private String getImageId() {
    if (imageId != null) {
        return imageId;
    }

    if (error == null) {
        throw new DockerClientException("Could not build image");
    }

    throw new DockerClientException("Could not build image: " + error);
}
 
Example #24
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public String getContainerIpAddress() {
  if (isRunningInContainer()) {
    String ipAddr = getContainerNetworks().values().iterator().next().getIpAddress();
    log.trace("Docker container IP address {}", ipAddr);
    return ipAddr;
  } else {
    throw new DockerClientException(
        "Can't obtain container ip address if not running in container");
  }
}
 
Example #25
Source File: PullImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private void checkDockerClientPullSuccessful() {
    if (latestItem == null) {
        throw new DockerClientException("Could not pull image");
    } else if (!latestItem.isPullSuccessIndicated()) {
        throw new DockerClientException("Could not pull image: " + messageFromPullResult(latestItem));
    }
}
 
Example #26
Source File: PullImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Awaits the image to be pulled successful.
 *
 * @deprecated use {@link #awaitCompletion()} or {@link #awaitCompletion(long, TimeUnit)} instead
 * @throws DockerClientException
 *             if the pull fails.
 */
public void awaitSuccess() {
    try {
        awaitCompletion();
    } catch (InterruptedException e) {
        throw new DockerClientException("", e);
    }
}
 
Example #27
Source File: PushImageCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void pushNonExistentImage() throws Exception {

    if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
            .isGreaterOrEqual(RemoteApiVersion.VERSION_1_24)) {
        exception.expect(DockerClientException.class);
    } else {
        exception.expect(NotFoundException.class);
    }

    dockerRule.getClient().pushImageCmd(UUID.randomUUID().toString().replace("-", ""))
            .start()
            .awaitCompletion(30, TimeUnit.SECONDS); // exclude infinite await sleep

}
 
Example #28
Source File: WaitContainerResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Awaits the status code from the container.
 *
 * @throws DockerClientException
 *             if the wait operation fails.
 */
public Integer awaitStatusCode(long timeout, TimeUnit timeUnit) {
    try {
        if (!awaitCompletion(timeout, timeUnit)) {
            throw new DockerClientException("Awaiting status code timeout.");
        }
    } catch (InterruptedException e) {
        throw new DockerClientException("Awaiting status code interrupted: ", e);
    }

    return getStatusCode();
}
 
Example #29
Source File: WaitContainerResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private Integer getStatusCode() {
    if (waitResponse == null) {
        throw new DockerClientException("Error while wait container");
    } else {
        return waitResponse.getStatusCode();
    }
}
 
Example #30
Source File: PushImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void throwFirstError() {
    super.throwFirstError();

    if (latestItem == null) {
        throw new DockerClientException("Could not push image");
    } else if (latestItem.isErrorIndicated()) {
        throw new DockerClientException("Could not push image: " + latestItem.getError());
    }
}