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

The following examples show how to use com.spotify.docker.client.DockerClient#removeImage() . 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: RemoveImageMojo.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
protected void execute(final DockerClient docker)
    throws MojoExecutionException, DockerException, InterruptedException {
  final String[] imageNameParts = parseImageName(imageName);
  if (imageTags == null) {
    imageTags = new ArrayList<>(1);
    imageTags.add(imageNameParts[1]);
  } else if (removeAllTags) {
    getLog().info("Removal of all tags requested, searching for tags");
    // removal of all tags requested, loop over all images to find tags
    for (final Image currImage : docker.listImages()) {
      getLog().debug("Found image: " + currImage.toString());
      String[] parsedRepoTag;
      if (currImage.repoTags() != null) {
        for (final String repoTag : currImage.repoTags()) {
          parsedRepoTag = parseImageName(repoTag);
          // if repo name matches imageName then save the tag for deletion
          if (Objects.equal(parsedRepoTag[0], imageNameParts[0])) {
            imageTags.add(parsedRepoTag[1]);
            getLog().info("Adding tag for removal: " + parsedRepoTag[1]);
          }
        }
      }
    }
  }
  imageTags.add(imageNameParts[1]);

  final Set<String> uniqueImageTags = new HashSet<>(imageTags);
  for (final String imageTag : uniqueImageTags) {
    final String currImageName =
        imageNameParts[0] + ((isNullOrEmpty(imageTag)) ? "" : (":" + imageTag));
    getLog().info("Removing -f " + currImageName);

    try {
      // force the image to be removed but don't remove untagged parents
      for (final RemovedImage removedImage : docker.removeImage(currImageName, true, false)) {
        getLog().info("Removed: " + removedImage.imageId());
      }
    } catch (ImageNotFoundException | NotFoundException e) {
      // ignoring 404 errors only
      getLog().warn("Image " + imageName + " doesn't exist and cannot be deleted - ignoring");
    }
  }
}