com.spotify.docker.client.messages.PortBinding Java Examples

The following examples show how to use com.spotify.docker.client.messages.PortBinding. 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: HeliosSoloDeployment.java    From helios with Apache License 2.0 6 votes vote down vote up
/**
 * Return the first host port bound to the requested container port.
 *
 * @param containerId   The container in which to find the requested port.
 * @param containerPort The container port to resolve to a host port.
 *
 * @return The first host port bound to the requested container port.
 *
 * @throws HeliosDeploymentException when no host port is found.
 */
private String getHostPort(final String containerId, final int containerPort)
    throws HeliosDeploymentException {
  final String heliosPort = String.format("%d/tcp", containerPort);
  try {
    final NetworkSettings settings = dockerClient.inspectContainer(containerId).networkSettings();
    for (final Map.Entry<String, List<PortBinding>> entry : settings.ports().entrySet()) {
      if (entry.getKey().equals(heliosPort)) {
        return entry.getValue().get(0).hostPort();
      }
    }
  } catch (DockerException | InterruptedException e) {
    throw new HeliosDeploymentException(String.format(
        "unable to find port binding for %s in container %s.",
        heliosPort,
        containerId),
        e);
  }
  throw new HeliosDeploymentException(String.format(
      "unable to find port binding for %s in container %s.",
      heliosPort,
      containerId));
}
 
Example #2
Source File: TaskConfig.java    From helios with Apache License 2.0 6 votes vote down vote up
/**
 * Create a port binding configuration for the job.
 *
 * @return The port bindings.
 */
private Map<String, List<PortBinding>> portBindings() {
  final Map<String, List<PortBinding>> bindings = Maps.newHashMap();
  for (final Map.Entry<String, PortMapping> e : job.getPorts().entrySet()) {
    final PortMapping mapping = e.getValue();
    final Integer jobDefinedExtPort = mapping.getExternalPort();

    // If the job didn't specify an external port, use dynamically allocated ports
    final String externalPort = jobDefinedExtPort == null
                                ? ports.get(e.getKey()).toString() : jobDefinedExtPort.toString();

    final PortBinding binding = PortBinding.of(mapping.getIp(), externalPort);
    final String entry = containerPort(mapping.getInternalPort(), mapping.getProtocol());
    bindings.put(entry, Collections.singletonList(binding));
  }
  return bindings;
}
 
Example #3
Source File: RedisContainer.java    From pay-publicapi with MIT License 6 votes vote down vote up
private static int hostPortNumber(ContainerInfo containerInfo) {
    String redisPortSpec = INTERNAL_PORT + "/tcp";
    PortBinding portBinding;
    try {
        portBinding = Objects.requireNonNull(containerInfo
                .networkSettings()
                .ports())
                .get(redisPortSpec)
                .get(0);
        logger.info("Redis host port: {}", portBinding.hostPort());
        return parseInt(portBinding.hostPort());
    } catch (NullPointerException e) {
        logger.error("Unable to find host port mapping for {} in container {}", redisPortSpec, containerInfo.id());
        throw e;
    }
}
 
Example #4
Source File: DockerContainerClient.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieve the host ports that were opened at runtime for communicating with the docker container. This method
 * is only useful to call after the container is started as the host ports are not known before.
 *
 * @return Optional {@link Map} of container port keys with a {@link List} of {@link PortBinding}s
 */
public Optional<Map<String, List<PortBinding>>> hostPortBindings() {
  // reuse existing containers if they are running
  if (nonNull(startedContainer)) {
    try {
      log.info("Inspecting container '{}' for host ports.", left(startedContainer.id(), SHORT_ID_LENGTH));

      return ofNullable(dockerClient.inspectContainer(startedContainer.id()).networkSettings().ports());
    }
    catch (DockerException | InterruptedException e) {
      log.error("Unable to inspect container for host ports '{}'", left(startedContainer.id(), SHORT_ID_LENGTH), e);
    }
  }

  return empty();
}
 
Example #5
Source File: DockerBasedTestExecutor.java    From pravega with Apache License 2.0 6 votes vote down vote up
private ContainerConfig setContainerConfig(String methodName, String className) {

        Map<String, String> labels = new HashMap<>(2);
        labels.put("testMethodName", methodName);
        labels.put("testClassName", className);

        HostConfig hostConfig = HostConfig.builder()
                .portBindings(ImmutableMap.of(DOCKER_CLIENT_PORT + "/tcp", Arrays.asList(PortBinding.
                        of(LoginClient.MESOS_MASTER, DOCKER_CLIENT_PORT)))).networkMode("docker_gwbridge").build();

        ContainerConfig containerConfig = ContainerConfig.builder()
                .hostConfig(hostConfig)
                .image(IMAGE)
                .user("root")
                .workingDir("/data")
                .cmd("sh", "-c", "java -DmasterIP=" + LoginClient.MESOS_MASTER + " -DexecType=" + getConfig("execType",
                        "LOCAL") + " -Dlog.level=" + LOG_LEVEL +  " -cp /data/build/libs/test-docker-collection.jar io.pravega.test.system." +
                        "SingleJUnitTestRunner " + className + "#" + methodName + " > server.log 2>&1")
                .labels(labels)
                .build();

        return containerConfig;
    }
 
Example #6
Source File: ContainerCommandLineITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@Nullable
public String getHostTcpPort(final String containerPort) {
  Map<String, List<PortBinding>> hostPortBindings = hostPortBindings().orElse(emptyMap());
  List<PortBinding> portBindings = hostPortBindings.get(containerPort + "/tcp");

  if (isNull(portBindings) || portBindings.isEmpty()) {
    // be kind and attempt to find without appendix of tcp
    portBindings = hostPortBindings.get(containerPort);
  }

  if (nonNull(portBindings) && !portBindings.isEmpty()) {
    PortBinding portBinding = portBindings.get(0);

    if(nonNull(portBinding)) {
      return portBinding.hostPort();
    }
  }

  return null;
}
 
Example #7
Source File: HeliosSoloDeploymentTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  this.dockerClient = mock(DockerClient.class);
  this.heliosClient = mock(HeliosClient.class);

  // the anonymous classes to override a method are to workaround the docker-client "messages"
  // having no mutators, fun
  final Info info = mock(Info.class);
  when(info.operatingSystem()).thenReturn("foo");
  when(this.dockerClient.info()).thenReturn(info);

  // mock the call to dockerClient.createContainer so we can test the arguments passed to it
  this.containerConfig = ArgumentCaptor.forClass(ContainerConfig.class);

  final ContainerCreation creation = mock(ContainerCreation.class);
  when(creation.id()).thenReturn(CONTAINER_ID);

  when(this.dockerClient.createContainer(
      this.containerConfig.capture(), anyString())).thenReturn(creation);

  // we have to mock out several other calls to get the HeliosSoloDeployment ctor
  // to return non-exceptionally. the anonymous classes to override a method are to workaround
  // the docker-client "messages" having no mutators, fun
  when(this.dockerClient.info()).thenReturn(info);

  final PortBinding binding = PortBinding.of("192.168.1.1", 5801);
  final ImmutableMap<String, List<PortBinding>> ports =
      ImmutableMap.<String, List<PortBinding>>of("5801/tcp", ImmutableList.of(binding));
  final ContainerInfo containerInfo = mock(ContainerInfo.class);
  final NetworkSettings networkSettings = mock(NetworkSettings.class);
  when(networkSettings.gateway()).thenReturn("a-gate-way");
  when(networkSettings.ports()).thenReturn(ports);
  when(containerInfo.networkSettings()).thenReturn(networkSettings);
  when(this.dockerClient.inspectContainer(CONTAINER_ID)).thenReturn(containerInfo);

  when(this.dockerClient.waitContainer(CONTAINER_ID)).thenReturn(ContainerExit.create(0L));
}
 
Example #8
Source File: GCloudEmulatorManager.java    From flink with Apache License 2.0 5 votes vote down vote up
private static String getPort(Map<String, List<PortBinding>> ports, String internalTCPPort, String label) {
	List<PortBinding> portMappings = ports.get(internalTCPPort + "/tcp");
	if (portMappings == null || portMappings.isEmpty()) {
		LOG.info("| {} Emulator --> NOTHING CONNECTED TO {}/tcp", label, internalTCPPort);
		return null;
	}

	return portMappings.get(0).hostPort();
}
 
Example #9
Source File: PushPullIT.java    From docker-client with Apache License 2.0 5 votes vote down vote up
private static String startAuthedRegistry(final DockerClient client) throws Exception {
  final Map<String, List<PortBinding>> ports = singletonMap(
      "5000/tcp", Collections.singletonList(PortBinding.of("0.0.0.0", 5000)));
  final HostConfig hostConfig = HostConfig.builder().portBindings(ports)
      .binds(ImmutableList.of(
          Resources.getResource("dockerRegistry/auth").getPath() + ":/auth",
          Resources.getResource("dockerRegistry/certs").getPath() + ":/certs"
      ))
      /*
       *  Mounting volumes requires special permissions on Docker >= 1.10.
       *  Until a proper Seccomp profile is in place, run container privileged.
       */
      .privileged(true)
      .build();

  final ContainerConfig containerConfig = ContainerConfig.builder()
      .image(REGISTRY_IMAGE)
      .hostConfig(hostConfig)
      .env(ImmutableList.of(
          "REGISTRY_AUTH=htpasswd",
          "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm",
          "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd",
          "REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt",
          "REGISTRY_HTTP_TLS_KEY=/certs/domain.key",
          "REGISTRY_HTTP_SECRET=super-secret"
      ))
      .build();

  return startAndAwaitContainer(client, containerConfig, REGISTRY_NAME);
}
 
Example #10
Source File: PushPullIT.java    From docker-client with Apache License 2.0 5 votes vote down vote up
private static String startUnauthedRegistry(final DockerClient client) throws Exception {
  final Map<String, List<PortBinding>> ports = singletonMap(
      "5000/tcp", Collections.singletonList(PortBinding.of("0.0.0.0", 5000)));
  final HostConfig hostConfig = HostConfig.builder().portBindings(ports)
      .build();

  final ContainerConfig containerConfig = ContainerConfig.builder()
      .image(REGISTRY_IMAGE)
      .hostConfig(hostConfig)
      .build();

  return startAndAwaitContainer(client, containerConfig, REGISTRY_NAME);
}
 
Example #11
Source File: DockerService.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
public String getBindPort(String containerId, String exposed)
        throws DockerException, InterruptedException {
    ImmutableMap<String, List<PortBinding>> ports = dockerClient
            .inspectContainer(containerId).networkSettings().ports();
    List<PortBinding> exposedPort = ports.get(exposed);
    log.trace("Port list {} -- Exposed port {} = {}", ports, exposed,
            exposedPort);
    if (ports.isEmpty() || exposedPort.isEmpty()) {
        String dockerImage = dockerClient.inspectContainer(containerId)
                .config().image();
        throw new SeleniumJupiterException("Port " + exposed
                + " is not bindable in container " + dockerImage);
    }
    return exposedPort.get(0).hostPort();
}
 
Example #12
Source File: DockerDriverHandler.java    From selenium-jupiter with Apache License 2.0 5 votes vote down vote up
public DockerContainer startNoVncContainer()
        throws DockerException, InterruptedException {

    DockerContainer novncContainer;
    String novncImage = getConfig().getNovncImage();

    if (containerMap.containsKey(novncImage)) {
        log.debug("noVNC container already available");
        novncContainer = containerMap.get(novncImage);

    } else {
        dockerService.pullImage(novncImage);

        Map<String, List<PortBinding>> portBindings = new HashMap<>();
        String defaultNovncPort = getConfig().getNovncPort();
        portBindings.put(defaultNovncPort,
                asList(randomPort(ALL_IPV4_ADDRESSES)));

        String network = getConfig().getDockerNetwork();
        novncContainer = DockerContainer.dockerBuilder(novncImage)
                .portBindings(portBindings).network(network).build();
        String containerId = dockerService.startContainer(novncContainer);
        String novncHost = dockerService.getHost(containerId, network);
        String novncPort = dockerService.getBindPort(containerId,
                defaultNovncPort + "/tcp");
        String novncUrl = format("http://%s:%s/", novncHost, novncPort);
        novncContainer.setContainerId(containerId);
        novncContainer.setContainerUrl(novncUrl);

        containerMap.put(novncImage, novncContainer);
    }

    return novncContainer;
}
 
Example #13
Source File: GCloudEmulatorManager.java    From flink with Apache License 2.0 5 votes vote down vote up
private static String getPort(Map<String, List<PortBinding>> ports, String internalTCPPort, String label) {
	List<PortBinding> portMappings = ports.get(internalTCPPort + "/tcp");
	if (portMappings == null || portMappings.isEmpty()) {
		LOG.info("| {} Emulator {} --> NOTHING CONNECTED TO {}", label, internalTCPPort + "/tcp");
		return null;
	}

	return portMappings.get(0).hostPort();
}
 
Example #14
Source File: ContainerCommandLineITSupport.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Optional<Map<String, List<PortBinding>>> hostPortBindings() {
  return dockerContainerClient.hostPortBindings();
}
 
Example #15
Source File: DockerContainer.java    From selenium-jupiter with Apache License 2.0 4 votes vote down vote up
public Optional<Map<String, List<PortBinding>>> getPortBindings() {
    return portBindings;
}
 
Example #16
Source File: DockerService.java    From selenium-jupiter with Apache License 2.0 4 votes vote down vote up
public synchronized String startContainer(DockerContainer dockerContainer)
        throws DockerException, InterruptedException {
    String imageId = dockerContainer.getImageId();
    log.info("Starting Docker container {}", imageId);
    com.spotify.docker.client.messages.HostConfig.Builder hostConfigBuilder = HostConfig
            .builder();
    com.spotify.docker.client.messages.ContainerConfig.Builder containerConfigBuilder = ContainerConfig
            .builder();

    boolean privileged = dockerContainer.isPrivileged();
    if (privileged) {
        log.trace("Using privileged mode");
        hostConfigBuilder.privileged(true);
        hostConfigBuilder.capAdd("NET_ADMIN", "NET_RAW");
    }
    Optional<String> network = dockerContainer.getNetwork();
    if (network.isPresent()) {
        log.trace("Using network: {}", network.get());
        hostConfigBuilder.networkMode(network.get());
    }
    Optional<Map<String, List<PortBinding>>> portBindings = dockerContainer
            .getPortBindings();
    if (portBindings.isPresent()) {
        log.trace("Using port bindings: {}", portBindings.get());
        hostConfigBuilder.portBindings(portBindings.get());
        containerConfigBuilder.exposedPorts(portBindings.get().keySet());
    }
    Optional<List<String>> binds = dockerContainer.getBinds();
    if (binds.isPresent()) {
        log.trace("Using binds: {}", binds.get());
        hostConfigBuilder.binds(binds.get());
    }
    Optional<List<String>> envs = dockerContainer.getEnvs();
    if (envs.isPresent()) {
        log.trace("Using envs: {}", envs.get());
        containerConfigBuilder.env(envs.get());
    }
    Optional<List<String>> cmd = dockerContainer.getCmd();
    if (cmd.isPresent()) {
        log.trace("Using cmd: {}", cmd.get());
        containerConfigBuilder.cmd(cmd.get());
    }
    Optional<List<String>> entryPoint = dockerContainer.getEntryPoint();
    if (entryPoint.isPresent()) {
        log.trace("Using entryPoint: {}", entryPoint.get());
        containerConfigBuilder.entrypoint(entryPoint.get());
    }

    ContainerConfig createContainer = containerConfigBuilder.image(imageId)
            .hostConfig(hostConfigBuilder.build()).build();
    String containerId = dockerClient.createContainer(createContainer).id();
    dockerClient.startContainer(containerId);

    return containerId;
}
 
Example #17
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 #18
Source File: DockerDriverHandler.java    From selenium-jupiter with Apache License 2.0 4 votes vote down vote up
public DockerContainer startAndroidContainer(String androidImage,
        String deviceName, CloudType cloudType)
        throws DockerException, InterruptedException {

    DockerContainer androidContainer;
    if (containerMap.containsKey(androidImage)) {
        log.trace("Android container already available");
        androidContainer = containerMap.get(androidImage);
    } else {
        // Pull image
        dockerService.pullImage(androidImage);

        // portBindings
        Map<String, List<PortBinding>> portBindings = new HashMap<>();
        String internalAppiumPort = getConfig().getAndroidAppiumPort();
        portBindings.put(internalAppiumPort,
                asList(randomPort(ALL_IPV4_ADDRESSES)));
        String internalNoVncPort = getConfig().getAndroidNoVncPort();
        portBindings.put(internalNoVncPort,
                asList(randomPort(ALL_IPV4_ADDRESSES)));

        // binds
        boolean recording = getConfig().isRecording()
                || getConfig().isRecordingWhenFailure();
        List<String> binds = new ArrayList<>();
        if (recording) {
            binds.add(getDockerPath(hostVideoFolder) + ":/tmp/video");
        }
        if (isAndroidLogging()) {
            binds.add(getDockerPath(hostAndroidLogsFolder)
                    + ":/var/log/supervisor");
        }

        // envs
        String network = getConfig().getDockerNetwork();
        List<String> envs = getAndroidEnvs(deviceName, cloudType,
                recording);

        // Build container
        DockerBuilder dockerBuilder = DockerContainer
                .dockerBuilder(androidImage).portBindings(portBindings)
                .binds(binds).envs(envs).network(network).privileged();

        String androidGenymotionDeviceName = getConfig()
                .getAndroidGenymotionDeviceName();
        boolean useGenymotion = cloudType == GENYMOTION_SAAS
                && !isNullOrEmpty(androidGenymotionDeviceName);
        if (useGenymotion) {
            getGenymotionContainer(dockerBuilder,
                    androidGenymotionDeviceName);
        }

        androidContainer = dockerBuilder.build();
        String containerId = dockerService.startContainer(androidContainer);

        if (useGenymotion) {
            String[] disposeDeviceCommand = { "gmtool", "--cloud", "admin",
                    "stopdisposable", androidGenymotionDeviceName };
            finalizerCommandMap.put(containerId, disposeDeviceCommand);
        }

        String androidHost = dockerService.getHost(containerId, network);
        String androidPort = dockerService.getBindPort(containerId,
                internalAppiumPort + "/tcp");

        String appiumUrl = format("http://%s:%s/wd/hub", androidHost,
                androidPort);
        androidContainer.setContainerId(containerId);
        androidContainer.setContainerUrl(appiumUrl);

        String androidNoVncPort = dockerService.getBindPort(containerId,
                internalNoVncPort + "/tcp");
        androidNoVncUrl = format("http://%s:%s/", androidHost,
                androidNoVncPort);

        containerMap.put(androidImage, androidContainer);
    }
    return androidContainer;
}
 
Example #19
Source File: DockerDriverHandler.java    From selenium-jupiter with Apache License 2.0 4 votes vote down vote up
public DockerContainer startSelenoidContainer()
        throws DockerException, InterruptedException {

    DockerContainer selenoidContainer;
    String selenoidImage = getConfig().getSelenoidImage();
    boolean recording = getConfig().isRecording()
            || getConfig().isRecordingWhenFailure();

    if (containerMap.containsKey(selenoidImage)) {
        log.trace("Selenoid container already available");
        selenoidContainer = containerMap.get(selenoidImage);
    } else {
        // Pull images
        dockerService.pullImage(selenoidImage);
        String recordingImage = getConfig().getRecordingImage();
        if (recording) {
            dockerService.pullImage(recordingImage);
        }

        // portBindings
        Map<String, List<PortBinding>> portBindings = new HashMap<>();
        String defaultSelenoidPort = getConfig().getSelenoidPort();
        String internalSelenoidPort = defaultSelenoidPort;
        portBindings.put(internalSelenoidPort,
                asList(randomPort(ALL_IPV4_ADDRESSES)));

        // binds
        String defaultSocket = dockerService.getDockerDefaultSocket();
        List<String> binds = new ArrayList<>();
        binds.add(defaultSocket + ":" + defaultSocket);
        if (recording) {
            binds.add(getDockerPath(hostVideoFolder)
                    + ":/opt/selenoid/video");
        }

        // entrypoint & cmd
        List<String> entryPoint = asList("");
        String internalBrowserPort = getConfig().getSelenoidPort();
        String browsersJson = selenoidConfig.getBrowsersJsonAsString();
        String browserTimeout = getConfig()
                .getBrowserSessionTimeoutDuration();
        String network = getConfig().getDockerNetwork();
        String dockerStartupTimeout = getConfig()
                .getDockerStartupTimeoutDuration();

        List<String> cmd = asList("sh", "-c",
                "mkdir -p /etc/selenoid/; echo '" + browsersJson
                        + "' > /etc/selenoid/browsers.json; /usr/bin/selenoid"
                        + " -listen :" + internalBrowserPort
                        + " -service-startup-timeout "
                        + dockerStartupTimeout
                        + " -conf /etc/selenoid/browsers.json"
                        + " -video-output-dir /opt/selenoid/video/"
                        + " -timeout " + browserTimeout
                        + " -container-network " + network + " -limit "
                        + getDockerBrowserCount());

        // envs
        List<String> envs = selenoidConfig.getDockerEnvs();

        if (recording) {
            envs.add("OVERRIDE_VIDEO_OUTPUT_DIR="
                    + getDockerPath(hostVideoFolder));
        }

        // Build container
        DockerBuilder dockerBuilder = DockerContainer
                .dockerBuilder(selenoidImage).portBindings(portBindings)
                .binds(binds).cmd(cmd).entryPoint(entryPoint).envs(envs)
                .network(network);
        selenoidContainer = dockerBuilder.build();
        containerMap.put(selenoidImage, selenoidContainer);

        String containerId = dockerService
                .startContainer(selenoidContainer);
        selenoidContainer.setContainerId(containerId);
        String selenoidHost = dockerService.getHost(containerId, network);
        String selenoidPort = dockerService.getBindPort(containerId,
                internalSelenoidPort + "/tcp");
        String selenoidUrl = format("http://%s:%s/wd/hub", selenoidHost,
                selenoidPort);

        selenoidContainer.setContainerUrl(selenoidUrl);
        log.trace("Selenium server URL {}", selenoidUrl);
    }
    return selenoidContainer;
}
 
Example #20
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 #21
Source File: CommandLine.java    From nexus-public with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Retrieve the {@link PortBinding} that are represented in the container for this host, to request this is only
 * valuable after a containers has been started, as ports are inspected at runtime for random ones assigned.
 *
 * @return Optional of {@link Map} of {@link PortBinding}s.
 */
Optional<Map<String, List<PortBinding>>> hostPortBindings();