com.spotify.docker.client.exceptions.DockerCertificateException Java Examples

The following examples show how to use com.spotify.docker.client.exceptions.DockerCertificateException. 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: DockerCertificates.java    From docker-client with Apache License 2.0 6 votes vote down vote up
private PrivateKey readPrivateKey(final Path file)
    throws IOException, InvalidKeySpecException, DockerCertificateException {
  try (final BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
       final PEMParser pemParser = new PEMParser(reader)) {

    final Object readObject = pemParser.readObject();

    if (readObject instanceof PEMKeyPair) {
      final PEMKeyPair clientKeyPair = (PEMKeyPair) readObject;
      return generatePrivateKey(clientKeyPair.getPrivateKeyInfo());
    } else if (readObject instanceof PrivateKeyInfo) {
      return generatePrivateKey((PrivateKeyInfo) readObject);
    }

    throw new DockerCertificateException("Can not generate private key from file: "
        + file.toString());
  }
}
 
Example #2
Source File: AbstractDockerMojo.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
protected DockerClient buildDockerClient() throws MojoExecutionException {

    final DefaultDockerClient.Builder builder;
    try {
      builder = getBuilder();

      final String dockerHost = rawDockerHost();
      if (!isNullOrEmpty(dockerHost)) {
        builder.uri(dockerHost);
      }
      final Optional<DockerCertificatesStore> certs = dockerCertificates();
      if (certs.isPresent()) {
        builder.dockerCertificates(certs.get());
      }
    } catch (DockerCertificateException ex) {
      throw new MojoExecutionException("Cannot build DockerClient due to certificate problem", ex);
    }

    builder.registryAuthSupplier(authSupplier());

    return builder.build();
  }
 
Example #3
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 #4
Source File: DockerClientFactory.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
private static void setupCerts(PluginSettings pluginSettings, DefaultDockerClient.Builder builder) throws IOException, DockerCertificateException {
    if (isBlank(pluginSettings.getDockerCACert()) || isBlank(pluginSettings.getDockerClientCert()) || isBlank(pluginSettings.getDockerClientKey())) {
        LOG.warn("Missing docker certificates, will attempt to connect without certificates");
        return;
    }

    Path certificateDir = Files.createTempDirectory(UUID.randomUUID().toString());
    File tempDirectory = certificateDir.toFile();

    try {
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CA_CERT_NAME), pluginSettings.getDockerCACert(), StandardCharsets.UTF_8);
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CLIENT_CERT_NAME), pluginSettings.getDockerClientCert(), StandardCharsets.UTF_8);
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CLIENT_KEY_NAME), pluginSettings.getDockerClientKey(), StandardCharsets.UTF_8);
        builder.dockerCertificates(new DockerCertificates(certificateDir));
    } finally {
        FileUtils.deleteDirectory(tempDirectory);
    }
}
 
Example #5
Source File: DockerClientFactory.java    From docker-elastic-agents-plugin with Apache License 2.0 6 votes vote down vote up
private static void setupCerts(PluginSettings pluginSettings, DefaultDockerClient.Builder builder) throws IOException, DockerCertificateException {
    if (isBlank(pluginSettings.getDockerCACert()) || isBlank(pluginSettings.getDockerClientCert()) || isBlank(pluginSettings.getDockerClientKey())) {
        LOG.warn("Missing docker certificates, will attempt to connect without certificates");
        return;
    }

    Path certificateDir = Files.createTempDirectory(UUID.randomUUID().toString());
    File tempDirectory = certificateDir.toFile();

    try {
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CA_CERT_NAME), pluginSettings.getDockerCACert(), StandardCharsets.UTF_8);
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CLIENT_CERT_NAME), pluginSettings.getDockerClientCert(), StandardCharsets.UTF_8);
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CLIENT_KEY_NAME), pluginSettings.getDockerClientKey(), StandardCharsets.UTF_8);
        builder.dockerCertificates(new DockerCertificates(certificateDir));
    } finally {
        FileUtils.deleteDirectory(tempDirectory);
    }
}
 
Example #6
Source File: ConnectionPoolTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that running a parallel operation does not break DefaultDockerClient.
 * Fixes issue #446.
 *
 * @throws Exception on error.
 */
@Test
public void testParallelOperation() throws Exception {
  final ExecutorService executor = Executors.newFixedThreadPool(5);
  List<Future<Exception>> tasks = new ArrayList<>(20);
  for (int i = 0; i < 20; i++) {
    tasks.add(executor.submit(
            new Callable<Exception>() {
              @Override
              public Exception call() throws Exception {
                try (DockerClient docker = DefaultDockerClient.fromEnv().build()) {
                  docker.pull(ConnectionPoolTest.BUSYBOX_LATEST);
                  docker.pull(ConnectionPoolTest.BUSYBOX_BUILDROOT_2013_08_1);
                } catch (InterruptedException | DockerException | DockerCertificateException e) {
                  ConnectionPoolTest.log.error(
                          "Error running task: {}", e.getMessage(), e
                  );
                  return e;
                }
                return null;
              }
            }
            )
    );
  }
  executor.shutdown();
  executor.awaitTermination(30, TimeUnit.SECONDS);
  for (final Future<Exception> task : tasks) {
    MatcherAssert.assertThat(task.get(), Matchers.nullValue());
  }
}
 
Example #7
Source File: DockerCertificatesTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test(expected = DockerCertificateException.class)
public void testBadDockerCertificates() throws Exception {
  // try building a DockerCertificates with specifying a cert path to something that
  // isn't a cert
  DockerCertificates.builder()
      .dockerCertPath(getResourceFile("dockerInvalidSslDirectory"))
      .build();
}
 
Example #8
Source File: DockerCertificates.java    From docker-client with Apache License 2.0 5 votes vote down vote up
public Optional<DockerCertificatesStore> build() throws DockerCertificateException {
  if (this.caCertPath == null || this.clientKeyPath == null || this.clientCertPath == null) {
    log.debug("caCertPath, clientKeyPath or clientCertPath not specified, not using SSL");
    return Optional.absent();
  } else if (Files.exists(this.caCertPath) && Files.exists(this.clientKeyPath)
             && Files.exists(this.clientCertPath)) {
    return Optional.of((DockerCertificatesStore) new DockerCertificates(this));
  } else {
    log.debug("{}, {} or {} does not exist, not using SSL", this.caCertPath, this.clientKeyPath,
              this.clientCertPath);
    return Optional.absent();
  }
}
 
Example #9
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link DefaultDockerClient} builder prepopulated with values loaded from the
 * DOCKER_HOST and DOCKER_CERT_PATH environment variables.
 *
 * @return Returns a builder that can be used to further customize and then build the client.
 * @throws DockerCertificateException if we could not build a DockerCertificates object
 */
public static Builder fromEnv() throws DockerCertificateException {
  final String endpoint = DockerHost.endpointFromEnv();
  final Path dockerCertPath = Paths.get(Iterables.find(
      Arrays.asList(DockerHost.certPathFromEnv(),
          DockerHost.configPathFromEnv(),
          DockerHost.defaultCertPath()),
      Predicates.notNull()));

  final Builder builder = new Builder();

  final Optional<DockerCertificatesStore> certs = DockerCertificates.builder()
      .dockerCertPath(dockerCertPath).build();

  if (endpoint.startsWith(UNIX_SCHEME + "://")) {
    builder.uri(endpoint);
  } else if (endpoint.startsWith(NPIPE_SCHEME + "://")) {
    builder.uri(endpoint);
  } else {
    final String stripped = endpoint.replaceAll(".*://", "");
    final HostAndPort hostAndPort = HostAndPort.fromString(stripped);
    final String hostText = hostAndPort.getHost();
    final String scheme = certs.isPresent() ? "https" : "http";

    final int port = hostAndPort.getPortOrDefault(DockerHost.defaultPort());
    final String address = isNullOrEmpty(hostText) ? DockerHost.defaultAddress() : hostText;

    builder.uri(scheme + "://" + address + ":" + port);
  }

  if (certs.isPresent()) {
    builder.dockerCertificates(certs.get());
  }

  return builder;
}
 
Example #10
Source File: RedisDockerRule.java    From pay-publicapi with MIT License 5 votes vote down vote up
private void startRedisIfNecessary() throws DockerException {
    try {
        if (container == null) {
            DockerClient docker = DefaultDockerClient.fromEnv().build();
            container = new RedisContainer(docker, host);
        }
    } catch (DockerCertificateException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: DockerContainerConfig.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public static DefaultDockerClient.Builder defaultDockerClientBuilder() {
  DefaultDockerClient.Builder defaultClient = null;

  try {
    defaultClient = DefaultDockerClient.fromEnv();
  }
  catch (DockerCertificateException e) {
    throw new RuntimeException(e);
  }

  return defaultClient;
}
 
Example #12
Source File: DockerHelper.java    From repairnator with MIT License 5 votes vote down vote up
public static DockerClient initDockerClient() {
    DockerClient docker;
    try {
        docker = DefaultDockerClient.fromEnv().build();
    } catch (DockerCertificateException e) {
        throw new RuntimeException("Error while initializing docker client.");
    }
    return docker;
}
 
Example #13
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Nonnull
private DockerClient openDockerClient() throws MojoExecutionException {
  final RegistryAuthSupplier authSupplier = createRegistryAuthSupplier();

  try {
    return DefaultDockerClient.fromEnv()
        .readTimeoutMillis(readTimeoutMillis)
        .connectTimeoutMillis(connectTimeoutMillis)
        .registryAuthSupplier(authSupplier)
        .useProxy(useProxy)
        .build();
  } catch (DockerCertificateException e) {
    throw new MojoExecutionException("Could not load Docker certificates", e);
  }
}
 
Example #14
Source File: PublishArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException, InterruptedException, DockerException, DockerCertificateException {
    initMocks(this);
    environmentVariables.clear();
    agentWorkingDir = tmpFolder.newFolder("go-agent");

    when(dockerClientFactory.docker(any())).thenReturn(dockerClient);
}
 
Example #15
Source File: AbstractDockerMojo.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected Optional<DockerCertificatesStore> dockerCertificates()
    throws DockerCertificateException {
  if (!isNullOrEmpty(dockerCertPath)) {
    return DockerCertificates.builder()
      .dockerCertPath(Paths.get(dockerCertPath)).build();
  } else {
    return Optional.absent();
  }
}
 
Example #16
Source File: DockerClientFactory.java    From docker-registry-artifact-plugin with Apache License 2.0 5 votes vote down vote up
private static DefaultDockerClient createClient(ArtifactStoreConfig artifactStoreConfig) throws DockerCertificateException, DockerException, InterruptedException {
    final RegistryAuthSupplierChain registryAuthSupplier = new RegistryAuthSupplierChain(artifactStoreConfig, new AWSTokenRequestGenerator());
    DefaultDockerClient docker = DefaultDockerClient.fromEnv().registryAuthSupplier(registryAuthSupplier).build();

    LOG.info(format("Using docker registry server `{0}`.", artifactStoreConfig.getRegistryUrl()));

    final String result = docker.ping();
    if (!result.equalsIgnoreCase("OK")) {
        throw new RuntimeException("Could not ping the docker server.");
    }
    return docker;
}
 
Example #17
Source File: AbstractDockerMojoTest.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected DefaultDockerClient.Builder getBuilder() throws DockerCertificateException {
  return builder;
}
 
Example #18
Source File: AbstractDockerMojo.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
protected DefaultDockerClient.Builder getBuilder() throws DockerCertificateException {
  return DefaultDockerClient.fromEnv()
    .readTimeoutMillis(0);
}
 
Example #19
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 #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: DockerCertificates.java    From docker-client with Apache License 2.0 4 votes vote down vote up
public DockerCertificates(final Path dockerCertPath) throws DockerCertificateException {
  this(new Builder().dockerCertPath(dockerCertPath));
}
 
Example #22
Source File: FetchArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws InterruptedException, DockerException, DockerCertificateException {
    initMocks(this);

    when(dockerClientFactory.docker(any())).thenReturn(dockerClient);
}
 
Example #23
Source File: DockerClientFactory.java    From docker-registry-artifact-plugin with Apache License 2.0 4 votes vote down vote up
public DockerClient docker(ArtifactStoreConfig artifactStoreConfig) throws InterruptedException, DockerException, DockerCertificateException {
    return createClient(artifactStoreConfig);
}
 
Example #24
Source File: HeliosSoloDeployment.java    From helios with Apache License 2.0 3 votes vote down vote up
/**
 * Return a Builder with its Docker Client configured automatically using the
 * <code>DOCKER_HOST</code> and <code>DOCKER_CERT_PATH</code> environment variables, or
 * sensible defaults if they are absent.
 *
 * @param profile A configuration profile used to populate builder options.
 * @return {@link Builder}
 */
public static Builder fromEnv(final String profile) {
  try {
    return builder(profile).dockerClient(DefaultDockerClient.fromEnv().build());
  } catch (DockerCertificateException ex) {
    throw new RuntimeException("unable to create Docker client from environment", ex);
  }
}