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

The following examples show how to use com.github.dockerjava.api.exception.NotFoundException. 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: 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 #2
Source File: DockerfileFixture.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws Exception {

    if (containerId != null) {
        LOGGER.info("removing container {}", containerId);
        try {
            client.removeContainerCmd(containerId).withForce(true) // stop too
                    .exec();
        } catch (NotFoundException | InternalServerErrorException ignored) {
            LOGGER.info("ignoring {}", ignored.getMessage());
        }
        containerId = null;
    }

    if (repository != null) {
        LOGGER.info("removing repository {}", repository);
        try {
            client.removeImageCmd(repository).withForce(true).exec();
        } catch (DockerException e) {
            LOGGER.info("ignoring {}", e.getMessage());
        }
        repository = null;
    }
}
 
Example #3
Source File: ExecStartCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = NotFoundException.class)
public void execStartWithNonExistentUser() throws Exception {
    String containerName = "generated_" + new SecureRandom().nextInt();

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("sleep", "9999")
            .withName(containerName).exec();
    LOG.info("Created container {}", container.toString());
    assertThat(container.getId(), not(is(emptyString())));

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

    ExecCreateCmdResponse execCreateCmdResponse = dockerRule.getClient().execCreateCmd(container.getId())
            .withAttachStdout(true).withCmd("touch", "/execStartTest.log").withUser("NonExistentUser").exec();
    dockerRule.getClient().execStartCmd(execCreateCmdResponse.getId()).withDetach(false).withTty(true)
            .exec(new ExecStartResultCallback(System.out, System.err)).awaitCompletion();

    dockerRule.getClient().copyArchiveFromContainerCmd(container.getId(), "/execStartTest.log").exec();
}
 
Example #4
Source File: RemoveVolumeCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = NotFoundException.class)
public void removeVolume() throws DockerException {

    String volumeName = "volume1" + dockerRule.getKind();

    CreateVolumeResponse createVolumeResponse = dockerRule.getClient().createVolumeCmd()
            .withName(volumeName)
            .withDriver("local")
            .withLabels(Collections.singletonMap("is-timelord", "yes")).exec();

    assertThat(createVolumeResponse.getName(), equalTo(volumeName));
    assertThat(createVolumeResponse.getDriver(), equalTo("local"));
    assertThat(createVolumeResponse.getLabels(), equalTo(Collections.singletonMap("is-timelord", "yes")));
    assertThat(createVolumeResponse.getMountpoint(), containsString(volumeName));

    dockerRule.getClient().removeVolumeCmd(volumeName).exec();

    dockerRule.getClient().inspectVolumeCmd(volumeName).exec();
}
 
Example #5
Source File: ResponseStatusExceptionFilter.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    int status = responseContext.getStatus();
    switch (status) {
        case 200:
        case 201:
        case 204:
            return;
        case 304:
            throw new NotModifiedException(getBodyAsMessage(responseContext));
        case 400:
            throw new BadRequestException(getBodyAsMessage(responseContext));
        case 401:
            throw new UnauthorizedException(getBodyAsMessage(responseContext));
        case 404:
            throw new NotFoundException(getBodyAsMessage(responseContext));
        case 406:
            throw new NotAcceptableException(getBodyAsMessage(responseContext));
        case 409:
            throw new ConflictException(getBodyAsMessage(responseContext));
        case 500:
            throw new InternalServerErrorException(getBodyAsMessage(responseContext));
        default:
            throw new DockerException(getBodyAsMessage(responseContext), status);
    }
}
 
Example #6
Source File: ImagePullPolicyTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
private void expectToFailWithNotFoundException(GenericContainer<?> container) {
    try {
        container.start();
        fail("Should fail");
    } catch (ContainerLaunchException e) {
        Throwable throwable = e;
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
            if (throwable.getCause() instanceof NotFoundException) {
                VisibleAssertions.pass("Caused by NotFoundException");
                return;
            }
        }
        VisibleAssertions.fail("Caused by NotFoundException");
    }
}
 
Example #7
Source File: DockerClientFactory.java    From testcontainers-java with MIT License 6 votes vote down vote up
private <T> T runInsideDocker(DockerClient client, Consumer<CreateContainerCmd> createContainerCmdConsumer, BiFunction<DockerClient, String, T> block) {
    checkAndPullImage(client, TINY_IMAGE);
    CreateContainerCmd createContainerCmd = client.createContainerCmd(TINY_IMAGE)
            .withLabels(DEFAULT_LABELS);
    createContainerCmdConsumer.accept(createContainerCmd);
    String id = createContainerCmd.exec().getId();

    try {
        client.startContainerCmd(id).exec();
        return block.apply(client, id);
    } finally {
        try {
            client.removeContainerCmd(id).withRemoveVolumes(true).withForce(true).exec();
        } catch (NotFoundException | InternalServerErrorException e) {
            log.debug("Swallowed exception while removing container", e);
        }
    }
}
 
Example #8
Source File: ContainerUtil.java    From presto with Apache License 2.0 6 votes vote down vote up
public static void killContainers(DockerClient dockerClient, Function<ListContainersCmd, ListContainersCmd> filter)
{
    while (true) {
        ListContainersCmd listContainersCmd = filter.apply(dockerClient.listContainersCmd()
                .withShowAll(true));

        List<Container> containers = listContainersCmd.exec();
        if (containers.isEmpty()) {
            break;
        }
        for (Container container : containers) {
            try {
                dockerClient.removeContainerCmd(container.getId())
                        .withForce(true)
                        .exec();
            }
            catch (ConflictException | NotFoundException ignored) {
            }
        }
    }
}
 
Example #9
Source File: TagImageCommand.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws DockerException {
	if (image == null || image.isEmpty()) {
		throw new IllegalArgumentException("Please provide an image name");
	} else if (repository == null || repository.isEmpty()) {
		throw new IllegalArgumentException("Please provide a repository");
	} else if (tag == null || tag.isEmpty()) {
		throw new IllegalArgumentException("Please provide a tag for the image");
	}
	DockerClient client = getClient();
	try {
		logger.debug("start tagging image " + image + " in " + repository + " as " + tag);
		client.tagImageCmd(image, repository, tag).withForce(withForce).exec();
		logger.debug("Tagged image " + image + " in " + repository + " as " + tag);
	} catch (NotFoundException e) {
		if (!ignoreIfNotFound) {
			logger.error(String.format("image '%s' not found ", image));
			throw e;
		} else {
			logger.error(String.format(
					"image '%s' not found, but skipping this error is turned on, let's continue ... ", image));
		}
	}
}
 
Example #10
Source File: DockerTestUtils.java    From module-ballerina-docker with Apache License 2.0 6 votes vote down vote up
/**
 * Stop and remove a running container.
 *
 * @param containerID The container ID.
 */
public static void stopContainer(String containerID) {
    try {
        InspectContainerResponse containerInfo = getDockerClient().inspectContainerCmd(containerID).exec();
        if ((null != containerInfo.getState().getRestarting() && containerInfo.getState().getRestarting()) ||
                (null != containerInfo.getState().getPaused() && containerInfo.getState().getPaused()) ||
                (null != containerInfo.getState().getRunning() && containerInfo.getState().getRunning())) {
            log.info("Stopping container: " + containerID);
            getDockerClient().stopContainerCmd(containerID).exec();
        }
        log.info("Removing container: " + containerID);
        getDockerClient().removeContainerCmd(containerID).exec();
    } catch (NotFoundException | NotModifiedException e) {
        // ignore
    }
}
 
Example #11
Source File: DefaultDockerClientIT.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void ensureContainerIsNotPresent() {
    try {
        String imageToRemove = dockerClient.inspectImageCmd(WANTED_IMAGE).exec().getId();
        dockerClient.removeImageCmd(imageToRemove).exec();
    } catch (NotFoundException e) {
        // not found, no problems
    }
}
 
Example #12
Source File: PullImageCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPullNonExistingImage() throws Exception {
    if (isNotSwarm(dockerRule.getClient()) && getVersion(dockerRule.getClient())
            .isGreaterOrEqual(RemoteApiVersion.VERSION_1_26)) {
        exception.expect(NotFoundException.class);
    } else {
        exception.expect(DockerClientException.class);
    }

    // stream needs to be fully read in order to close the underlying connection
    dockerRule.getClient().pullImageCmd("xvxcv/foo")
            .start()
            .awaitCompletion(30, TimeUnit.SECONDS);
}
 
Example #13
Source File: DockerImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<ContainerStats> getContainerStats(ContainerName containerName) {
    try {
        DockerStatsCallback statsCallback = dockerClient.statsCmd(containerName.asString()).exec(new DockerStatsCallback());
        statsCallback.awaitCompletion(5, TimeUnit.SECONDS);

        return statsCallback.stats.map(ContainerStats::new);
    } catch (NotFoundException ignored) {
        return Optional.empty();
    } catch (RuntimeException | InterruptedException e) {
        numberOfDockerApiFails.increment();
        throw new DockerException("Failed to get stats for container '" + containerName.asString() + "'", e);
    }
}
 
Example #14
Source File: CopyArchiveToContainerCmdImpl.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * @throws com.github.dockerjava.api.exception.NotFoundException
 *             No such container
 */
@Override
public Void exec() throws NotFoundException {
    if (StringUtils.isNotEmpty(this.hostResource)) {
        // User set host resource and not directly a stream
        if (this.tarInputStream != null) {
            throw new DockerClientException(
                    "Only one of host resource or tar input stream should be defined to perform the copy, not both");
        }
        // create TAR package for the given path so docker can consume it
        Path toUpload = null;
        try {
            toUpload = Files.createTempFile("docker-java", ".tar.gz");
            CompressArchiveUtil.tar(Paths.get(hostResource), toUpload, true, dirChildrenOnly);
        } catch (IOException createFileIOException) {
            if (toUpload != null) {
                // remove tmp docker-javaxxx.tar.gz
                toUpload.toFile().delete();
            }
            throw new DockerClientException("Unable to perform tar on host resource " + this.hostResource, createFileIOException);
        }
        // send the tar stream, call exec so that the stream is consumed and then closed by try-with-resources
        try (InputStream uploadStream = Files.newInputStream(toUpload)) {
            this.tarInputStream = uploadStream;
            return super.exec();
        } catch (IOException e) {
            throw new DockerClientException("Unable to read temp file " + toUpload.toFile().getAbsolutePath(), e);
        } finally {
            this.tarInputStream = null;
            // remove tmp docker-javaxxx.tar.gz
            toUpload.toFile().delete();
        }
    } else if (this.tarInputStream == null) {
        throw new DockerClientException("One of host resource or tar input stream must be defined to perform the copy");
    }
    // User set a stream, so we will just consume it and let the user close it by him self
    return super.exec();
}
 
Example #15
Source File: DockerImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Optional<InspectContainerResponse> inspectContainerCmd(String container) {
    try {
        return Optional.of(dockerClient.inspectContainerCmd(container).exec());
    } catch (NotFoundException ignored) {
        return Optional.empty();
    } catch (RuntimeException e) {
        numberOfDockerApiFails.increment();
        throw new DockerException("Failed to get info for container '" + container + "'", e);
    }
}
 
Example #16
Source File: DockerImplTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void pullImageAsyncIfNeededSuccessfully() {
    final DockerImage image = DockerImage.fromString("test:1.2.3");

    InspectImageResponse inspectImageResponse = mock(InspectImageResponse.class);
    when(inspectImageResponse.getId()).thenReturn(image.asString());

    InspectImageCmd imageInspectCmd = mock(InspectImageCmd.class);
    when(imageInspectCmd.exec())
            .thenThrow(new NotFoundException("Image not found"))
            .thenReturn(inspectImageResponse);

    // Array to make it final
    ArgumentCaptor<ResultCallback> resultCallback = ArgumentCaptor.forClass(ResultCallback.class);
    PullImageCmd pullImageCmd = mock(PullImageCmd.class);
    when(pullImageCmd.exec(resultCallback.capture())).thenReturn(null);

    when(dockerClient.inspectImageCmd(image.asString())).thenReturn(imageInspectCmd);
    when(dockerClient.pullImageCmd(eq(image.asString()))).thenReturn(pullImageCmd);

    assertTrue("Should return true, we just scheduled the pull", docker.pullImageAsyncIfNeeded(image));
    assertTrue("Should return true, the pull i still ongoing", docker.pullImageAsyncIfNeeded(image));

    assertTrue(docker.imageIsDownloaded(image));
    resultCallback.getValue().onComplete();
    assertFalse(docker.pullImageAsyncIfNeeded(image));
}
 
Example #17
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 #18
Source File: DockerImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
private ExecCreateCmdResponse execCreateCmd(ContainerName containerName, String user, String... command) {
    try {
        return dockerClient.execCreateCmd(containerName.asString())
                .withCmd(command)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withUser(user)
                .exec();
    } catch (NotFoundException e) {
        throw new ContainerNotFoundException(containerName);
    }
}
 
Example #19
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 #20
Source File: DockerDelegatingComputerLauncher.java    From docker-plugin with MIT License 5 votes vote down vote up
@Override
public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
    try(final DockerClient client = api.getClient()) {
        client.inspectContainerCmd(containerId).exec();
    } catch (NotFoundException e) {
        // Container has been removed
        Queue.withLock(() -> {
            DockerTransientNode node = (DockerTransientNode) computer.getNode();
            node.terminate(listener);
        });
        return;
    }
    super.launch(computer, listener);
}
 
Example #21
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public boolean existsImage(String imageName) {
  boolean exists = true;
  try {
    getClient().inspectImageCmd(imageName).exec();
    log.trace("Image {} exists", imageName);

  } catch (NotFoundException e) {
    log.trace("Image {} does not exist", imageName);
    exists = false;
  }
  return exists;
}
 
Example #22
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 #23
Source File: DockerImagePullStrategyTest.java    From docker-plugin with MIT License 5 votes vote down vote up
private DockerClient mockDockerClient() {
    InspectImageCmd cmd = mock(InspectImageCmd.class);
    if (existedImage)
        when(cmd.exec()).thenReturn(mock(InspectImageResponse.class));
    else
        when(cmd.exec()).thenThrow(new NotFoundException("not found"));
    DockerClient dockerClient = mock(DockerClient.class);
    when(dockerClient.inspectImageCmd(imageName)).thenReturn(cmd);

    return dockerClient;
}
 
Example #24
Source File: ResultCallback.java    From Core with MIT License 5 votes vote down vote up
@Override
public void onNext(Event event) {
    if (event.getType() == null || !event.getType().getValue().equals("container")) {
        super.onNext(event);
        return;
    }

    ContainerEvent containerEvent = new ContainerEvent(event.getId(), event.getAction());

    // Not lets inspect the container, we won't fire any events without network information
    try {
        InspectContainerResponse info = this.dockerClient.inspectContainerCmd(event.getId()).exec();

        containerEvent.setName(info.getName());
        containerEvent.setEnvironmentVariables(this.getEnvironmentVariables(info));
        containerEvent.setPort(this.getPort(info));
        containerEvent.setIp(this.getIp(info, this.network));

    } catch (NotFoundException e) {
        super.onNext(event);
        return;
    }

    super.onNext(event);
    this.proxyServer.getPluginManager().callEvent(containerEvent);

}
 
Example #25
Source File: WaitContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = NotFoundException.class)
public void testWaitNonExistingContainer() throws Exception {

    ResultCallback.Adapter<WaitResponse> callback = new ResultCallback.Adapter<WaitResponse>() {
        public void onNext(WaitResponse waitResponse) {
            throw new AssertionError("expected NotFoundException");
        }
    };

    dockerRule.getClient().waitContainerCmd("non-existing").exec(callback).awaitCompletion();
}
 
Example #26
Source File: DockerRule.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public void ensureContainerRemoved(String container1Name) {
    try {
        getClient().removeContainerCmd(container1Name)
                .withForce(true)
                .withRemoveVolumes(true)
                .exec();
    } catch (NotFoundException ex) {
        // ignore
    }
}
 
Example #27
Source File: DefaultInvocationBuilder.java    From docker-java with Apache License 2.0 5 votes vote down vote up
protected DockerHttpClient.Response execute(DockerHttpClient.Request request) {
    try {
        DockerHttpClient.Response response = dockerHttpClient.execute(request);
        int statusCode = response.getStatusCode();
        if (statusCode < 200 || statusCode > 299) {
            try {
                String body = IOUtils.toString(response.getBody(), StandardCharsets.UTF_8);
                switch (statusCode) {
                    case 304:
                        throw new NotModifiedException(body);
                    case 400:
                        throw new BadRequestException(body);
                    case 401:
                        throw new UnauthorizedException(body);
                    case 404:
                        throw new NotFoundException(body);
                    case 406:
                        throw new NotAcceptableException(body);
                    case 409:
                        throw new ConflictException(body);
                    case 500:
                        throw new InternalServerErrorException(body);
                    default:
                        throw new DockerException(body, statusCode);
                }
            } finally {
                response.close();
            }
        } else {
            return response;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: LogContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void asyncLogNonExistingContainer() throws Exception {

    LogContainerTestCallback loggingCallback = new LogContainerTestCallback() {
        @Override
        public void onError(Throwable throwable) {

            assertEquals(NotFoundException.class.getName(), throwable.getClass().getName());

            try {
                // close the callback to prevent the call to onComplete
                close();
            } catch (IOException e) {
                throw new RuntimeException();
            }

            super.onError(throwable);
        }

        public void onComplete() {
            super.onComplete();
            throw new AssertionError("expected NotFoundException");
        };
    };

    dockerRule.getClient().logContainerCmd("non-existing").withStdErr(true).withStdOut(true).exec(loggingCallback)
            .awaitCompletion();
}
 
Example #29
Source File: DockerRule.java    From docker-java with Apache License 2.0 5 votes vote down vote up
public void ensureImageRemoved(String imageId) {
    try {
        getClient().removeImageCmd(imageId)
                .withForce(true)
                .exec();
    } catch (NotFoundException ex) {
        // ignore
    }
}
 
Example #30
Source File: DefaultDockerClientIT.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("should remove the container")
public void shouldRemoveTheContainer() {
    defaultDockerClient.stopAndRemoveContainer(containerId);
    assertThat(dockerClient.listContainersCmd().exec()).hasSize(existingContainers.size());
    assertThatExceptionOfType(NotFoundException.class)
        .isThrownBy(() -> dockerClient.inspectContainerCmd(containerId).exec());
}