Search in sources :

Example 11 with ExposedPort

use of com.github.dockerjava.api.model.ExposedPort 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)

Example 12 with ExposedPort

use of com.github.dockerjava.api.model.ExposedPort in project testcontainers-java by testcontainers.

the class ContainerState method getMappedPort.

/**
 * Get the actual mapped port for a given port exposed by the container.
 *
 * @param originalPort the original TCP port that is exposed
 * @return the port that the exposed port is mapped to, or null if it is not exposed
 */
default Integer getMappedPort(int originalPort) {
    Preconditions.checkState(this.getContainerId() != null, "Mapped port can only be obtained after the container is started");
    Ports.Binding[] binding = new Ports.Binding[0];
    final InspectContainerResponse containerInfo = this.getContainerInfo();
    if (containerInfo != null) {
        binding = containerInfo.getNetworkSettings().getPorts().getBindings().get(new ExposedPort(originalPort));
    }
    if (binding != null && binding.length > 0 && binding[0] != null) {
        return Integer.valueOf(binding[0].getHostPortSpec());
    } else {
        throw new IllegalArgumentException("Requested port (" + originalPort + ") is not mapped");
    }
}
Also used : PortBinding(com.github.dockerjava.api.model.PortBinding) InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) ExposedPort(com.github.dockerjava.api.model.ExposedPort)

Aggregations

ExposedPort (com.github.dockerjava.api.model.ExposedPort)12 ArrayList (java.util.ArrayList)6 PortBinding (com.github.dockerjava.api.model.PortBinding)5 Volume (com.github.dockerjava.api.model.Volume)5 Ports (com.github.dockerjava.api.model.Ports)4 InspectContainerResponse (com.github.dockerjava.api.command.InspectContainerResponse)3 Bind (com.github.dockerjava.api.model.Bind)3 HostConfig (com.github.dockerjava.api.model.HostConfig)3 Binding (com.github.dockerjava.api.model.Ports.Binding)3 VolumesFrom (com.github.dockerjava.api.model.VolumesFrom)3 IOException (java.io.IOException)3 DockerClient (com.github.dockerjava.api.DockerClient)2 CreateContainerCmd (com.github.dockerjava.api.command.CreateContainerCmd)2 Capability (com.github.dockerjava.api.model.Capability)2 DockerBuilder (io.elastest.epm.client.DockerContainer.DockerBuilder)2 Map (java.util.Map)2 DockerClientException (com.github.dockerjava.api.exception.DockerClientException)1 InternalServerErrorException (com.github.dockerjava.api.exception.InternalServerErrorException)1 NotFoundException (com.github.dockerjava.api.exception.NotFoundException)1 NotModifiedException (com.github.dockerjava.api.exception.NotModifiedException)1