Search in sources :

Example 1 with InspectContainerResponse

use of com.github.dockerjava.api.command.InspectContainerResponse in project tutorials by eugenp.

the class ContainerLiveTest method whenHavingContainer_thenInspectContainer.

@Test
public void whenHavingContainer_thenInspectContainer() {
    // when
    CreateContainerResponse container = dockerClient.createContainerCmd("alpine:3.6").withCmd("sleep", "10000").exec();
    // then
    InspectContainerResponse containerResponse = dockerClient.inspectContainerCmd(container.getId()).exec();
    assertThat(containerResponse.getId(), is(container.getId()));
}
Also used : InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) CreateContainerResponse(com.github.dockerjava.api.command.CreateContainerResponse) Test(org.junit.Test)

Example 2 with InspectContainerResponse

use of com.github.dockerjava.api.command.InspectContainerResponse in project elastest-torm by elastest.

the class DockerService2 method getContainerIdByName.

public String getContainerIdByName(String containerName) {
    DockerClient dockerClient = this.getDockerClient();
    String id = "";
    if (existsContainer(containerName)) {
        try {
            InspectContainerResponse response = dockerClient.inspectContainerCmd(containerName).exec();
            id = response.getId();
        } catch (Exception e) {
        }
    }
    return id;
}
Also used : InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) DockerClient(com.github.dockerjava.api.DockerClient) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NotModifiedException(com.github.dockerjava.api.exception.NotModifiedException) DockerClientException(com.github.dockerjava.api.exception.DockerClientException) InternalServerErrorException(com.github.dockerjava.api.exception.InternalServerErrorException) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 3 with InspectContainerResponse

use of com.github.dockerjava.api.command.InspectContainerResponse in project elastest-torm by elastest.

the class DockerService2 method getContainerInfoByName.

public InspectContainerResponse getContainerInfoByName(String containerName) {
    InspectContainerResponse response = null;
    DockerClient dockerClient = getDockerClient();
    if (existsContainer(containerName, dockerClient)) {
        try {
            response = dockerClient.inspectContainerCmd(containerName).exec();
        } catch (Exception e) {
        }
    }
    return response;
}
Also used : InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) DockerClient(com.github.dockerjava.api.DockerClient) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NotModifiedException(com.github.dockerjava.api.exception.NotModifiedException) DockerClientException(com.github.dockerjava.api.exception.DockerClientException) InternalServerErrorException(com.github.dockerjava.api.exception.InternalServerErrorException) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 4 with InspectContainerResponse

use of com.github.dockerjava.api.command.InspectContainerResponse in project testcontainers-java by testcontainers.

the class ResourceReaper method stopContainer.

private void stopContainer(String containerId, String imageName) {
    boolean running;
    try {
        InspectContainerResponse containerInfo = dockerClient.inspectContainerCmd(containerId).exec();
        running = containerInfo.getState().getRunning();
    } catch (NotFoundException e) {
        LOGGER.trace("Was going to stop container but it apparently no longer exists: {}");
        return;
    } catch (DockerException e) {
        LOGGER.trace("Error encountered when checking container for shutdown (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());
        return;
    }
    if (running) {
        try {
            LOGGER.trace("Stopping container: {}", containerId);
            dockerClient.killContainerCmd(containerId).exec();
            LOGGER.trace("Stopped container: {}", imageName);
        } catch (DockerException e) {
            LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());
        }
    }
    try {
        dockerClient.inspectContainerCmd(containerId).exec();
    } catch (NotFoundException e) {
        LOGGER.trace("Was going to remove container but it apparently no longer exists: {}");
        return;
    }
    try {
        LOGGER.trace("Removing container: {}", containerId);
        try {
            dockerClient.removeContainerCmd(containerId).withRemoveVolumes(true).withForce(true).exec();
            LOGGER.debug("Removed container and associated volume(s): {}", imageName);
        } catch (InternalServerErrorException e) {
            LOGGER.trace("Exception when removing container with associated volume(s): {} (due to {})", imageName, e.getMessage());
        }
    } catch (DockerException e) {
        LOGGER.trace("Error encountered shutting down container (ID: {}) - it may not have been stopped, or may already be stopped: {}", containerId, e.getMessage());
    }
}
Also used : InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) DockerException(com.github.dockerjava.api.exception.DockerException) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) InternalServerErrorException(com.github.dockerjava.api.exception.InternalServerErrorException)

Example 5 with InspectContainerResponse

use of com.github.dockerjava.api.command.InspectContainerResponse in project testcontainers-java by testcontainers.

the class ResourceReaper method start.

@SneakyThrows(InterruptedException.class)
public static String start(String hostIpAddress, DockerClient client, boolean withDummyMount) {
    String ryukImage = TestcontainersConfiguration.getInstance().getRyukImage();
    DockerClientFactory.instance().checkAndPullImage(client, ryukImage);
    MountableFile mountableFile = MountableFile.forClasspathResource(ResourceReaper.class.getName().replace(".", "/") + ".class");
    List<Bind> binds = new ArrayList<>();
    binds.add(new Bind("//var/run/docker.sock", new Volume("/var/run/docker.sock")));
    if (withDummyMount) {
        // Not needed for Ryuk, but we perform pre-flight checks with it (micro optimization)
        binds.add(new Bind(mountableFile.getResolvedPath(), new Volume("/dummy"), AccessMode.ro));
    }
    String ryukContainerId = client.createContainerCmd(ryukImage).withHostConfig(new HostConfig() {

        @JsonProperty("AutoRemove")
        boolean autoRemove = true;
    }).withExposedPorts(new ExposedPort(8080)).withPublishAllPorts(true).withName("testcontainers-ryuk-" + DockerClientFactory.SESSION_ID).withLabels(Collections.singletonMap(DockerClientFactory.TESTCONTAINERS_LABEL, "true")).withBinds(binds).exec().getId();
    client.startContainerCmd(ryukContainerId).exec();
    InspectContainerResponse inspectedContainer = client.inspectContainerCmd(ryukContainerId).exec();
    Integer ryukPort = inspectedContainer.getNetworkSettings().getPorts().getBindings().values().stream().flatMap(Stream::of).findFirst().map(Ports.Binding::getHostPortSpec).map(Integer::parseInt).get();
    CountDownLatch ryukScheduledLatch = new CountDownLatch(1);
    synchronized (DEATH_NOTE) {
        DEATH_NOTE.add(DockerClientFactory.DEFAULT_LABELS.entrySet().stream().<Map.Entry<String, String>>map(it -> new SimpleEntry<>("label", it.getKey() + "=" + it.getValue())).collect(Collectors.toList()));
    }
    Thread kiraThread = new Thread(() -> {
        while (true) {
            int index = 0;
            try (Socket clientSocket = new Socket(hostIpAddress, ryukPort)) {
                OutputStream out = clientSocket.getOutputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                synchronized (DEATH_NOTE) {
                    while (true) {
                        if (DEATH_NOTE.size() <= index) {
                            try {
                                DEATH_NOTE.wait(1_000);
                                continue;
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        List<Map.Entry<String, String>> filters = DEATH_NOTE.get(index);
                        String query = URLEncodedUtils.format(filters.stream().map(it -> new BasicNameValuePair(it.getKey(), it.getValue())).collect(Collectors.toList()), (String) null);
                        log.debug("Sending '{}' to Ryuk", query);
                        out.write(query.getBytes());
                        out.write('\n');
                        out.flush();
                        while (!"ACK".equalsIgnoreCase(in.readLine())) {
                        }
                        ryukScheduledLatch.countDown();
                        index++;
                    }
                }
            } catch (IOException e) {
                log.warn("Can not connect to Ryuk at {}:{}", hostIpAddress, ryukPort, e);
            }
        }
    }, "testcontainers-ryuk");
    kiraThread.setDaemon(true);
    kiraThread.start();
    // We need to wait before we can start any containers to make sure that we delete them
    if (!ryukScheduledLatch.await(5, TimeUnit.SECONDS)) {
        throw new IllegalStateException("Can not connect to Ryuk");
    }
    return ryukContainerId;
}
Also used : Bind(com.github.dockerjava.api.model.Bind) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) SimpleEntry(java.util.AbstractMap.SimpleEntry) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HostConfig(com.github.dockerjava.api.model.HostConfig) OutputStream(java.io.OutputStream) Stream(java.util.stream.Stream) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ExposedPort(com.github.dockerjava.api.model.ExposedPort) Volume(com.github.dockerjava.api.model.Volume) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) SneakyThrows(lombok.SneakyThrows)

Aggregations

InspectContainerResponse (com.github.dockerjava.api.command.InspectContainerResponse)7 InternalServerErrorException (com.github.dockerjava.api.exception.InternalServerErrorException)3 NotFoundException (com.github.dockerjava.api.exception.NotFoundException)3 IOException (java.io.IOException)3 DockerClient (com.github.dockerjava.api.DockerClient)2 DockerClientException (com.github.dockerjava.api.exception.DockerClientException)2 DockerException (com.github.dockerjava.api.exception.DockerException)2 NotModifiedException (com.github.dockerjava.api.exception.NotModifiedException)2 ExposedPort (com.github.dockerjava.api.model.ExposedPort)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 SAXException (org.xml.sax.SAXException)2 CreateContainerResponse (com.github.dockerjava.api.command.CreateContainerResponse)1 Bind (com.github.dockerjava.api.model.Bind)1 HostConfig (com.github.dockerjava.api.model.HostConfig)1 PortBinding (com.github.dockerjava.api.model.PortBinding)1 Volume (com.github.dockerjava.api.model.Volume)1 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1