Java Code Examples for com.spotify.docker.client.DockerClient#close()

The following examples show how to use com.spotify.docker.client.DockerClient#close() . 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: PublishArtifactExecutor.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse execute() {
    ArtifactPlan artifactPlan = publishArtifactRequest.getArtifactPlan();
    final ArtifactStoreConfig artifactStoreConfig = publishArtifactRequest.getArtifactStore().getArtifactStoreConfig();
    try {
        final DockerClient docker = clientFactory.docker(artifactStoreConfig);
        Map<String, String> environmentVariables = publishArtifactRequest.getEnvironmentVariables() == null ? new HashMap<>() : publishArtifactRequest.getEnvironmentVariables();
        environmentVariables.putAll(System.getenv());
        final DockerImage image = artifactPlan.getArtifactPlanConfig().imageToPush(publishArtifactRequest.getAgentWorkingDir(), environmentVariables);

        LOG.info(format("Pushing docker image `%s` to docker registry `%s`.", image, artifactStoreConfig.getRegistryUrl()));
        consoleLogger.info(format("Pushing docker image `%s` to docker registry `%s`.", image, artifactStoreConfig.getRegistryUrl()));

        docker.push(image.toString(), progressHandler);
        docker.close();

        publishArtifactResponse.addMetadata("image", image.toString());
        publishArtifactResponse.addMetadata("digest", progressHandler.getDigest());
        consoleLogger.info(format("Image `%s` successfully pushed to docker registry `%s`.", image, artifactStoreConfig.getRegistryUrl()));
        return DefaultGoPluginApiResponse.success(publishArtifactResponse.toJSON());
    } catch (Exception e) {
        consoleLogger.error(String.format("Failed to publish %s: %s", artifactPlan, e));
        LOG.error(String.format("Failed to publish %s: %s", artifactPlan, e.getMessage()), e);
        return DefaultGoPluginApiResponse.error(String.format("Failed to publish %s: %s", artifactPlan, e.getMessage()));
    }
}
 
Example 2
Source File: FetchArtifactExecutor.java    From docker-registry-artifact-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public GoPluginApiResponse execute() {
    try {
        final Map<String, String> artifactMap = fetchArtifactRequest.getMetadata();
        validateMetadata(artifactMap);
        FetchArtifactConfig fetchArtifactConfig = fetchArtifactRequest.getFetchArtifactConfig();

        final String artifactPrefix = fetchArtifactConfig.getEnvironmentVariablePrefix();
        final boolean skipImagePulling = fetchArtifactConfig.getSkipImagePulling();
        final String imageToPull = artifactMap.get("image");

        if (skipImagePulling) {
            consoleLogger.info(String.format("Not pulling docker image `%s` due to `Skip Image Pulling` configuration being set.", imageToPull));
            LOG.info(String.format("Not pulling docker image `%s` due to `Skip Image Pulling` configuration being set.", imageToPull));
        } else {
            consoleLogger.info(String.format("Pulling docker image `%s` from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));
            LOG.info(String.format("Pulling docker image `%s` from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));

            DockerClient docker = clientFactory.docker(fetchArtifactRequest.getArtifactStoreConfig());
            docker.pull(imageToPull, dockerProgressHandler);
            docker.close();

            consoleLogger.info(String.format("Image `%s` successfully pulled from docker registry `%s`.", imageToPull, fetchArtifactRequest.getArtifactStoreConfig().getRegistryUrl()));

            if (!dockerProgressHandler.getDigest().equals(artifactMap.get("digest"))) {
                throw new RuntimeException(format("Expecting pulled image digest to be [%s] but it is [%s].", artifactMap.get("digest"), dockerProgressHandler.getDigest()));
            }
        }

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", StringUtils.isEmpty(artifactPrefix) ? "ARTIFACT_IMAGE" : String.format("%s_ARTIFACT_IMAGE", artifactPrefix));
        jsonObject.addProperty("value", imageToPull);

        JsonArray jsonElements = new JsonArray();
        jsonElements.add(jsonObject);

        return DefaultGoPluginApiResponse.success(jsonElements.toString());
    } catch (Exception e) {
        final String message = format("Failed pull docker image: %s", e);
        consoleLogger.error(message);
        LOG.error(message);
        return DefaultGoPluginApiResponse.error(message);
    }
}
 
Example 3
Source File: DockerHelper.java    From paas with Apache License 2.0 4 votes vote down vote up
public static void execute(String ip, String port, DockerAction dockerAction) throws Exception {
    DockerClient docker = DefaultDockerClient.builder().uri(protocol.concat(ip).concat(":" + port)).apiVersion(apiVersion).build();
    dockerAction.action(docker);
    docker.close();
}
 
Example 4
Source File: DockerHelper.java    From paas with Apache License 2.0 4 votes vote down vote up
public static <T> T query(String ip, String port, DockerQuery<T> dockerQuery) throws Exception {
    DockerClient docker = DefaultDockerClient.builder().uri(protocol.concat(ip).concat(":" + port)).apiVersion(apiVersion).build();
    T result = dockerQuery.action(docker);
    docker.close();
    return result;
}
 
Example 5
Source File: DockerHelper.java    From java-docker-exec with MIT License 4 votes vote down vote up
public static void execute(String ip,DockerAction dockerAction)throws Exception{
    DockerClient docker = DefaultDockerClient.builder().uri("http://".concat(ip).concat(":2375")).apiVersion("v1.30").build();
    dockerAction.action(docker);
    docker.close();
}
 
Example 6
Source File: DockerHelper.java    From java-docker-exec with MIT License 4 votes vote down vote up
public static <T> T query(String ip,DockerQuery<T> dockerQuery)throws Exception{
    DockerClient docker = DefaultDockerClient.builder().uri("http://".concat(ip).concat(":2375")).apiVersion("v1.30").build();
    T result=dockerQuery.action(docker);
    docker.close();
    return result;
}
 
Example 7
Source File: DockerSample.java    From just-ask with Apache License 2.0 4 votes vote down vote up
private static void foo() throws Exception {
    boolean debug = Boolean.parseBoolean(System.getProperty("debug", "false"));
    String dockerHost = String.format("http://%s:%d", CENTOS, 2375);
    DockerClient docker = null;
    try {
        docker = DefaultDockerClient.builder()
            .uri(dockerHost).build();
        Info info = docker.info();
        System.err.println("Information : " + info);
        if (debug) {
            docker.pull(SELENIUM_STANDALONE_CHROME, new LoggingBuildHandler());
        } else {
            docker.pull(SELENIUM_STANDALONE_CHROME);
        }
        final ImageInfo imageInfo = docker.inspectImage(SELENIUM_STANDALONE_CHROME);
        System.err.println("Information : " + imageInfo);
        // Bind container ports to host ports
        //            final String[] ports = {Integer.toString(PortProber.findFreePort())};
        final String[] ports = {"4444"};
        final Map<String, List<PortBinding>> portBindings = new HashMap<>();
        for (String port : ports) {
            List<PortBinding> hostPorts = new ArrayList<>();
            hostPorts.add(PortBinding.of("0.0.0.0", PortProber.findFreePort()));
            portBindings.put(port, hostPorts);
        }
        //            // Bind container port 443 to an automatically allocated available host port.
        //            List<PortBinding> randomPort = new ArrayList<>();
        //            randomPort.add(PortBinding.randomPort("0.0.0.0"));
        //            portBindings.put("443", randomPort);

        System.err.println("Printing the port mappings : " + portBindings);

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

        final ContainerConfig containerConfig = ContainerConfig.builder()
            .hostConfig(hostConfig)
            .image(SELENIUM_STANDALONE_CHROME).exposedPorts(ports)
            .build();

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

        // Inspect container
        final ContainerInfo containerInfo = docker.inspectContainer(id);
        System.err.println("Container Information " + containerInfo);
        String msg = "Checking to see if the container with id [" + id + "] and name [" +
            containerInfo.name() + "]...";
        System.err.println(msg);
        if (! containerInfo.state().running()) {
            // Start container
            docker.startContainer(id);
            System.err.println(containerInfo.name() + " is now running.");
        } else {
            System.err.println(containerInfo.name() + " was already running.");
        }

        System.err.println("Lets wait here !!!");
    } finally {
        if (docker != null) {
            docker.close();
        }
    }
}
 
Example 8
Source File: HealthCheckTest.java    From helios with Apache License 2.0 4 votes vote down vote up
@Test
public void testExec() throws Exception {
  // CircleCI uses lxc which doesn't support exec - https://circleci.com/docs/docker/#docker-exec
  assumeFalse(isCircleCi());

  final DockerClient dockerClient = getNewDockerClient();
  assumeThat(dockerClient.version(), is(execCompatibleDockerVersion()));

  startDefaultMaster();

  final HeliosClient client = defaultClient();

  startDefaultAgent(testHost(), "--service-registry=" + registryAddress);
  awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS);

  // check if "file" exists in the root directory as a healthcheck
  final HealthCheck healthCheck = ExecHealthCheck.of("test", "-e", "file");

  // start a container that listens on the service port
  final String portName = "service";
  final String serviceName = "foo_service";
  final String serviceProtocol = "foo_proto";
  final Job job = Job.newBuilder()
      .setName(testJobName)
      .setVersion(testJobVersion)
      .setImage(BUSYBOX)
      .setCommand(asList("sh", "-c", "nc -l -p 4711"))
      .addPort(portName, PortMapping.of(4711))
      .addRegistration(ServiceEndpoint.of(serviceName, serviceProtocol),
          ServicePorts.of(portName))
      .setHealthCheck(healthCheck)
      .build();

  final JobId jobId = createJob(job);
  deployJob(jobId, testHost());
  final TaskStatus jobState = awaitTaskState(jobId, testHost(), HEALTHCHECKING);

  // wait a few seconds to see if the service gets registered
  Thread.sleep(3000);
  // shouldn't be registered, since we haven't created the file yet
  verify(registrar, never()).register(any(ServiceRegistration.class));

  // create the file in the container to make the healthcheck succeed
  final String[] makeFileCmd = new String[]{ "touch", "file" };
  final ExecCreation execCreation = dockerClient.execCreate(
      jobState.getContainerId(), makeFileCmd);
  final String execId = execCreation.id();
  dockerClient.execStart(execId);

  awaitTaskState(jobId, testHost(), RUNNING);
  dockerClient.close();

  verify(registrar, timeout((int) SECONDS.toMillis(LONG_WAIT_SECONDS)))
      .register(registrationCaptor.capture());
  final ServiceRegistration serviceRegistration = registrationCaptor.getValue();

  assertEquals(1, serviceRegistration.getEndpoints().size());
  final Endpoint registeredEndpoint = serviceRegistration.getEndpoints().get(0);

  assertEquals("wrong service", serviceName, registeredEndpoint.getName());
  assertEquals("wrong protocol", serviceProtocol, registeredEndpoint.getProtocol());
}