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

The following examples show how to use com.spotify.docker.client.exceptions.DockerException. 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 String execCommandInContainer(String containerId, String... command)
        throws DockerException, InterruptedException {
    String commandStr = Arrays.toString(command);
    log.trace("Running command {} in container {}", commandStr,
            containerId);
    String execId = dockerClient.execCreate(containerId, command,
            DockerClient.ExecCreateParam.attachStdout(),
            DockerClient.ExecCreateParam.attachStderr()).id();
    String output = null;
    try (LogStream stream = dockerClient.execStart(execId)) {
        if (stream.hasNext()) {
            output = UTF_8.decode(stream.next().content()).toString();
        }
    } catch (Exception e) {
        log.trace("Exception executing command in container", e);
    }
    log.trace("Result of command {} in container {}: {}", commandStr,
            containerId, output);
    return output;
}
 
Example #2
Source File: PublishArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddErrorToPublishArtifactResponseWhenFailedToPublishImage() throws IOException, DockerException, InterruptedException {
    final ArtifactPlan artifactPlan = new ArtifactPlan("id", "storeId", "build.json");
    final ArtifactStoreConfig artifactStoreConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final ArtifactStore artifactStore = new ArtifactStore(artifactPlan.getId(), artifactStoreConfig);
    final PublishArtifactRequest publishArtifactRequest = new PublishArtifactRequest(artifactStore, artifactPlan, agentWorkingDir.getAbsolutePath());
    final ArgumentCaptor<DockerProgressHandler> argumentCaptor = ArgumentCaptor.forClass(DockerProgressHandler.class);

    Path path = Paths.get(agentWorkingDir.getAbsolutePath(), "build.json");
    Files.write(path, "{\"image\":\"localhost:5000/alpine\",\"tag\":\"3.6\"}".getBytes());

    when(request.requestBody()).thenReturn(publishArtifactRequest.toJSON());
    doThrow(new RuntimeException("Some error")).when(dockerClient).push(eq("localhost:5000/alpine:3.6"), argumentCaptor.capture());

    final GoPluginApiResponse response = new PublishArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    assertThat(response.responseCode()).isEqualTo(500);
    assertThat(response.responseBody()).contains("Failed to publish Artifact[id=id, storeId=storeId, artifactPlanConfig={\"BuildFile\":\"build.json\"}]: Some error");
}
 
Example #3
Source File: PublishArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishArtifactUsingBuildFile() throws IOException, DockerException, InterruptedException {
    final ArtifactPlan artifactPlan = new ArtifactPlan("id", "storeId", "build.json");
    final ArtifactStoreConfig storeConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final ArtifactStore artifactStore = new ArtifactStore(artifactPlan.getId(), storeConfig);
    final PublishArtifactRequest publishArtifactRequest = new PublishArtifactRequest(artifactStore, artifactPlan, agentWorkingDir.getAbsolutePath());

    Path path = Paths.get(agentWorkingDir.getAbsolutePath(), "build.json");
    Files.write(path, "{\"image\":\"localhost:5000/alpine\",\"tag\":\"3.6\"}".getBytes());

    when(request.requestBody()).thenReturn(publishArtifactRequest.toJSON());
    when(dockerProgressHandler.getDigest()).thenReturn("foo");

    final GoPluginApiResponse response = new PublishArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    verify(dockerClient).push(eq("localhost:5000/alpine:3.6"), any(ProgressHandler.class));
    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo("{\"metadata\":{\"image\":\"localhost:5000/alpine:3.6\",\"digest\":\"foo\"}}");
}
 
Example #4
Source File: FetchArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldErrorOutWhenFailedToPull() throws DockerException, InterruptedException {
    final ArtifactStoreConfig storeConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final HashMap<String, String> artifactMetadata = new HashMap<>();
    artifactMetadata.put("image", "localhost:5000/alpine:v1");
    artifactMetadata.put("digest", "foo");
    final FetchArtifactRequest fetchArtifactRequest = new FetchArtifactRequest(storeConfig, artifactMetadata, new FetchArtifactConfig());

    when(request.requestBody()).thenReturn(new Gson().toJson(fetchArtifactRequest));
    doThrow(new RuntimeException("Some error")).when(dockerClient).pull("localhost:5000/alpine:v1", dockerProgressHandler);

    final GoPluginApiResponse response = new FetchArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    assertThat(response.responseCode()).isEqualTo(500);
    assertThat(response.responseBody()).isEqualTo("Failed pull docker image: java.lang.RuntimeException: Some error");
}
 
Example #5
Source File: DockerHelper.java    From just-ask with Apache License 2.0 6 votes vote down vote up
private static void predownloadImagesIfRequired() throws DockerException, InterruptedException {

        DockerClient client = getClient();
        LOG.warning("Commencing download of images.");
        Collection<MappingInfo> images = getInstance().getMapping().values();

        ProgressHandler handler = new LoggingBuildHandler();
        for (MappingInfo image : images) {
            List<Image> foundImages = client.listImages(DockerClient.ListImagesParam.byName(image.getTarget()));
            if (! foundImages.isEmpty()) {
                LOG.warning(String.format("Skipping download for Image [%s] because it's already available.",
                    image.getTarget()));
                continue;
            }
            client.pull(image.getTarget(), handler);
        }
    }
 
Example #6
Source File: DockerBasedService.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> scaleService(final int instanceCount) {
    try {
        Preconditions.checkArgument(instanceCount >= 0, "negative value: %s", instanceCount);

        Service.Criteria criteria = Service.Criteria.builder().serviceName(this.serviceName).build();
        TaskSpec taskSpec = Exceptions.handleInterruptedCall(() -> dockerClient.listServices(criteria).get(0).spec().taskTemplate());
        String serviceId = getServiceID();
        EndpointSpec endpointSpec = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId).spec().endpointSpec());
        Service service = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId));
        Exceptions.handleInterrupted(() -> dockerClient.updateService(serviceId, service.version().index(), ServiceSpec.builder().endpointSpec(endpointSpec).mode(ServiceMode.withReplicas(instanceCount)).taskTemplate(taskSpec).name(serviceName).networks(service.spec().networks()).build()));
        return Exceptions.handleInterruptedCall(() -> waitUntilServiceRunning());
    } catch (DockerException e) {
        throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Test failure: Unable to scale service to given instances=" + instanceCount, e);
    }
}
 
Example #7
Source File: MavenRegistryAuthSupplier.java    From dockerfile-maven with Apache License 2.0 6 votes vote down vote up
private RegistryAuth createRegistryAuth(Server server) throws DockerException {
  SettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(server);
  SettingsDecryptionResult decryptionResult = settingsDecrypter.decrypt(decryptionRequest);

  if (decryptionResult.getProblems().isEmpty()) {
    log.debug("Successfully decrypted Maven server password");
  } else {
    for (SettingsProblem problem : decryptionResult.getProblems()) {
      log.error("Settings problem for server {}: {}", server.getId(), problem);
    }

    throw new DockerException("Failed to decrypt Maven server password");
  }

  return RegistryAuth.builder()
          .username(server.getUsername())
          .password(decryptionResult.getServer().getPassword())
          .build();
}
 
Example #8
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 #9
Source File: DockerContainerClient.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void killAndRemoveStartedContainer() {
  // assure that we do not have multiple threads clearing the started container at once.
  synchronized (clearStartedContainerLock) {
    if (nonNull(startedContainer)) {
      String containerId = startedContainer.id();
      String shortId = left(containerId, SHORT_ID_LENGTH);

      startedContainer = null;

      try {
        log.info("Attempting to kill and remove container '{}' for image '{}'", shortId, image);

        dockerClient.killContainer(containerId);
        dockerClient.removeContainer(containerId);

        log.info("Successfully killed and removed container '{}' for image '{}'", shortId, image);
      }
      catch (DockerException | InterruptedException e) { // NOSONAR
        log.error("Failed to kill and/or remove container '{}'", shortId, log.isDebugEnabled() ? e : null);
      }
    }
  }
}
 
Example #10
Source File: PublishArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishArtifactUsingImageAndTag() throws IOException, DockerException, InterruptedException {
    final ArtifactPlan artifactPlan = new ArtifactPlan("id", "storeId", "alpine", Optional.of("3.6"));
    final ArtifactStoreConfig storeConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final ArtifactStore artifactStore = new ArtifactStore(artifactPlan.getId(), storeConfig);
    final PublishArtifactRequest publishArtifactRequest = new PublishArtifactRequest(artifactStore, artifactPlan, agentWorkingDir.getAbsolutePath());

    when(request.requestBody()).thenReturn(publishArtifactRequest.toJSON());
    when(dockerProgressHandler.getDigest()).thenReturn("foo");

    final GoPluginApiResponse response = new PublishArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    verify(dockerClient).push(eq("alpine:3.6"), any(ProgressHandler.class));
    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo("{\"metadata\":{\"image\":\"alpine:3.6\",\"digest\":\"foo\"}}");
}
 
Example #11
Source File: PublishArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReadEnvironmentVariablesPassedFromServer() throws IOException, DockerException, InterruptedException {
    final ArtifactPlan artifactPlan = new ArtifactPlan("id", "storeId", "${IMAGE_NAME}", Optional.of("3.6"));
    final ArtifactStoreConfig storeConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final ArtifactStore artifactStore = new ArtifactStore(artifactPlan.getId(), storeConfig);
    final PublishArtifactRequest publishArtifactRequest = new PublishArtifactRequest(artifactStore, artifactPlan, agentWorkingDir.getAbsolutePath(), Collections.singletonMap("IMAGE_NAME", "alpine"));

    when(request.requestBody()).thenReturn(publishArtifactRequest.toJSON());
    when(dockerProgressHandler.getDigest()).thenReturn("foo");

    final GoPluginApiResponse response = new PublishArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    verify(dockerClient).push(eq("alpine:3.6"), any(ProgressHandler.class));
    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo("{\"metadata\":{\"image\":\"alpine:3.6\",\"digest\":\"foo\"}}");
}
 
Example #12
Source File: Mapper_SQLServer_Test.java    From rmlmapper-java with MIT License 6 votes vote down vote up
private static void closeDocker(DockerDBInfo dockerDBInfo) {
    if (dockerDBInfo != null && dockerDBInfo.docker != null) {
        try {
            // Kill container
            dockerDBInfo.docker.killContainer(dockerDBInfo.containerID);

            // Remove container
            dockerDBInfo.docker.removeContainer(dockerDBInfo.containerID);

            // Close the docker client
            dockerDBInfo.docker.close();
        } catch (DockerException | InterruptedException ex) {
            logger.warn("Could not kill the database container with connection string: " + dockerDBInfo.connectionString + "!", ex);
        }
    }
}
 
Example #13
Source File: PublishArtifactExecutorTest.java    From docker-registry-artifact-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReadEnvironmentVariablesFromTheSystem() throws IOException, DockerException, InterruptedException {
    environmentVariables.set("IMAGE_NAME", "alpine");
    final ArtifactPlan artifactPlan = new ArtifactPlan("id", "storeId", "${IMAGE_NAME}", Optional.of("3.6"));
    final ArtifactStoreConfig storeConfig = new ArtifactStoreConfig("localhost:5000", "other", "admin", "admin123");
    final ArtifactStore artifactStore = new ArtifactStore(artifactPlan.getId(), storeConfig);
    final PublishArtifactRequest publishArtifactRequest = new PublishArtifactRequest(artifactStore, artifactPlan, agentWorkingDir.getAbsolutePath());

    when(request.requestBody()).thenReturn(publishArtifactRequest.toJSON());
    when(dockerProgressHandler.getDigest()).thenReturn("foo");

    final GoPluginApiResponse response = new PublishArtifactExecutor(request, consoleLogger, dockerProgressHandler, dockerClientFactory).execute();

    verify(dockerClient).push(eq("alpine:3.6"), any(ProgressHandler.class));
    assertThat(response.responseCode()).isEqualTo(200);
    assertThat(response.responseBody()).isEqualTo("{\"metadata\":{\"image\":\"alpine:3.6\",\"digest\":\"foo\"}}");
}
 
Example #14
Source File: BaseTest.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 6 votes vote down vote up
private static void removeVolume() throws Exception {
    if (dockerApiVersionAtLeast(docker, "1.26")) {
        if (docker.listVolumes().volumes() != null) {
            docker.listVolumes().volumes().forEach(volume -> {
                if (volume.labels() != null && volume.labels().containsKey("cd.go.contrib.elasticagents.dockerswarm.elasticagent.DockerPlugin")) {
                    try {
                        docker.removeVolume(volume.name());
                    } catch (DockerException | InterruptedException e) {
                    }
                }
            });
        }
    } else {
        LOG.warn(format("Detected docker version and api version is {0} and {1} respectively. Docker with api version 1.26 or above is required to use volume mounts, secrets and host file entries. Please refer https://docs.docker.com/engine/api/v1.32/#section/Versioning for more information about docker release.", docker.version().version(), docker.version().apiVersion()));
    }
}
 
Example #15
Source File: DockerService.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
public void pullImage(String imageId)
        throws DockerException, InterruptedException {
    if (!preferences.checkKeyInPreferences(imageId)
            || !getConfig().isUsePreferences() || !localDaemon) {
        log.info("Pulling Docker image {}", imageId);
        dockerClient.pull(imageId, new ProgressHandler() {
            @Override
            public void progress(ProgressMessage message)
                    throws DockerException {
                log.trace("Pulling Docker image {} ... {}", imageId,
                        message);
            }
        });
        log.trace("Docker image {} downloaded", imageId);
        if (getConfig().isUsePreferences() && localDaemon) {
            preferences.putValueInPreferencesIfEmpty(imageId, "pulled");
        }
    }
}
 
Example #16
Source File: RunnablePipelineContainer.java    From repairnator with MIT License 6 votes vote down vote up
/**
 * In case of timeout, we kill the container.
 * @param remove if true, it will remove both the container and the volumes
 */
public void killDockerContainer(DockerClient docker, boolean remove) {
    if (this.containerId == null) {
        LOGGER.error("Error while trying to kill docker container: the container id is not available. Maybe the container is not started yet.");
    } else {
        LOGGER.info("Killing the docker container with id "+containerId+". Forced killing date: "+this.limitDateBeforeKilling);
        try {
            docker.killContainer(containerId);
            if (remove) {
                docker.removeContainer(containerId);
                this.removeVolumes(docker);
            }
            this.poolManager.removeSubmittedRunnablePipelineContainer(this);
            serialize("INTERRUPTED");
        } catch (DockerException|InterruptedException e) {
            LOGGER.error("Error while killing docker container "+containerId, e);
        }
    }

}
 
Example #17
Source File: DockerDriverHandler.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
public String startDockerBrowser(BrowserInstance browserInstance,
        String version) throws DockerException, InterruptedException {

    String browserImage;
    BrowserType browserType = browserInstance.getBrowserType();
    if (version == null || version.isEmpty()
            || version.equalsIgnoreCase(LATEST)) {
        log.info("Using {} version {} (latest)", browserType,
                selenoidConfig.getDefaultBrowser(browserType));
        browserImage = selenoidConfig.getLatestImage(browserInstance);
    } else {
        log.info("Using {} version {}", browserType, version);
        browserImage = selenoidConfig.getImageFromVersion(browserType,
                version);
    }
    if (browserType != EDGE && browserType != IEXPLORER) {
        dockerService.pullImage(browserImage);
    }

    DockerContainer selenoidContainer = startSelenoidContainer();
    return selenoidContainer.getContainerUrl();
}
 
Example #18
Source File: DockerInterpreterProcess.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private void execInContainer(String containerId, String execCommand, boolean logout)
    throws DockerException, InterruptedException {

  LOGGER.info("exec container commmand: " + execCommand);

  final String[] command = {"sh", "-c", execCommand};
  final ExecCreation execCreation = docker.execCreate(
      containerId, command, DockerClient.ExecCreateParam.attachStdout(),
      DockerClient.ExecCreateParam.attachStderr());

  LogStream logStream = docker.execStart(execCreation.id());
  while (logStream.hasNext() && logout) {
    final String log = UTF_8.decode(logStream.next().content()).toString();
    LOGGER.info(log);
  }
}
 
Example #19
Source File: DockerDriverHandler.java    From selenium-jupiter with Apache License 2.0 6 votes vote down vote up
private boolean setHubUrl(BrowserInstance browserInstance,
        String versionFromLabel) throws MalformedURLException,
        DockerException, InterruptedException {
    String seleniumServerUrl = getConfig().getSeleniumServerUrl();
    boolean seleniumServerUrlAvailable = seleniumServerUrl != null
            && !seleniumServerUrl.isEmpty();
    hubUrl = new URL(seleniumServerUrlAvailable ? seleniumServerUrl
            : startDockerBrowser(browserInstance, versionFromLabel));
    if (remoteUrl != null) {
        try {
            String remoteHost = remoteUrl.getHost();
            log.trace("Converting {} to use {}", hubUrl, remoteHost);
            URI uri = new URI(hubUrl.toString());
            hubUrl = new URI(uri.getScheme(), null, remoteHost,
                    uri.getPort(), uri.getPath(), uri.getQuery(),
                    uri.getFragment()).toURL();
        } catch (URISyntaxException e) {
            log.warn("Exception converting URL {}", remoteUrl, e);
        }
    }
    return seleniumServerUrlAvailable;
}
 
Example #20
Source File: DockerBasedService.java    From pravega with Apache License 2.0 6 votes vote down vote up
private String getServiceID() {
    Service.Criteria criteria = Service.Criteria.builder().serviceName(this.serviceName).build();
    String serviceId = null;
    try {
        List<Service> serviceList = Exceptions.handleInterruptedCall(
                () -> dockerClient.listServices(criteria));
        log.info("Service list size {}", serviceList.size());
        if (!serviceList.isEmpty()) {
            serviceId = serviceList.get(0).id();
        }

    } catch (DockerException e) {
        throw new TestFrameworkException(TestFrameworkException.Type.RequestFailed, "Unable to get service id", e);
    }
    return serviceId;
}
 
Example #21
Source File: DockerHelper.java    From repairnator with MIT License 6 votes vote down vote up
public static String findDockerImage(String imageName, DockerClient docker) {
    if (docker == null) {
        throw new RuntimeException("Docker client has not been initialized. No docker image can be found.");
    }

    try {
        List<Image> allImages = docker.listImages(DockerClient.ListImagesParam.allImages());

        String imageId = null;
        for (Image image : allImages) {
            if (image.repoTags() != null && image.repoTags().contains(imageName)) {
                imageId = image.id();
                break;
            }
        }

        if (imageId == null) {
            throw new RuntimeException("There was a problem when looking for the docker image with argument \""+imageName+"\": no image has been found.");
        }
        return imageId;
    } catch (InterruptedException|DockerException e) {
        throw new RuntimeException("Error while looking for the docker image",e);
    }
}
 
Example #22
Source File: Mapper_Postgres_Test.java    From rmlmapper-java with MIT License 6 votes vote down vote up
private static void closeDocker(DockerDBInfo dockerDBInfo) {
    if (dockerDBInfo != null && dockerDBInfo.docker != null) {
        try {
            // Kill container
            dockerDBInfo.docker.killContainer(dockerDBInfo.containerID);

            // Remove container
            dockerDBInfo.docker.removeContainer(dockerDBInfo.containerID);

            // Close the docker client
            dockerDBInfo.docker.close();
        } catch (DockerException | InterruptedException ex) {
            logger.warn("Could not kill the database container with connection string: " + dockerDBInfo.connectionString + "!", ex);
        }
    }
}
 
Example #23
Source File: PushMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Override
protected void execute(DockerClient dockerClient)
    throws MojoExecutionException, MojoFailureException {
  final Log log = getLog();

  if (skipPush) {
    log.info("Skipping execution because 'dockerfile.push.skip' is set");
    return;
  }

  if (repository == null) {
    repository = readMetadata(Metadata.REPOSITORY);
  }

  // Do this hoop jumping so that the override order is correct
  if (tag == null) {
    tag = readMetadata(Metadata.TAG);
  }
  if (tag == null) {
    tag = "latest";
  }

  if (repository == null) {
    throw new MojoExecutionException(
        "Can't push image; image repository not known "
        + "(specify dockerfile.repository parameter, or run the tag goal before)");
  }

  try {
    dockerClient
        .push(formatImageName(repository, tag), LoggingProgressHandler.forLog(log, verbose));
  } catch (DockerException | InterruptedException e) {
    throw new MojoExecutionException("Could not push image", e);
  }
}
 
Example #24
Source File: DockerServiceElasticAgent.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
public static DockerServiceElasticAgent fromService(Service service, DockerClient client) throws DockerException, InterruptedException {
    DockerServiceElasticAgent agent = new DockerServiceElasticAgent();

    agent.id = service.id();
    agent.name = service.spec().name();
    agent.createdAt = service.createdAt();
    agent.jobIdentifier = JobIdentifier.fromJson(service.spec().labels().get(JOB_IDENTIFIER_LABEL_KEY));

    LogStream logStream = client.serviceLogs(service.id(), DockerClient.LogsParam.stdout(), DockerClient.LogsParam.stderr());
    agent.logs = logStream.readFully();
    logStream.close();

    TaskSpec taskSpec = service.spec().taskTemplate();

    agent.image = taskSpec.containerSpec().image();
    agent.hostname = taskSpec.containerSpec().hostname();
    agent.limits = resourceToString(taskSpec.resources().limits());
    agent.reservations = resourceToString(taskSpec.resources().reservations());
    agent.command = listToString(taskSpec.containerSpec().command());
    agent.args = listToString(taskSpec.containerSpec().args());
    agent.placementConstraints = listToString(taskSpec.placement().constraints());
    agent.environments = toMap(taskSpec);
    agent.hosts = listToString(taskSpec.containerSpec().hosts());

    final List<Task> tasks = client.listTasks(Task.Criteria.builder().serviceName(service.id()).build());
    if (!tasks.isEmpty()) {
        for (Task task : tasks) {
            agent.tasksStatus.add(new TaskStatus(task));
        }
    }

    return agent;
}
 
Example #25
Source File: MavenRegistryAuthSupplier.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Override
public RegistryAuth authFor(final String imageName) throws DockerException {
  final ImageRef ref = new ImageRef(imageName);
  Server server = settings.getServer(ref.getRegistryName());
  if (server != null) {
    return createRegistryAuth(server);
  }
  log.warn("Did not find maven server configuration for docker server " + ref.getRegistryName());
  return null;
}
 
Example #26
Source File: MavenRegistryAuthSupplier.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Override
public RegistryConfigs authForBuild() throws DockerException {
  final Map<String, RegistryAuth> allConfigs = new HashMap<>();
  for (Server server : settings.getServers()) {
    allConfigs.put(server.getId(), createRegistryAuth(server));
  }
  return RegistryConfigs.create(allConfigs);
}
 
Example #27
Source File: TagMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Override
protected void execute(DockerClient dockerClient)
    throws MojoExecutionException, MojoFailureException {
  final Log log = getLog();

  if (skipTag) {
    log.info("Skipping execution because 'dockerfile.tag.skip' is set");
    return;
  }

  final String imageId = readMetadata(Metadata.IMAGE_ID);
  final String imageName = formatImageName(repository, tag);

  final String message =
      MessageFormat.format("Tagging image {0} as {1}", imageId, imageName);
  log.info(message);

  try {
    dockerClient.tag(imageId, imageName, force);
  } catch (DockerException | InterruptedException e) {
    throw new MojoExecutionException("Could not tag Docker image", e);
  }

  writeImageInfo(repository, tag);

  writeMetadata(log);
}
 
Example #28
Source File: CheckBranchRunner.java    From repairnator with MIT License 5 votes vote down vote up
private void killDockerContainer(DockerClient docker, String containerId) {
    LOGGER.info("Killing docker container: "+containerId);
    try {
        docker.killContainer(containerId);
        docker.removeContainer(containerId);
    } catch (DockerException|InterruptedException e) {
        LOGGER.error("Error while killing docker container "+containerId, e);
    }

}
 
Example #29
Source File: SwarmCluster.java    From docker-swarm-elastic-agent-plugin with Apache License 2.0 5 votes vote down vote up
private Map<String, Service> serviceIdToServiceMap(DockerClient dockerClient) throws DockerException, InterruptedException {
    final List<Service> services = dockerClient.listServices();
    if (services == null || services.isEmpty()) {
        return Collections.emptyMap();
    }

    final HashMap<String, Service> serviceIdToService = new HashMap<>();
    for (Service service : services) {
        serviceIdToService.put(service.id(), service);
    }
    return serviceIdToService;
}
 
Example #30
Source File: BuildMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
private static boolean imageExistLocally(DockerClient dockerClient, String image)
        throws DockerException, InterruptedException {
  try {
    dockerClient.inspectImage(image);
    return true;
  } catch (ImageNotFoundException e) {
    return false;
  }
}