Search in sources :

Example 11 with CreateContainerCmd

use of com.github.dockerjava.api.command.CreateContainerCmd in project vespa by vespa-engine.

the class CreateContainerCommandImpl method createCreateContainerCmd.

private CreateContainerCmd createCreateContainerCmd() {
    List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList());
    final CreateContainerCmd containerCmd = docker.createContainerCmd(dockerImage.asString()).withCpuShares(containerResources.cpuShares).withMemory(containerResources.memoryBytes).withName(containerName.asString()).withHostName(hostName).withLabels(labels).withEnv(environmentAssignments).withBinds(volumeBinds).withUlimits(ulimits).withCapAdd(new ArrayList<>(addCapabilities)).withCapDrop(new ArrayList<>(dropCapabilities)).withPrivileged(privileged);
    networkMode.filter(mode -> !mode.toLowerCase().equals("host")).ifPresent(mode -> containerCmd.withMacAddress(generateMACAddress(hostName, ipv4Address, ipv6Address)));
    networkMode.ifPresent(containerCmd::withNetworkMode);
    ipv4Address.ifPresent(containerCmd::withIpv4Address);
    ipv6Address.ifPresent(containerCmd::withIpv6Address);
    entrypoint.ifPresent(containerCmd::withEntrypoint);
    return containerCmd;
}
Also used : CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) IntStream(java.util.stream.IntStream) Bind(com.github.dockerjava.api.model.Bind) Set(java.util.Set) HashMap(java.util.HashMap) Random(java.util.Random) Collectors(java.util.stream.Collectors) DockerClient(com.github.dockerjava.api.DockerClient) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) SecureRandom(java.security.SecureRandom) HashSet(java.util.HashSet) Capability(com.github.dockerjava.api.model.Capability) Ulimit(com.github.dockerjava.api.model.Ulimit) Inet6Address(java.net.Inet6Address) CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) List(java.util.List) Stream(java.util.stream.Stream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Map(java.util.Map) Optional(java.util.Optional) Bind(com.github.dockerjava.api.model.Bind) ArrayList(java.util.ArrayList)

Example 12 with CreateContainerCmd

use of com.github.dockerjava.api.command.CreateContainerCmd in project hazelcast by hazelcast.

the class PostgresCdcNetworkIntegrationTest method initPostgres.

private PostgreSQLContainer<?> initPostgres(Network network, Integer fixedExposedPort) {
    PostgreSQLContainer<?> postgres = namedTestContainer(new PostgreSQLContainer<>(AbstractPostgresCdcIntegrationTest.DOCKER_IMAGE).withDatabaseName("postgres").withUsername("postgres").withPassword("postgres"));
    if (fixedExposedPort != null) {
        Consumer<CreateContainerCmd> cmd = e -> e.withPortBindings(new PortBinding(Ports.Binding.bindPort(fixedExposedPort), new ExposedPort(POSTGRESQL_PORT)));
        postgres = postgres.withCreateContainerCmdModifier(cmd);
    }
    if (network != null) {
        postgres = postgres.withNetwork(network);
    }
    postgres.start();
    return postgres;
}
Also used : CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) Arrays(java.util.Arrays) Ports(com.github.dockerjava.api.model.Ports) Connection(java.sql.Connection) AbstractPostgresCdcIntegrationTest.getConnection(com.hazelcast.jet.cdc.postgres.AbstractPostgresCdcIntegrationTest.getConnection) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) RetryStrategies(com.hazelcast.jet.retry.RetryStrategies) PostgreSQLContainer(org.testcontainers.containers.PostgreSQLContainer) HazelcastSerialParametersRunnerFactory(com.hazelcast.test.HazelcastSerialParametersRunnerFactory) StreamSource(com.hazelcast.jet.pipeline.StreamSource) Network(org.testcontainers.containers.Network) JetException(com.hazelcast.jet.JetException) CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) SQLException(java.sql.SQLException) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Util.entry(com.hazelcast.jet.Util.entry) After(org.junit.After) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) ExposedPort(com.github.dockerjava.api.model.ExposedPort) Assume(org.junit.Assume) PortBinding(com.github.dockerjava.api.model.PortBinding) ChangeRecord(com.hazelcast.jet.cdc.ChangeRecord) AbstractCdcIntegrationTest(com.hazelcast.jet.cdc.AbstractCdcIntegrationTest) Nonnull(javax.annotation.Nonnull) Job(com.hazelcast.jet.Job) UseParametersRunnerFactory(org.junit.runners.Parameterized.UseParametersRunnerFactory) HazelcastInstance(com.hazelcast.core.HazelcastInstance) POSTGRESQL_PORT(org.testcontainers.containers.PostgreSQLContainer.POSTGRESQL_PORT) NightlyTest(com.hazelcast.test.annotation.NightlyTest) HazelcastParametrizedRunner(com.hazelcast.test.HazelcastParametrizedRunner) Pipeline(com.hazelcast.jet.pipeline.Pipeline) Parameter(org.junit.runners.Parameterized.Parameter) Collection(java.util.Collection) Sinks(com.hazelcast.jet.pipeline.Sinks) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Category(org.junit.experimental.categories.Category) Consumer(java.util.function.Consumer) ToxiproxyContainer(org.testcontainers.containers.ToxiproxyContainer) Statement(java.sql.Statement) RUNNING(com.hazelcast.jet.core.JobStatus.RUNNING) RetryStrategy(com.hazelcast.jet.retry.RetryStrategy) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) ExposedPort(com.github.dockerjava.api.model.ExposedPort) PortBinding(com.github.dockerjava.api.model.PortBinding) PostgreSQLContainer(org.testcontainers.containers.PostgreSQLContainer)

Example 13 with CreateContainerCmd

use of com.github.dockerjava.api.command.CreateContainerCmd in project dockerunit by qzagarese.

the class DefaultServiceBuilder method createInstance.

private ServiceInstance createInstance(ServiceDescriptor descriptor, DockerClient client, int i) {
    String containerId = null;
    Status status = null;
    String statusDetails = null;
    CreateContainerCmd cmd = null;
    try {
        cmd = client.createContainerCmd(descriptor.getImage().value());
        cmd = computeContainerName(descriptor, i, cmd);
        cmd = executeOptionBuilders(descriptor, cmd);
        if (descriptor.getCustomisationHook() != null) {
            cmd = executeCustomisationHook(descriptor.getCustomisationHook(), descriptor.getInstance(), cmd);
        }
        containerId = createAndStartContainer(cmd, descriptor.getImage().pull(), client);
        status = Status.STARTED;
        statusDetails = "Started.";
    } catch (Throwable t) {
        if (t instanceof CompletionException) {
            if (t.getCause() != null && t.getCause() instanceof ContainerException) {
                containerId = ((ContainerException) t.getCause()).getContainerId();
                statusDetails = t.getCause().getCause() != null ? t.getCause().getCause().getMessage() : null;
            } else {
                statusDetails = t.getCause() != null ? t.getCause().getMessage() : null;
            }
        } else {
            statusDetails = t.getMessage();
        }
        status = Status.ABORTED;
    }
    return ServiceInstance.builder().containerName(cmd.getName()).containerId(containerId).status(status).statusDetails(statusDetails).build();
}
Also used : Status(com.github.qzagarese.dockerunit.ServiceInstance.Status) CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) ContainerException(com.github.qzagarese.dockerunit.exception.ContainerException) CompletionException(java.util.concurrent.CompletionException)

Example 14 with CreateContainerCmd

use of com.github.dockerjava.api.command.CreateContainerCmd in project dockerunit by qzagarese.

the class DefaultServiceBuilder method executeOptionBuilders.

private CreateContainerCmd executeOptionBuilders(ServiceDescriptor descriptor, CreateContainerCmd cmd) {
    for (Annotation a : descriptor.getOptions()) {
        Class<? extends ExtensionInterpreter<?>> builderType = a.annotationType().getAnnotation(ExtensionMarker.class).value();
        ExtensionInterpreter<?> builder = null;
        Method buildMethod = null;
        try {
            builder = builderType.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate " + ExtensionInterpreter.class.getSimpleName() + " of type " + builderType.getSimpleName() + " to handle annotation " + a.annotationType().getSimpleName() + " that has been detected on class " + descriptor.getInstance().getClass().getName(), e);
        }
        try {
            buildMethod = builderType.getDeclaredMethod("build", new Class<?>[] { ServiceDescriptor.class, CreateContainerCmd.class, a.annotationType() });
            cmd = (CreateContainerCmd) buildMethod.invoke(builder, descriptor, cmd, a);
        } catch (Exception e) {
            throw new RuntimeException("An error occurred while invoking the build method on builder class " + builderType.getName(), e);
        }
    }
    return cmd;
}
Also used : CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) ServiceDescriptor(com.github.qzagarese.dockerunit.internal.ServiceDescriptor) Method(java.lang.reflect.Method) ExtensionInterpreter(com.github.qzagarese.dockerunit.annotation.ExtensionInterpreter) ExtensionMarker(com.github.qzagarese.dockerunit.annotation.ExtensionMarker) Annotation(java.lang.annotation.Annotation) NotFoundException(com.github.dockerjava.api.exception.NotFoundException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) ContainerException(com.github.qzagarese.dockerunit.exception.ContainerException)

Example 15 with CreateContainerCmd

use of com.github.dockerjava.api.command.CreateContainerCmd in project hub-docker-inspector by blackducksoftware.

the class DockerClientManager method ensureContainerRunning.

private String ensureContainerRunning(final DockerClient dockerClient, final String imageId, final String extractorContainerName, final String hubPassword, final String hubApiToken) {
    String oldContainerId;
    final List<Container> containers = dockerClient.listContainersCmd().withShowAll(true).exec();
    final Container extractorContainer = getRunningContainer(containers, extractorContainerName);
    if (extractorContainer != null) {
        logger.debug(String.format("Extractor container status: %s", extractorContainer.getStatus()));
        oldContainerId = extractorContainer.getId();
        if (extractorContainer.getStatus().startsWith("Up")) {
            logger.debug("The extractor container is running; stopping it");
            dockerClient.stopContainerCmd(oldContainerId).exec();
        }
        logger.debug("The extractor container exists; removing it");
        dockerClient.removeContainerCmd(oldContainerId).exec();
    }
    logger.debug(String.format("Creating container %s from image %s", extractorContainerName, imageId));
    final CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(imageId).withStdinOpen(true).withTty(true).withName(extractorContainerName).withCmd("/bin/bash");
    final List<String> envAssignments = new ArrayList<>();
    envAssignments.add(String.format("BD_HUB_PASSWORD=%s", hubPassword));
    envAssignments.add(String.format("BD_HUB_TOKEN=%s", hubApiToken));
    if ((StringUtils.isBlank(config.getHubProxyHost())) && (!StringUtils.isBlank(config.getScanCliOptsEnvVar()))) {
        envAssignments.add(String.format("SCAN_CLI_OPTS=%s", config.getScanCliOptsEnvVar()));
    } else {
    }
    createContainerCmd.withEnv(envAssignments);
    final CreateContainerResponse containerResponse = createContainerCmd.exec();
    final String containerId = containerResponse.getId();
    dockerClient.startContainerCmd(containerId).exec();
    logger.info(String.format("Started container %s from image %s", containerId, imageId));
    return containerId;
}
Also used : CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) Container(com.github.dockerjava.api.model.Container) ArrayList(java.util.ArrayList) CreateContainerResponse(com.github.dockerjava.api.command.CreateContainerResponse)

Aggregations

CreateContainerCmd (com.github.dockerjava.api.command.CreateContainerCmd)15 IOException (java.io.IOException)6 NotFoundException (com.github.dockerjava.api.exception.NotFoundException)4 ExposedPort (com.github.dockerjava.api.model.ExposedPort)4 ContainerException (com.github.qzagarese.dockerunit.exception.ContainerException)4 ArrayList (java.util.ArrayList)4 CompletionException (java.util.concurrent.CompletionException)4 Bind (com.github.dockerjava.api.model.Bind)3 PortBinding (com.github.dockerjava.api.model.PortBinding)3 Volume (com.github.dockerjava.api.model.Volume)3 List (java.util.List)3 DockerClient (com.github.dockerjava.api.DockerClient)2 InternalServerErrorException (com.github.dockerjava.api.exception.InternalServerErrorException)2 Capability (com.github.dockerjava.api.model.Capability)2 Ports (com.github.dockerjava.api.model.Ports)2 VolumesFrom (com.github.dockerjava.api.model.VolumesFrom)2 Status (com.github.qzagarese.dockerunit.ServiceInstance.Status)2 ExtensionInterpreter (com.github.qzagarese.dockerunit.annotation.ExtensionInterpreter)2 ExtensionMarker (com.github.qzagarese.dockerunit.annotation.ExtensionMarker)2 HazelcastInstance (com.hazelcast.core.HazelcastInstance)2