Search in sources :

Example 6 with ExposedPort

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

the class ContainerState method getPortBindings.

/**
 * @return the port bindings
 */
default List<String> getPortBindings() {
    List<String> portBindings = new ArrayList<>();
    final Ports hostPortBindings = this.getContainerInfo().getHostConfig().getPortBindings();
    for (Map.Entry<ExposedPort, Ports.Binding[]> binding : hostPortBindings.getBindings().entrySet()) {
        for (Ports.Binding portBinding : binding.getValue()) {
            portBindings.add(String.format("%s:%s", portBinding.toString(), binding.getKey()));
        }
    }
    return portBindings;
}
Also used : ExposedPort(com.github.dockerjava.api.model.ExposedPort) ArrayList(java.util.ArrayList) Ports(com.github.dockerjava.api.model.Ports) Map(java.util.Map)

Example 7 with ExposedPort

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

the class GenericContainer method applyConfiguration.

private void applyConfiguration(CreateContainerCmd createCommand) {
    // Set up exposed ports (where there are no host port bindings defined)
    ExposedPort[] portArray = exposedPorts.stream().map(ExposedPort::new).toArray(ExposedPort[]::new);
    createCommand.withExposedPorts(portArray);
    // Set up exposed ports that need host port bindings
    PortBinding[] portBindingArray = portBindings.stream().map(PortBinding::parse).toArray(PortBinding[]::new);
    createCommand.withPortBindings(portBindingArray);
    if (commandParts != null) {
        createCommand.withCmd(commandParts);
    }
    String[] envArray = env.entrySet().stream().map(it -> it.getKey() + "=" + it.getValue()).toArray(String[]::new);
    createCommand.withEnv(envArray);
    Bind[] bindsArray = binds.stream().toArray(Bind[]::new);
    createCommand.withBinds(bindsArray);
    VolumesFrom[] volumesFromsArray = volumesFroms.stream().toArray(VolumesFrom[]::new);
    createCommand.withVolumesFrom(volumesFromsArray);
    Set<Link> allLinks = new HashSet<>();
    Set<String> allLinkedContainerNetworks = new HashSet<>();
    for (Map.Entry<String, LinkableContainer> linkEntries : linkedContainers.entrySet()) {
        String alias = linkEntries.getKey();
        LinkableContainer linkableContainer = linkEntries.getValue();
        Set<Link> links = findLinksFromThisContainer(alias, linkableContainer);
        allLinks.addAll(links);
        if (allLinks.size() == 0) {
            throw new ContainerLaunchException("Aborting attempt to link to container " + linkableContainer.getContainerName() + " as it is not running");
        }
        Set<String> linkedContainerNetworks = findAllNetworksForLinkedContainers(linkableContainer);
        allLinkedContainerNetworks.addAll(linkedContainerNetworks);
    }
    createCommand.withLinks(allLinks.toArray(new Link[allLinks.size()]));
    allLinkedContainerNetworks.remove("bridge");
    if (allLinkedContainerNetworks.size() > 1) {
        logger().warn("Container needs to be on more than one custom network to link to other " + "containers - this is not currently supported. Required networks are: {}", allLinkedContainerNetworks);
    }
    Optional<String> networkForLinks = allLinkedContainerNetworks.stream().findFirst();
    if (networkForLinks.isPresent()) {
        logger().debug("Associating container with network: {}", networkForLinks.get());
        createCommand.withNetworkMode(networkForLinks.get());
    }
    createCommand.withPublishAllPorts(true);
    String[] extraHostsArray = extraHosts.stream().toArray(String[]::new);
    createCommand.withExtraHosts(extraHostsArray);
    if (network != null) {
        createCommand.withNetworkMode(network.getId());
        createCommand.withAliases(this.networkAliases);
    } else if (networkMode != null) {
        createCommand.withNetworkMode(networkMode);
    }
    if (workingDirectory != null) {
        createCommand.withWorkingDir(workingDirectory);
    }
    if (privilegedMode) {
        createCommand.withPrivileged(privilegedMode);
    }
    createContainerCmdModifiers.forEach(hook -> hook.accept(createCommand));
    Map<String, String> labels = createCommand.getLabels();
    labels = new HashMap<>(labels != null ? labels : Collections.emptyMap());
    labels.putAll(DockerClientFactory.DEFAULT_LABELS);
    createCommand.withLabels(labels);
}
Also used : Arrays(java.util.Arrays) MinimumDurationRunningStartupCheckStrategy(org.testcontainers.containers.startupcheck.MinimumDurationRunningStartupCheckStrategy) VolumesFrom(com.github.dockerjava.api.model.VolumesFrom) Link(com.github.dockerjava.api.model.Link) DockerClient(com.github.dockerjava.api.DockerClient) IsRunningStartupCheckStrategy(org.testcontainers.containers.startupcheck.IsRunningStartupCheckStrategy) Future(java.util.concurrent.Future) Wait(org.testcontainers.containers.wait.Wait) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) STDOUT(org.testcontainers.containers.output.OutputFrame.OutputType.STDOUT) Duration(java.time.Duration) Map(java.util.Map) ExposedPort(com.github.dockerjava.api.model.ExposedPort) PortBinding(com.github.dockerjava.api.model.PortBinding) WaitStrategyTarget(org.testcontainers.containers.wait.strategy.WaitStrategyTarget) Path(java.nio.file.Path) NonNull(lombok.NonNull) StartupCheckStrategy(org.testcontainers.containers.startupcheck.StartupCheckStrategy) Set(java.util.Set) Description(org.junit.runner.Description) EqualsAndHashCode(lombok.EqualsAndHashCode) InspectContainerResponse(com.github.dockerjava.api.command.InspectContainerResponse) Collectors(java.util.stream.Collectors) WaitStrategy(org.testcontainers.containers.wait.WaitStrategy) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Stream(java.util.stream.Stream) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) Optional(java.util.Optional) DockerClientFactory(org.testcontainers.DockerClientFactory) NotNull(org.jetbrains.annotations.NotNull) Info(com.github.dockerjava.api.model.Info) Setter(lombok.Setter) Bind(com.github.dockerjava.api.model.Bind) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) AccessLevel(lombok.AccessLevel) RemoteDockerImage(org.testcontainers.images.RemoteDockerImage) Slf4jLogConsumer(org.testcontainers.containers.output.Slf4jLogConsumer) Charset(java.nio.charset.Charset) FrameConsumerResultCallback(org.testcontainers.containers.output.FrameConsumerResultCallback) CommandLine.runShellCommand(org.testcontainers.utility.CommandLine.runShellCommand) org.testcontainers.utility(org.testcontainers.utility) LinkedHashSet(java.util.LinkedHashSet) Profiler(org.slf4j.profiler.Profiler) Logger(org.slf4j.Logger) IOUtils(org.apache.commons.compress.utils.IOUtils) FileOutputStream(java.io.FileOutputStream) RateLimiterBuilder(org.rnorth.ducttape.ratelimits.RateLimiterBuilder) IOException(java.io.IOException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Unreliables(org.rnorth.ducttape.unreliables.Unreliables) RateLimiter(org.rnorth.ducttape.ratelimits.RateLimiter) LinkableContainer(org.testcontainers.containers.traits.LinkableContainer) Data(lombok.Data) Volume(com.github.dockerjava.api.model.Volume) OutputFrame(org.testcontainers.containers.output.OutputFrame) Collections(java.util.Collections) STDERR(org.testcontainers.containers.output.OutputFrame.OutputType.STDERR) LinkableContainer(org.testcontainers.containers.traits.LinkableContainer) Bind(com.github.dockerjava.api.model.Bind) VolumesFrom(com.github.dockerjava.api.model.VolumesFrom) ExposedPort(com.github.dockerjava.api.model.ExposedPort) PortBinding(com.github.dockerjava.api.model.PortBinding) Map(java.util.Map) HashMap(java.util.HashMap) Link(com.github.dockerjava.api.model.Link) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 8 with ExposedPort

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

use of com.github.dockerjava.api.model.ExposedPort in project elastest-torm by elastest.

the class DockerService2 method bindingPort.

public SocatBindedPort bindingPort(String containerIp, String port, String networkName) throws Exception {
    DockerClient dockerClient = this.getDockerClient();
    int listenPort = 37000;
    String bindedPort = null;
    try {
        listenPort = utilTools.findRandomOpenPort();
        List<String> envVariables = new ArrayList<>();
        envVariables.add("LISTEN_PORT=" + listenPort);
        envVariables.add("FORWARD_PORT=" + port);
        envVariables.add("TARGET_SERVICE_IP=" + containerIp);
        Ports portBindings = new Ports();
        ExposedPort exposedListenPort = ExposedPort.tcp(listenPort);
        portBindings.bind(exposedListenPort, Ports.Binding.bindPort(listenPort));
        bindedPort = this.runDockerContainer(dockerClient, etSocatImage, envVariables, "container" + listenPort, networkName, portBindings, listenPort);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(e.getMessage());
    }
    SocatBindedPort bindedPortObj = new SocatBindedPort(Integer.toString(listenPort), bindedPort);
    return bindedPortObj;
}
Also used : ExposedPort(com.github.dockerjava.api.model.ExposedPort) DockerClient(com.github.dockerjava.api.DockerClient) ArrayList(java.util.ArrayList) Ports(com.github.dockerjava.api.model.Ports) SocatBindedPort(io.elastest.etm.model.SocatBindedPort) 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 10 with ExposedPort

use of com.github.dockerjava.api.model.ExposedPort in project elastest-torm by elastest.

the class DockerIntegrationTest method testDocker.

@Test
@DisplayName("Ask for Chrome to Docker")
void testDocker() throws Exception {
    // Test data (input)
    String imageId = "selenium/standalone-chrome-debug:3.5.3";
    log.debug("Starting Hub with image {}", imageId);
    String containerName = dockerService.generateContainerName("hub-for-test-");
    Binding bindPort = bindPort(dockerService.findRandomOpenPort());
    ExposedPort exposedPort = tcp(4444);
    Binding bindHubVncPort = bindPort(dockerService.findRandomOpenPort());
    ExposedPort exposedHubVncPort = tcp(5900);
    List<PortBinding> portBindings = asList(new PortBinding(bindPort, exposedPort), new PortBinding(bindHubVncPort, exposedHubVncPort));
    DockerBuilder dockerBuilder = dockerBuilder(imageId, containerName).portBindings(portBindings);
    dockerService.startAndWaitContainer(dockerBuilder.build());
    // Assertions
    assertTrue(dockerService.existsContainer(containerName));
    // Tear down
    log.debug("Stoping Hub");
    dockerService.stopAndRemoveContainer(containerName);
}
Also used : PortBinding(com.github.dockerjava.api.model.PortBinding) Binding(com.github.dockerjava.api.model.Ports.Binding) ExposedPort(com.github.dockerjava.api.model.ExposedPort) DockerBuilder(io.elastest.epm.client.DockerContainer.DockerBuilder) PortBinding(com.github.dockerjava.api.model.PortBinding) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) DisplayName(org.junit.jupiter.api.DisplayName)

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