Search in sources :

Example 1 with HostConfig

use of com.github.dockerjava.api.model.HostConfig in project camel by apache.

the class CreateContainerCmdHeaderTest method createContainerHeaderTest.

@Test
public void createContainerHeaderTest() {
    String image = "busybox";
    ExposedPort exposedPort = ExposedPort.tcp(22);
    boolean tty = true;
    String name = "cameldocker";
    String workingDir = "/opt";
    boolean disableNetwork = false;
    String domainName = "apache.org";
    String hostname = "dockerjava";
    String user = "docker";
    boolean stdInOpen = false;
    boolean stdInOnce = false;
    boolean attachStdErr = true;
    boolean attachStdOut = true;
    boolean attachStdIn = false;
    Long memoryLimit = 2048L;
    Long swapMemory = 512L;
    Integer cpuShares = 512;
    Volume volumes = new Volume("/example");
    VolumesFrom volumesFromContainer = new VolumesFrom("/etc");
    String env = "FOO=bar";
    String cmd = "whoami";
    HostConfig hostConfig = new HostConfig();
    Capability capAdd = Capability.NET_BROADCAST;
    Capability capDrop = Capability.BLOCK_SUSPEND;
    String[] entrypoint = new String[] { "sleep", "9999" };
    String portSpecs = "80";
    String dns = "8.8.8.8";
    Map<String, Object> headers = getDefaultParameters();
    headers.put(DockerConstants.DOCKER_IMAGE, image);
    headers.put(DockerConstants.DOCKER_EXPOSED_PORTS, exposedPort);
    headers.put(DockerConstants.DOCKER_TTY, tty);
    headers.put(DockerConstants.DOCKER_NAME, name);
    headers.put(DockerConstants.DOCKER_WORKING_DIR, workingDir);
    headers.put(DockerConstants.DOCKER_DISABLE_NETWORK, disableNetwork);
    headers.put(DockerConstants.DOCKER_HOSTNAME, hostname);
    headers.put(DockerConstants.DOCKER_USER, user);
    headers.put(DockerConstants.DOCKER_STD_IN_OPEN, stdInOpen);
    headers.put(DockerConstants.DOCKER_STD_IN_ONCE, stdInOnce);
    headers.put(DockerConstants.DOCKER_ATTACH_STD_IN, attachStdIn);
    headers.put(DockerConstants.DOCKER_ATTACH_STD_ERR, attachStdErr);
    headers.put(DockerConstants.DOCKER_ATTACH_STD_OUT, attachStdOut);
    headers.put(DockerConstants.DOCKER_MEMORY_LIMIT, memoryLimit);
    headers.put(DockerConstants.DOCKER_MEMORY_SWAP, swapMemory);
    headers.put(DockerConstants.DOCKER_CPU_SHARES, cpuShares);
    headers.put(DockerConstants.DOCKER_VOLUMES, volumes);
    headers.put(DockerConstants.DOCKER_VOLUMES_FROM, volumesFromContainer);
    headers.put(DockerConstants.DOCKER_ENV, env);
    headers.put(DockerConstants.DOCKER_CMD, cmd);
    headers.put(DockerConstants.DOCKER_HOST_CONFIG, hostConfig);
    headers.put(DockerConstants.DOCKER_CAP_ADD, capAdd);
    headers.put(DockerConstants.DOCKER_CAP_DROP, capDrop);
    headers.put(DockerConstants.DOCKER_ENTRYPOINT, entrypoint);
    headers.put(DockerConstants.DOCKER_PORT_SPECS, portSpecs);
    headers.put(DockerConstants.DOCKER_DNS, dns);
    headers.put(DockerConstants.DOCKER_DOMAIN_NAME, domainName);
    template.sendBodyAndHeaders("direct:in", "", headers);
    Mockito.verify(dockerClient, Mockito.times(1)).createContainerCmd(image);
    Mockito.verify(mockObject, Mockito.times(1)).withExposedPorts(Matchers.eq(exposedPort));
    Mockito.verify(mockObject, Mockito.times(1)).withTty(Matchers.eq(tty));
    Mockito.verify(mockObject, Mockito.times(1)).withName(Matchers.eq(name));
    Mockito.verify(mockObject, Mockito.times(1)).withWorkingDir(workingDir);
    Mockito.verify(mockObject, Mockito.times(1)).withNetworkDisabled(disableNetwork);
    Mockito.verify(mockObject, Mockito.times(1)).withHostName(hostname);
    Mockito.verify(mockObject, Mockito.times(1)).withUser(user);
    Mockito.verify(mockObject, Mockito.times(1)).withStdinOpen(stdInOpen);
    Mockito.verify(mockObject, Mockito.times(1)).withStdInOnce(stdInOnce);
    Mockito.verify(mockObject, Mockito.times(1)).withAttachStderr(attachStdErr);
    Mockito.verify(mockObject, Mockito.times(1)).withAttachStdin(attachStdIn);
    Mockito.verify(mockObject, Mockito.times(1)).withAttachStdout(attachStdOut);
    Mockito.verify(mockObject, Mockito.times(1)).withMemory(memoryLimit);
    Mockito.verify(mockObject, Mockito.times(1)).withMemorySwap(swapMemory);
    Mockito.verify(mockObject, Mockito.times(1)).withCpuShares(cpuShares);
    Mockito.verify(mockObject, Mockito.times(1)).withVolumes(volumes);
    Mockito.verify(mockObject, Mockito.times(1)).withVolumesFrom(volumesFromContainer);
    Mockito.verify(mockObject, Mockito.times(1)).withEnv(env);
    Mockito.verify(mockObject, Mockito.times(1)).withCmd(cmd);
    Mockito.verify(mockObject, Mockito.times(1)).withHostConfig(hostConfig);
    Mockito.verify(mockObject, Mockito.times(1)).withCapAdd(capAdd);
    Mockito.verify(mockObject, Mockito.times(1)).withCapDrop(capDrop);
    Mockito.verify(mockObject, Mockito.times(1)).withEntrypoint(entrypoint);
    Mockito.verify(mockObject, Mockito.times(1)).withPortSpecs(portSpecs);
    Mockito.verify(mockObject, Mockito.times(1)).withDns(dns);
    Mockito.verify(mockObject, Mockito.times(1)).withDomainName(domainName);
}
Also used : ExposedPort(com.github.dockerjava.api.model.ExposedPort) Capability(com.github.dockerjava.api.model.Capability) Volume(com.github.dockerjava.api.model.Volume) VolumesFrom(com.github.dockerjava.api.model.VolumesFrom) HostConfig(com.github.dockerjava.api.model.HostConfig) Test(org.junit.Test)

Example 2 with HostConfig

use of com.github.dockerjava.api.model.HostConfig in project camel by apache.

the class DockerProducer method executeCreateContainerRequest.

/**
     * Produce a create container request
     *
     * @param client
     * @param message
     * @return
     */
private CreateContainerCmd executeCreateContainerRequest(DockerClient client, Message message) {
    LOGGER.debug("Executing Docker Create Container Request");
    String image = DockerHelper.getProperty(DockerConstants.DOCKER_IMAGE, configuration, message, String.class);
    ObjectHelper.notNull(image, "Image must be specified");
    CreateContainerCmd createContainerCmd = client.createContainerCmd(image);
    Boolean attachStdErr = DockerHelper.getProperty(DockerConstants.DOCKER_ATTACH_STD_ERR, configuration, message, Boolean.class);
    if (attachStdErr != null) {
        createContainerCmd.withAttachStderr(attachStdErr);
    }
    Boolean attachStdIn = DockerHelper.getProperty(DockerConstants.DOCKER_ATTACH_STD_IN, configuration, message, Boolean.class);
    if (attachStdIn != null) {
        createContainerCmd.withAttachStdin(attachStdIn);
    }
    Boolean attachStdOut = DockerHelper.getProperty(DockerConstants.DOCKER_ATTACH_STD_OUT, configuration, message, Boolean.class);
    if (attachStdOut != null) {
        createContainerCmd.withAttachStdout(attachStdOut);
    }
    Capability[] capAdd = DockerHelper.getArrayProperty(DockerConstants.DOCKER_CAP_ADD, message, Capability.class);
    if (capAdd != null) {
        createContainerCmd.withCapAdd(capAdd);
    }
    Capability[] capDrop = DockerHelper.getArrayProperty(DockerConstants.DOCKER_CAP_DROP, message, Capability.class);
    if (capDrop != null) {
        createContainerCmd.withCapDrop(capDrop);
    }
    String[] cmd = DockerHelper.parseDelimitedStringHeader(DockerConstants.DOCKER_CMD, message);
    if (cmd != null) {
        createContainerCmd.withCmd(cmd);
    }
    Integer cpuShares = DockerHelper.getProperty(DockerConstants.DOCKER_CPU_SHARES, configuration, message, Integer.class);
    if (cpuShares != null) {
        createContainerCmd.withCpuShares(cpuShares);
    }
    Boolean disableNetwork = DockerHelper.getProperty(DockerConstants.DOCKER_DISABLE_NETWORK, configuration, message, Boolean.class);
    if (disableNetwork != null) {
        createContainerCmd.withNetworkDisabled(disableNetwork);
    }
    String[] dns = DockerHelper.parseDelimitedStringHeader(DockerConstants.DOCKER_DNS, message);
    if (dns != null) {
        createContainerCmd.withDns(dns);
    }
    String domainName = DockerHelper.getProperty(DockerConstants.DOCKER_DOMAIN_NAME, configuration, message, String.class);
    if (domainName != null) {
        createContainerCmd.withDomainName(domainName);
    }
    String[] env = DockerHelper.parseDelimitedStringHeader(DockerConstants.DOCKER_ENV, message);
    if (env != null) {
        createContainerCmd.withEnv(env);
    }
    String[] entrypoint = DockerHelper.getArrayProperty(DockerConstants.DOCKER_ENTRYPOINT, message, String.class);
    if (entrypoint != null) {
        createContainerCmd.withEntrypoint(entrypoint);
    }
    ExposedPort[] exposedPorts = DockerHelper.getArrayProperty(DockerConstants.DOCKER_EXPOSED_PORTS, message, ExposedPort.class);
    if (exposedPorts != null) {
        createContainerCmd.withExposedPorts(exposedPorts);
    }
    HostConfig hostConfig = DockerHelper.getProperty(DockerConstants.DOCKER_HOST_CONFIG, configuration, message, HostConfig.class);
    if (hostConfig != null) {
        createContainerCmd.withHostConfig(hostConfig);
    }
    String hostName = DockerHelper.getProperty(DockerConstants.DOCKER_HOSTNAME, configuration, message, String.class);
    if (hostName != null) {
        createContainerCmd.withHostName(hostName);
    }
    Long memoryLimit = DockerHelper.getProperty(DockerConstants.DOCKER_MEMORY_LIMIT, configuration, message, Long.class);
    if (memoryLimit != null) {
        createContainerCmd.withMemory(memoryLimit);
    }
    Long memorySwap = DockerHelper.getProperty(DockerConstants.DOCKER_MEMORY_SWAP, configuration, message, Long.class);
    if (memorySwap != null) {
        createContainerCmd.withMemorySwap(memorySwap);
    }
    String name = DockerHelper.getProperty(DockerConstants.DOCKER_NAME, configuration, message, String.class);
    if (name != null) {
        createContainerCmd.withName(name);
    }
    String[] portSpecs = DockerHelper.parseDelimitedStringHeader(DockerConstants.DOCKER_PORT_SPECS, message);
    if (portSpecs != null) {
        createContainerCmd.withPortSpecs(portSpecs);
    }
    Boolean stdInOpen = DockerHelper.getProperty(DockerConstants.DOCKER_STD_IN_OPEN, configuration, message, Boolean.class);
    if (stdInOpen != null) {
        createContainerCmd.withStdinOpen(stdInOpen);
    }
    Boolean stdInOnce = DockerHelper.getProperty(DockerConstants.DOCKER_STD_IN_ONCE, configuration, message, Boolean.class);
    if (stdInOnce != null) {
        createContainerCmd.withStdInOnce(stdInOnce);
    }
    Boolean tty = DockerHelper.getProperty(DockerConstants.DOCKER_TTY, configuration, message, Boolean.class);
    if (tty != null) {
        createContainerCmd.withTty(tty);
    }
    String user = DockerHelper.getProperty(DockerConstants.DOCKER_USER, configuration, message, String.class);
    if (user != null) {
        createContainerCmd.withUser(user);
    }
    Volume[] volume = DockerHelper.getArrayProperty(DockerConstants.DOCKER_VOLUMES, message, Volume.class);
    if (volume != null) {
        createContainerCmd.withVolumes(volume);
    }
    VolumesFrom[] volumesFrom = DockerHelper.getArrayProperty(DockerConstants.DOCKER_VOLUMES_FROM, message, VolumesFrom.class);
    if (volumesFrom != null) {
        createContainerCmd.withVolumesFrom(volumesFrom);
    }
    String workingDir = DockerHelper.getProperty(DockerConstants.DOCKER_WORKING_DIR, configuration, message, String.class);
    if (workingDir != null) {
        createContainerCmd.withWorkingDir(workingDir);
    }
    return createContainerCmd;
}
Also used : Capability(com.github.dockerjava.api.model.Capability) VolumesFrom(com.github.dockerjava.api.model.VolumesFrom) CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) ExposedPort(com.github.dockerjava.api.model.ExposedPort) Volume(com.github.dockerjava.api.model.Volume) HostConfig(com.github.dockerjava.api.model.HostConfig)

Example 3 with HostConfig

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

ExposedPort (com.github.dockerjava.api.model.ExposedPort)3 HostConfig (com.github.dockerjava.api.model.HostConfig)3 Volume (com.github.dockerjava.api.model.Volume)3 Capability (com.github.dockerjava.api.model.Capability)2 VolumesFrom (com.github.dockerjava.api.model.VolumesFrom)2 CreateContainerCmd (com.github.dockerjava.api.command.CreateContainerCmd)1 InspectContainerResponse (com.github.dockerjava.api.command.InspectContainerResponse)1 Bind (com.github.dockerjava.api.model.Bind)1 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 Socket (java.net.Socket)1 SimpleEntry (java.util.AbstractMap.SimpleEntry)1 ArrayList (java.util.ArrayList)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Stream (java.util.stream.Stream)1 SneakyThrows (lombok.SneakyThrows)1 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)1 Test (org.junit.Test)1