com.spotify.docker.client.DefaultDockerClient.Builder Java Examples

The following examples show how to use com.spotify.docker.client.DefaultDockerClient.Builder. 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: DockerService.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
public DockerService(Config config, InternalPreferences preferences) {
    this.config = config;
    this.preferences = preferences;

    dockerDefaultSocket = getConfig().getDockerDefaultSocket();
    dockerWaitTimeoutSec = getConfig().getDockerWaitTimeoutSec();
    dockerPollTimeMs = getConfig().getDockerPollTimeMs();

    String dockerServerUrl = getConfig().getDockerServerUrl();
    Builder dockerClientBuilder = null;
    if (dockerServerUrl.isEmpty()) {
        try {
            dockerClientBuilder = DefaultDockerClient.fromEnv();
        } catch (DockerCertificateException e) {
            throw new SeleniumJupiterException(e);
        }
    } else {
        log.debug("Using Docker server URL {}", dockerServerUrl);
        dockerClientBuilder = DefaultDockerClient.builder()
                .uri(dockerServerUrl);
    }
    dockerClient = dockerClientBuilder.build();
}
 
Example #2
Source File: SingularityExecutorModule.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
public DockerClient providesDockerClient(
  SingularityExecutorConfiguration configuration
) {
  Builder dockerClientBuilder = DefaultDockerClient
    .builder()
    .uri(URI.create("unix://localhost/var/run/docker.sock"))
    .connectionPoolSize(configuration.getDockerClientConnectionPoolSize());

  if (configuration.getDockerAuthConfig().isPresent()) {
    SingularityExecutorDockerAuthConfig authConfig = configuration
      .getDockerAuthConfig()
      .get();

    if (authConfig.isFromDockerConfig()) {
      try {
        dockerClientBuilder.registryAuth(RegistryAuth.fromDockerConfig().build());
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      dockerClientBuilder.registryAuth(
        RegistryAuth
          .builder()
          .email(authConfig.getEmail())
          .username(authConfig.getUsername())
          .password(authConfig.getPassword())
          .serverAddress(authConfig.getServerAddress())
          .build()
      );
    }
  }

  return dockerClientBuilder.build();
}
 
Example #3
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 #4
Source File: DockerClientFactory.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This method returns the DockerClient dependent on the current OS.
 * 
 * @return
 * @throws DockerCertificateException
 * @throws IOException
 * @throws InterruptedException
 */
public DockerClient getDockerClient() throws DockerCertificateException, IOException, InterruptedException {
	DockerClient client = null;

	// If this is not Linux, then we have to find DOCKER_HOST
	if (!Platform.getOS().equals(Platform.OS_LINUX)) {

		// See if we can get the DOCKER_HOST environment variaable
		String dockerHost = System.getenv("DOCKER_HOST");
		if (dockerHost == null) {

			// If not, run a script to see if we can get it
			File script = getDockerConnectionScript();
			String[] scriptExec = null;
			if (Platform.getOS().equals(Platform.OS_MACOSX)) {
				scriptExec = new String[] { script.getAbsolutePath() };
			} else if (Platform.getOS().equals(Platform.OS_WIN32)) {
				scriptExec = new String[] { "cmd.exe", "/C", script.getAbsolutePath() };
			}

			// Execute the script to get the DOCKER vars.
			Process process = new ProcessBuilder(scriptExec).start();
			process.waitFor();
			int exitValue = process.exitValue();
			if (exitValue == 0) {

				// Read them into a Properties object
				InputStream processInputStream = process.getInputStream();
				Properties dockerSettings = new Properties();
				// Properties.load screws up windows path separators
				// so if windows, just get the string from the stream
				if (Platform.getOS().equals(Platform.OS_WIN32)) {
					String result = streamToString(processInputStream).trim();
					String[] dockerEnvs = result.split(System.lineSeparator());
					for (String s : dockerEnvs) {
						String[] env = s.split("=");
						dockerSettings.put(env[0], env[1]);
					}
				} else {
					dockerSettings.load(processInputStream);
				}
				
				// Create the Builder object that wil build the DockerClient
				Builder builder = new Builder();

				// Get the DOCKER_HOST and CERT_PATH vars
				String endpoint = dockerSettings.getProperty("DOCKER_HOST");
				Path dockerCertPath = Paths.get(dockerSettings.getProperty("DOCKER_CERT_PATH"));

				System.out.println("DOCKERHOST: " + endpoint);
				System.out.println("DOCKER CERT PATH: " + dockerSettings.getProperty("DOCKER_CERT_PATH"));
				// Set up the certificates
				DockerCertificates certs = DockerCertificates.builder().dockerCertPath(dockerCertPath).build();

				// Set the data need for the builder.
				String stripped = endpoint.replaceAll(".*://", "");
				HostAndPort hostAndPort = HostAndPort.fromString(stripped);
				String hostText = hostAndPort.getHostText();
				String scheme = certs != null ? "https" : "http";
				int port = hostAndPort.getPortOrDefault(2375);
				String address = hostText;
				builder.uri(scheme + "://" + address + ":" + port);
				if (certs != null) {
					builder.dockerCertificates(certs);
				}

				// Build the Dockerclient!
				client = builder.build();

			} else {
				// log what happened if the process did not end as expected
				// an exit value of 1 should indicate no connection found
				InputStream processErrorStream = process.getErrorStream();
				String errorMessage = streamToString(processErrorStream);
				logger.error("Error in getting DOCKER variables: " + errorMessage);
			}
		} else {
			client = DefaultDockerClient.fromEnv().build();
		}
	} else {
		// It was equal to Linux, so just use the default stuff.
		client = DefaultDockerClient.fromEnv().build();
	}

	return client;
}
 
Example #5
Source File: SingularityExecutorModule.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
public LocalDownloadServiceFetcher provideDownloadFetcher(
  SingularityS3Configuration s3Configuration,
  SingularityExecutorConfiguration executorConfiguration,
  ObjectMapper objectMapper
) {
  if (s3Configuration.getLocalDownloadSocket().isPresent()) {
    HttpClient httpClient = new HttpClient(
      new HttpClientTransportOverUnixSockets(
        s3Configuration.getLocalDownloadSocket().get()
      ),
      null
    );
    return new UnixLocalDownloadServiceFetcher(
      httpClient,
      objectMapper,
      executorConfiguration,
      s3Configuration
    );
  } else {
    AsyncHttpClientConfig.Builder configBldr = new AsyncHttpClientConfig.Builder();
    configBldr.setRequestTimeout(
      (int) executorConfiguration.getLocalDownloadServiceTimeoutMillis()
    );
    configBldr.setPooledConnectionIdleTimeout(
      (int) executorConfiguration.getLocalDownloadServiceTimeoutMillis()
    );
    configBldr.addRequestFilter(
      new ThrottleRequestFilter(
        executorConfiguration.getLocalDownloadServiceMaxConnections()
      )
    );
    return new HttpLocalDownloadServiceFetcher(
      new AsyncHttpClient(configBldr.build()),
      objectMapper,
      executorConfiguration,
      s3Configuration
    );
  }
}