Java Code Examples for com.spotify.docker.client.messages.ContainerCreation#id()

The following examples show how to use com.spotify.docker.client.messages.ContainerCreation#id() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DockerContainerManager.java    From simpleci with MIT License 6 votes vote down vote up
public String runContainer(ContainerConfig.Builder containerConfigBuilder, String containerName) throws DockerException {
    try {
        final ContainerConfig containerConfig = containerConfigBuilder.build();
        final ContainerCreation creation;

        creation = dockerClient.createContainer(containerConfig, containerName);

        final String id = creation.id();
        dockerClient.startContainer(id);
        return id;
    } catch (InterruptedException e) {
        logger.error("", e);
    }

    return null;
}
 
Example 2
Source File: PushPullIT.java    From docker-client with Apache License 2.0 5 votes vote down vote up
private static String startAndAwaitContainer(final DockerClient client,
                                             final ContainerConfig containerConfig,
                                             final String containerName)
    throws Exception {
  final ContainerCreation creation = client.createContainer(containerConfig, containerName);
  final String containerId = creation.id();
  client.startContainer(containerId);
  awaitRunning(client, containerId);
  return containerId;
}
 
Example 3
Source File: SyslogRedirectionTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  try (final DockerClient docker = getNewDockerClient()) {
    // Build an image with an ENTRYPOINT and CMD prespecified
    final String dockerDirectory = Resources.getResource("syslog-test-image").getPath();
    docker.build(Paths.get(dockerDirectory), testImage);

    // Figure out the host IP from the container's point of view (needed for syslog)
    final ContainerConfig config = ContainerConfig.builder()
        .image(BUSYBOX)
        .cmd(asList("ip", "route", "show"))
        .build();
    final ContainerCreation creation = docker.createContainer(config);
    final String containerId = creation.id();
    docker.startContainer(containerId);

    // Wait for the container to exit.
    // If we don't wait, docker.logs() might return an epmty string because the container
    // cmd hasn't run yet.
    docker.waitContainer(containerId);

    final String log;
    try (LogStream logs = docker.logs(containerId, stdout(), stderr())) {
      log = logs.readFully();
    }

    final Matcher m = DEFAULT_GATEWAY_PATTERN.matcher(log);
    if (m.find()) {
      syslogHost = m.group("gateway");
    } else {
      fail("couldn't determine the host address from '" + log + "'");
    }
  }
}
 
Example 4
Source File: ReapingTest.java    From helios with Apache License 2.0 5 votes vote down vote up
private void startContainer(final String name)
    throws DockerException, InterruptedException {
  docker.pull(BUSYBOX);
  final HostConfig hostConfig = HostConfig.builder().build();
  final ContainerConfig config = ContainerConfig.builder()
      .image(BUSYBOX)
      .cmd(IDLE_COMMAND)
      .hostConfig(hostConfig)
      .build();
  final ContainerCreation creation = docker.createContainer(config, name);
  final String containerId = creation.id();
  docker.startContainer(containerId);
}
 
Example 5
Source File: TaskRunner.java    From helios with Apache License 2.0 5 votes vote down vote up
private String startContainer(final String image, final Optional<String> dockerVersion)
    throws InterruptedException, DockerException {

  // Get container image info
  final ImageInfo imageInfo = docker.inspectImage(image);
  if (imageInfo == null) {
    throw new HeliosRuntimeException("docker inspect image returned null on image " + image);
  }

  // Create container
  final HostConfig hostConfig = config.hostConfig(dockerVersion);
  final ContainerConfig containerConfig = config.containerConfig(imageInfo, dockerVersion)
      .toBuilder()
      .hostConfig(hostConfig)
      .build();
  listener.creating();
  final ContainerCreation container = docker.createContainer(containerConfig, containerName);
  log.info("created container: {}: {}, {}", config, container, containerConfig);
  listener.created(container.id());

  // Start container
  log.info("starting container: {}: {} {}", config, container.id(), hostConfig);
  listener.starting();
  docker.startContainer(container.id());
  log.info("started container: {}: {}", config, container.id());
  listener.started();

  return container.id();
}
 
Example 6
Source File: GCloudEmulatorManager.java    From flink with Apache License 2.0 4 votes vote down vote up
public static void launchDocker() throws DockerException, InterruptedException, DockerCertificateException {
	// Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars
	docker = DefaultDockerClient.fromEnv().build();

	terminateAndDiscardAnyExistingContainers(true);

	LOG.info("");
	LOG.info("/===========================================");
	LOG.info("| GCloud Emulator");

	ContainerInfo containerInfo;
	String id;

	try {
		docker.inspectImage(DOCKER_IMAGE_NAME);
	} catch (ImageNotFoundException e) {
		// No such image so we must download it first.
		LOG.info("| - Getting docker image \"{}\"", DOCKER_IMAGE_NAME);
		docker.pull(DOCKER_IMAGE_NAME, message -> {
			if (message.id() != null && message.progress() != null) {
				LOG.info("| - Downloading > {} : {}", message.id(), message.progress());
			}
		});
	}

	// No such container. Good, we create one!
	LOG.info("| - Creating new container");

	// Bind container ports to host ports
	final Map<String, List<PortBinding>> portBindings = new HashMap<>();
	portBindings.put(INTERNAL_PUBSUB_PORT, Collections.singletonList(PortBinding.randomPort("0.0.0.0")));

	final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();

	// Create new container with exposed ports
	final ContainerConfig containerConfig = ContainerConfig.builder()
		.hostConfig(hostConfig)
		.exposedPorts(INTERNAL_PUBSUB_PORT)
		.image(DOCKER_IMAGE_NAME)
		.cmd("sh", "-c", "mkdir -p /opt/data/pubsub ; gcloud beta emulators pubsub start --data-dir=/opt/data/pubsub  --host-port=0.0.0.0:" + INTERNAL_PUBSUB_PORT)
		.build();

	final ContainerCreation creation = docker.createContainer(containerConfig, CONTAINER_NAME_JUNIT);
	id = creation.id();

	containerInfo = docker.inspectContainer(id);

	if (!containerInfo.state().running()) {
		LOG.warn("| - Starting it up ....");
		docker.startContainer(id);
		Thread.sleep(1000);
	}

	containerInfo = docker.inspectContainer(id);

	dockerIpAddress = "127.0.0.1";

	Map<String, List<PortBinding>> ports = containerInfo.networkSettings().ports();

	assertNotNull("Unable to retrieve the ports where to connect to the emulators", ports);
	assertEquals("We expect 1 port to be mapped", 1, ports.size());

	pubsubPort = getPort(ports, INTERNAL_PUBSUB_PORT, "PubSub");

	LOG.info("| Waiting for the emulators to be running");

	// PubSub exposes an "Ok" at the root url when running.
	if (!waitForOkStatus("PubSub", pubsubPort)) {
		// Oops, we did not get an "Ok" within 10 seconds
		startHasFailedKillEverything();
	}
	LOG.info("\\===========================================");
	LOG.info("");
}
 
Example 7
Source File: DockerContainer.java    From docker-elastic-agents-plugin with Apache License 2.0 4 votes vote down vote up
public static DockerContainer create(CreateAgentRequest request, PluginSettings settings, DockerClient docker,
                                     ConsoleLogAppender consoleLogAppender) throws InterruptedException, DockerException {
    String containerName = UUID.randomUUID().toString();

    HashMap<String, String> labels = labelsFrom(request);
    String imageName = image(request.properties());
    List<String> env = environmentFrom(request, settings, containerName);

    try {
        docker.inspectImage(imageName);
        if (settings.pullOnContainerCreate()) {
            consoleLogAppender.accept("Pulling a fresh version of " + imageName + ".");
            LOG.info("Pulling a fresh version of " + imageName + ".");
            docker.pull(imageName);
        }
    } catch (ImageNotFoundException ex) {
        consoleLogAppender.accept("Image " + imageName + " not found, attempting to download.");
        LOG.info("Image " + imageName + " not found, attempting to download.");
        docker.pull(imageName);
    }

    ContainerConfig.Builder containerConfigBuilder = ContainerConfig.builder();
    if (StringUtils.isNotBlank(request.properties().get("Command"))) {
        containerConfigBuilder.cmd(splitIntoLinesAndTrimSpaces(request.properties().get("Command")).toArray(new String[]{}));
    }

    final String hostConfig = request.properties().get("Hosts");
    final String reservedMemory = request.properties().get("ReservedMemory");
    final String maxMemory = request.properties().get("MaxMemory");
    final String cpus = request.properties().get("Cpus");
    final String volumeMounts = request.properties().get("Mounts");

    HostConfig.Builder hostBuilder = HostConfig.builder()
            .privileged(privileged(request.properties()))
            .extraHosts(new Hosts(hostConfig))
            .memoryReservation(new MemorySpecification(reservedMemory).getMemory())
            .memory(new MemorySpecification(maxMemory).getMemory());

    CpusSpecification cpusValue = new CpusSpecification(cpus);
    if (cpusValue.getCpus() != null) {
        hostBuilder
                .cpuPeriod(cpusValue.getCpuPeriod())
                .cpuQuota(cpusValue.getCpuQuota());
    }
    if (volumeMounts != null) {
        hostBuilder.appendBinds(Util.splitIntoLinesAndTrimSpaces(volumeMounts));
    }

    ContainerConfig containerConfig = containerConfigBuilder
            .image(imageName)
            .labels(labels)
            .env(env)
            .hostConfig(hostBuilder.build())
            .build();

    consoleLogAppender.accept(String.format("Creating container: %s", containerName));
    ContainerCreation container = docker.createContainer(containerConfig, containerName);
    String id = container.id();

    ContainerInfo containerInfo = docker.inspectContainer(id);

    LOG.debug("Created container " + containerName);
    consoleLogAppender.accept(String.format("Starting container: %s", containerName));
    docker.startContainer(containerName);
    consoleLogAppender.accept(String.format("Started container: %s", containerName));
    LOG.debug("container " + containerName + " started");
    return new DockerContainer(id, containerName, request.jobIdentifier(), containerInfo.created(), request.properties(), request.environment());
}
 
Example 8
Source File: DockerContainerClient.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private Optional<ContainerInfo> runAndPullIfNotExist(String commands) {
  // assure that we don't have multiple threads set the started container
  synchronized (reuseStartedContainerLock) {
    // reuse existing containers if they are running
    if (nonNull(startedContainer)) {
      log.info("Using existing container '{}' for image '{}'", left(startedContainer.id(), SHORT_ID_LENGTH), image);
      return of(startedContainer);
    }

    if (pullIfNotExist().isPresent()) {
      try {
        ContainerCreation container = dockerClient
            .createContainer(ContainerConfig
                .builder()
                .hostConfig(hostConfig)
                .exposedPorts(hostConfig.portBindings().keySet())
                .image(image)
                .env(env)
                .cmd(cmd(commands))
                .build());

        String containerId = container.id();
        String shortId = left(containerId, SHORT_ID_LENGTH);

        startedContainer = dockerClient.inspectContainer(containerId);

        log.info("Attempting to run container '{}' with commands '{}' for image '{}'", shortId, commands, image);

        dockerClient.startContainer(containerId);

        log.info("Successfully run container '{}' with commands '{}' for image '{}'", shortId, commands, image);

        return of(startedContainer);
      }
      catch (Exception e) {
        log.error("Failed to run container for image '{}'", image, e);
      }
    }

    return empty();
  }
}
 
Example 9
Source File: GCloudEmulatorManager.java    From flink with Apache License 2.0 4 votes vote down vote up
public static void launchDocker() throws DockerException, InterruptedException, DockerCertificateException {
	// Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars
	docker = DefaultDockerClient.fromEnv().build();

	terminateAndDiscardAnyExistingContainers(true);

	LOG.info("");
	LOG.info("/===========================================");
	LOG.info("| GCloud Emulator");

	ContainerInfo containerInfo;
	String id;

	try {
		docker.inspectImage(DOCKER_IMAGE_NAME);
	} catch (ImageNotFoundException e) {
		// No such image so we must download it first.
		LOG.info("| - Getting docker image \"{}\"", DOCKER_IMAGE_NAME);
		docker.pull(DOCKER_IMAGE_NAME, message -> {
			if (message.id() != null && message.progress() != null) {
				LOG.info("| - Downloading > {} : {}", message.id(), message.progress());
			}
		});
	}

	// No such container. Good, we create one!
	LOG.info("| - Creating new container");

	// Bind container ports to host ports
	final Map<String, List<PortBinding>> portBindings = new HashMap<>();
	portBindings.put(INTERNAL_PUBSUB_PORT, Collections.singletonList(PortBinding.randomPort("0.0.0.0")));

	final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();

	// Create new container with exposed ports
	final ContainerConfig containerConfig = ContainerConfig.builder()
		.hostConfig(hostConfig)
		.exposedPorts(INTERNAL_PUBSUB_PORT)
		.image(DOCKER_IMAGE_NAME)
		.cmd("sh", "-c", "mkdir -p /opt/data/pubsub ; gcloud beta emulators pubsub start --data-dir=/opt/data/pubsub --host-port=0.0.0.0:" + INTERNAL_PUBSUB_PORT)
		.build();

	final ContainerCreation creation = docker.createContainer(containerConfig, CONTAINER_NAME_JUNIT);
	id = creation.id();

	containerInfo = docker.inspectContainer(id);

	if (!containerInfo.state().running()) {
		LOG.warn("| - Starting it up ....");
		docker.startContainer(id);
		Thread.sleep(1000);
	}

	containerInfo = docker.inspectContainer(id);

	dockerIpAddress = "127.0.0.1";

	Map<String, List<PortBinding>> ports = containerInfo.networkSettings().ports();

	assertNotNull("Unable to retrieve the ports where to connect to the emulators", ports);
	assertEquals("We expect 1 port to be mapped", 1, ports.size());

	pubsubPort = getPort(ports, INTERNAL_PUBSUB_PORT, "PubSub");

	LOG.info("| Waiting for the emulators to be running");

	// PubSub exposes an "Ok" at the root url when running.
	if (!waitForOkStatus("PubSub", pubsubPort)) {
		// Oops, we did not get an "Ok" within 10 seconds
		startHasFailedKillEverything();
	}
	LOG.info("\\===========================================");
	LOG.info("");
}