Search in sources :

Example 6 with CreateContainerCmd

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

the class GenericContainer method tryStart.

private void tryStart(Profiler profiler) {
    try {
        String dockerImageName = image.get();
        logger().debug("Starting container: {}", dockerImageName);
        logger().info("Creating container for image: {}", dockerImageName);
        profiler.start("Create container");
        CreateContainerCmd createCommand = dockerClient.createContainerCmd(dockerImageName);
        applyConfiguration(createCommand);
        containerId = createCommand.exec().getId();
        logger().info("Starting container with ID: {}", containerId);
        profiler.start("Start container");
        dockerClient.startContainerCmd(containerId).exec();
        // For all registered output consumers, start following as close to container startup as possible
        this.logConsumers.forEach(this::followOutput);
        logger().info("Container {} is starting: {}", dockerImageName, containerId);
        // Tell subclasses that we're starting
        profiler.start("Inspecting container");
        containerInfo = dockerClient.inspectContainerCmd(containerId).exec();
        containerName = containerInfo.getName();
        profiler.start("Call containerIsStarting on subclasses");
        containerIsStarting(containerInfo);
        // Wait until the container is running (may not be fully started)
        profiler.start("Wait until container has started properly, or there's evidence it failed to start.");
        if (!this.startupCheckStrategy.waitUntilStartupSuccessful(dockerClient, containerId)) {
            // (Exception thrown here will be caught below and wrapped)
            throw new IllegalStateException("Container did not start correctly.");
        }
        profiler.start("Wait until container started properly");
        waitUntilContainerStarted();
        logger().info("Container {} started", dockerImageName);
        containerIsStarted(containerInfo);
    } catch (Exception e) {
        logger().error("Could not start container", e);
        // Log output if startup failed, either due to a container failure or exception (including timeout)
        logger().error("Container log output (if any) will follow:");
        FrameConsumerResultCallback resultCallback = new FrameConsumerResultCallback();
        resultCallback.addConsumer(STDOUT, new Slf4jLogConsumer(logger()));
        resultCallback.addConsumer(STDERR, new Slf4jLogConsumer(logger()));
        dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true).exec(resultCallback);
        // Try to ensure that container log output is shown before proceeding
        try {
            resultCallback.getCompletionLatch().await(1, TimeUnit.MINUTES);
        } catch (InterruptedException ignored) {
        // Cannot do anything at this point
        }
        throw new ContainerLaunchException("Could not create/start container", e);
    } finally {
        profiler.stop();
    }
}
Also used : CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) FrameConsumerResultCallback(org.testcontainers.containers.output.FrameConsumerResultCallback) Slf4jLogConsumer(org.testcontainers.containers.output.Slf4jLogConsumer) IOException(java.io.IOException)

Example 7 with CreateContainerCmd

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

the class DefaultServiceBuilder method createInstance.

private ServiceInstance createInstance(TestDescriptor descriptor, DockerClient client, int i) {
    CreateContainerCmd 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);
    }
    String containerId = null;
    Status status = null;
    String statusDetails = null;
    try {
        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 : CreateContainerCmd(com.github.dockerjava.api.command.CreateContainerCmd) Status(com.github.qzagarese.dockerunit.ServiceInstance.Status) ContainerException(com.github.qzagarese.dockerunit.exception.ContainerException) CompletionException(java.util.concurrent.CompletionException)

Example 8 with CreateContainerCmd

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

the class DefaultServiceBuilder method executeOptionBuilders.

private CreateContainerCmd executeOptionBuilders(TestDescriptor 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<?>[] { TestDescriptor.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) Method(java.lang.reflect.Method) ExtensionInterpreter(com.github.qzagarese.dockerunit.annotation.ExtensionInterpreter) ExtensionMarker(com.github.qzagarese.dockerunit.annotation.ExtensionMarker) TestDescriptor(com.github.qzagarese.dockerunit.internal.TestDescriptor) 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 9 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 10 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)10 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 NotFoundException (com.github.dockerjava.api.exception.NotFoundException)3 Bind (com.github.dockerjava.api.model.Bind)3 Volume (com.github.dockerjava.api.model.Volume)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 DockerClient (com.github.dockerjava.api.DockerClient)2 InternalServerErrorException (com.github.dockerjava.api.exception.InternalServerErrorException)2 Capability (com.github.dockerjava.api.model.Capability)2 ExposedPort (com.github.dockerjava.api.model.ExposedPort)2 VolumesFrom (com.github.dockerjava.api.model.VolumesFrom)2 ContainerException (com.github.qzagarese.dockerunit.exception.ContainerException)2 HashSet (java.util.HashSet)2 Optional (java.util.Optional)2 Set (java.util.Set)2 CompletionException (java.util.concurrent.CompletionException)2 CreateContainerResponse (com.github.dockerjava.api.command.CreateContainerResponse)1