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();
}
}
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();
}
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;
}
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;
}
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;
}
Aggregations