com.github.dockerjava.api.model.Image Java Examples

The following examples show how to use com.github.dockerjava.api.model.Image. 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: DockerUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * list images
 *
 * @param imageName 镜像名称
 * @return
 */
public static List<String> listImages(String imageName) {
    logger.info("list images:" + imageName);
  List<String> imageNameList = new ArrayList<String>();
  DockerClient dockerClient = getDockerClient();
  List<Image> imageList = dockerClient.listImagesCmd().exec();
  for (Image image : imageList) {
    if (image.getRepoTags() == null) {
      continue;
    }
    String imageTag = image.getRepoTags()[0];
    if (StringUtils.isEmpty(imageName) || StringUtils.contains(imageTag, imageName)) {
      imageNameList.add(imageTag);
    }
  }
  closeDockerClient(dockerClient);
  return imageNameList;
}
 
Example #2
Source File: DockerUtils.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Finds an image by tag.
 * @param imageTag the image tag (not null)
 * @param images a non-null list of images
 * @return an image, or null if none was found
 */
public static Image findImageByTag( String imageTag, List<Image> images ) {

	Image result = null;
	for( Image img : images ) {
		String[] tags = img.getRepoTags();
		if( tags == null )
			continue;

		for( String s : tags ) {
			if( s.contains( imageTag )) {
				result = img;
				break;
			}
		}
	}

	return result;
}
 
Example #3
Source File: DockerUtils.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Finds an image by ID or by tag.
 * @param name an image ID or a tag name (can be null)
 * @param dockerClient a Docker client (not null)
 * @return an image, or null if none matched
 */
public static Image findImageByIdOrByTag( String name, DockerClient dockerClient ) {

	Image image = null;
	if( ! Utils.isEmptyOrWhitespaces( name )) {
		Logger logger = Logger.getLogger( DockerUtils.class.getName());

		List<Image> images = dockerClient.listImagesCmd().exec();
		if(( image = DockerUtils.findImageById( name, images )) != null )
			logger.fine( "Found a Docker image with ID " + name );
		else if(( image = DockerUtils.findImageByTag( name, images )) != null )
			logger.fine( "Found a Docker image with tag " + name );
	}

	return image;
}
 
Example #4
Source File: DockerMachineConfigurator.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean configure() throws TargetException {

	// Creating a container is almost immediate.
	// And building an image with the REST API is blocking the thread until the creation is complete.
	// So, this is not asynchronous configuration.
	// Said differently, this method will be invoked only once!

	Map<String,String> targetProperties = this.parameters.getTargetProperties();
	this.dockerClient = DockerUtils.createDockerClient( targetProperties );

	String rbcfVersion = DockerUtils.findDefaultImageVersion( ManifestUtils.findBundleVersion());
	String imageId = Utils.getValue( targetProperties, IMAGE_ID, DEFAULT_IMAGE + ":" + rbcfVersion );
	this.logger.fine( "Used image: " + imageId );

	Image img = DockerUtils.findImageByIdOrByTag( imageId, this.dockerClient );
	if( img == null )
		createImage( imageId );

	createContainer( imageId );
	return true;
}
 
Example #5
Source File: DockerHandlerWithContainerTest.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void testDockerUtils_onLimits() {

	DockerUtils.deleteImageIfItExists( null, this.docker );
	Assert.assertTrue( "No exception is thrown trying to delete a null image ID.", true );

	DockerUtils.deleteImageIfItExists( "bla 11 4 2 bla", this.docker );
	Assert.assertTrue( "No exception is thrown trying to delete something that does not exist.", true );

	Container container = DockerUtils.findContainerByIdOrByName( "bla 11 4 2 bla", this.docker );
	Assert.assertNull( container );

	Image image = DockerUtils.findImageByIdOrByTag( null, this.docker );
	Assert.assertNull( image );

	image = DockerUtils.findImageByIdOrByTag( "invalid", this.docker );
	Assert.assertNull( image );
}
 
Example #6
Source File: LoadImageCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void loadImageFromTar() throws Exception {
    try (InputStream uploadStream = Files.newInputStream(TestResources.getApiImagesLoadTestTarball())) {
        dockerRule.getClient().loadImageCmd(uploadStream).exec();
    }

    //swarm needs some time to reflect new images
    synchronized (this) {
        wait(5000);
    }

    final Image image = findImageWithId(expectedImageId, dockerRule.getClient().listImagesCmd().exec());

    assertThat("Can't find expected image after loading from a tar archive!", image, notNullValue());
    assertThat("Image after loading from a tar archive has wrong tags!",
            asList(image.getRepoTags()), equalTo(singletonList("docker-java/load:1.0")));
}
 
Example #7
Source File: AbstractContainer.java    From minimesos with Apache License 2.0 6 votes vote down vote up
protected Boolean imageExists(String imageName, String registryTag) {
    List<Image> images = DockerClientFactory.build().listImagesCmd().exec();
    if (images.isEmpty()) {
        throw new MinimesosException("Failed to find image '" +  imageName + ":" + registryTag + ". No images found");
    }
    for (Image image : images) {
        if (image.getRepoTags() == null) {
            continue;
        }
        for (String repoTag : image.getRepoTags()) {
            if (repoTag.equals(imageName + ":" + registryTag)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #8
Source File: ListImagesCmdExec.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
protected List<Image> execute(ListImagesCmd command) {
    WebTarget webTarget = getBaseResource().path("/images/json");

    webTarget = booleanQueryParam(webTarget, "all", command.hasShowAllEnabled());

    if (command.getFilters() != null && !command.getFilters().isEmpty()) {
        webTarget = webTarget.queryParam("filters", FiltersEncoder.jsonEncode(command.getFilters()));
    }

   if (command.getImageNameFilter() != null) {
        webTarget = webTarget.queryParam("filter", command.getImageNameFilter());
   }

    LOGGER.trace("GET: {}", webTarget);

    List<Image> images = webTarget.request().accept(MediaType.APPLICATION_JSON)
            .get(new TypeReference<List<Image>>() {
            });

    LOGGER.trace("Response: {}", images);

    return images;
}
 
Example #9
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenListingImages_thenReturnNonEmptyList() {

    // when
    List<Image> images = dockerClient.listImagesCmd().exec();

    // then
    assertThat(images.size(), is(not(0)));
}
 
Example #10
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenListingImagesWithIntermediateImages_thenReturnNonEmptyList() {

    // when
    List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();

    // then
    assertThat(images.size(), is(not(0)));
}
 
Example #11
Source File: ListImagesCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private boolean isImageInFilteredList(List<Image> images, String expectedImageId) {
    for (Image image : images) {
        if (expectedImageId.equals(image.getId())) {
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: ListImagesCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void listImagesWithDanglingFilter() throws DockerException {
    String imageId = createDanglingImage();
    List<Image> images = dockerRule.getClient().listImagesCmd().withDanglingFilter(true).withShowAll(true)
            .exec();
    assertThat(images, notNullValue());
    LOG.info("Images List: {}", images);
    assertThat(images.size(), is(greaterThan(0)));
    Boolean imageInFilteredList = isImageInFilteredList(images, imageId);
    assertTrue(imageInFilteredList);
}
 
Example #13
Source File: LoadImageCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
private Image findImageWithId(final String id, final List<Image> images) {
    for (Image image : images) {
        if (id.equals(image.getId())) {
            return image;
        }
    }
    return null;
}
 
Example #14
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenListingDanglingImages_thenReturnNonNullList() {

    // when
    List<Image> images = dockerClient.listImagesCmd().withDanglingFilter(true).exec();

    // then
    assertThat(images, is(not(null)));
}
 
Example #15
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenListOfImages_whenInspectImage_thenMustReturnObject() {

    // given
    List<Image> images = dockerClient.listImagesCmd().exec();
    Image image = images.get(0);

    // when
    InspectImageResponse imageResponse = dockerClient.inspectImageCmd(image.getId()).exec();

    // then
    MatcherAssert.assertThat(imageResponse.getId(), Is.is(image.getId()));
}
 
Example #16
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenListOfImages_whenTagImage_thenListMustIncrement() {

    // given
    List<Image> images = dockerClient.listImagesCmd().exec();
    Image image = images.get(0);

    // when
    dockerClient.tagImageCmd(image.getId(), "baeldung/alpine", "3.6.v2").exec();

    // then
    List<Image> imagesNow = dockerClient.listImagesCmd().exec();
    assertThat(imagesNow.size(), is(greaterThan(images.size())));
}
 
Example #17
Source File: DockerHandlerWithContainerTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void prepareDockerEnv() throws Exception {

	final Logger logger = Logger.getLogger( DockerHandlerWithContainerTest.class.getName());
	try {
		// Is Docker installed?
		DockerTestUtils.checkDockerIsInstalled();

		// Prepare the environment
		DockerClient docker = buildDockerClient();
		File baseDir = new File( Thread.currentThread().getContextClassLoader().getResource( "./image/alpine" ).getFile());
		Assert.assertTrue( baseDir.exists());

		String builtImageId = docker.buildImageCmd(baseDir)
				.withNoCache( true ).withTags( new HashSet<>( Arrays.asList( TAG )))
				.exec( new RoboconfBuildImageResultCallback())
				.awaitImageId();

		logger.finest( "Built image ID: " + builtImageId );

		List<Image> images = docker.listImagesCmd().exec();
		images = images == null ? new ArrayList<Image>( 0 ) : images;
		Image img = DockerUtils.findImageByTag( TAG, images );

		Assert.assertNotNull( img );
		dockerImageId = img.getId();
		docker.close();

	} catch( IOException | InterruptedException e ) {
		logger.warning( "Tests are skipped because Docker is not installed or misconfigured." );
		Utils.logException( logger, e );

		dockerIsInstalled = false;
		Assume.assumeNoException( e );
	}
}
 
Example #18
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenPullingImage_thenImageListNotEmpty() throws InterruptedException {

    // when
    dockerClient.pullImageCmd("alpine").withTag("latest").exec(new PullImageResultCallback()).awaitCompletion(30, TimeUnit.SECONDS);

    // then
    List<Image> images = dockerClient.listImagesCmd().exec();
    assertThat(images.size(), is(not(0)));
}
 
Example #19
Source File: DockerImageManagementService.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteItem(ResourceItem item) {
    Map<String, String> additionalProperties = item.getAdditionalPropertiesMap();

    String imageName = additionalProperties.get("repository") + ":" + additionalProperties.get("tag");
    DockerClient dockerClient = newDockerClient(item.getResourceServer().getHost(), item.getResourceServer().getPort());
    List<Image> images = dockerClient.listImagesCmd().withShowAll(true).withImageNameFilter(imageName).exec();
    if (images.isEmpty()) {
        log.warn("The image {} to be deleted is not existed.", imageName);
        return;
    }
    dockerClient.removeImageCmd(imageName).exec();
}
 
Example #20
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenRemovingImage_thenImageListDecrease() {

    // when
    List<Image> images = dockerClient.listImagesCmd().exec();
    Image image = images.get(0);
    dockerClient.removeImageCmd(image.getId()).exec();

    // then
    List<Image> imagesNow = dockerClient.listImagesCmd().exec();
    assertThat(imagesNow.size(), is(lessThan(images.size())));
}
 
Example #21
Source File: DockerUtils.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a Docker image if it exists.
 * @param imageId the image ID (not null)
 * @param dockerClient a Docker client
 */
public static void deleteImageIfItExists( String imageId, DockerClient dockerClient ) {

	if( imageId != null ) {
		List<Image> images = dockerClient.listImagesCmd().exec();
		if( findImageById( imageId, images ) != null )
			dockerClient.removeImageCmd( imageId ).withForce( true ).exec();
	}
}
 
Example #22
Source File: ListImagesWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    Map<String, Object> results = new HashMap<>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String showAll = (String) workItem.getParameter("ShowAll");

        if (dockerClient == null) {
            DockerClientConnector connector = new DockerClientConnector();
            dockerClient = connector.getDockerClient();
        }

        ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
        if (showAll != null && Boolean.parseBoolean(showAll)) {
            listImagesCmd = listImagesCmd.withShowAll(true);
        }

        List<Image> images = listImagesCmd.exec();

        results.put(RESULTS_DOCUMENT,
                    images);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Unable to get list of containers: " + e.getMessage());
        handleException(e);
    }
}
 
Example #23
Source File: DockerWorkitemHandlerTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    try {
        List<Container> testContainers = new ArrayList<>();
        List<Image> testImages = new ArrayList<>();

        when(dockerClient.createContainerCmd(anyString())).thenReturn(createContainerCmd);
        when(createContainerCmd.withName(anyString())).thenReturn(createContainerCmd);
        when(createContainerCmd.exec()).thenReturn(createContainerResponse);
        when(createContainerResponse.getId()).thenReturn("1");

        when(dockerClient.inspectContainerCmd(anyString())).thenReturn(inspectContainerCmd);
        when(inspectContainerCmd.exec()).thenReturn(inspectContainerResponse);

        when(dockerClient.killContainerCmd(anyString())).thenReturn(killContainerCmd);

        when(dockerClient.listContainersCmd()).thenReturn(listContainersCmd);
        when(listContainersCmd.withShowAll(any(Boolean.class))).thenReturn(listContainersCmd);
        when(listContainersCmd.withShowSize(any(Boolean.class))).thenReturn(listContainersCmd);
        when(listContainersCmd.exec()).thenReturn(testContainers);

        when(dockerClient.listImagesCmd()).thenReturn(listImagesCmd);
        when(listImagesCmd.exec()).thenReturn(testImages);

        when(dockerClient.startContainerCmd(anyString())).thenReturn(startContainerCmd);

        when(dockerClient.stopContainerCmd(anyString())).thenReturn(stopContainerCmd);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example #24
Source File: DockerHelperTest.java    From dew with Apache License 2.0 5 votes vote down vote up
/**
 * Test all.
 */
@Test
public void testAll() {
    // Init Project
    DockerHelper.inst("").image.remove("harbor.dew.test/unit-test/test:1.0");
    DockerHelper.inst("").image.remove(defaultDockerRegistryHost + "/unit-test/test:1.0");
    DockerHelper.inst("").registry.removeImage(defaultDockerRegistryHost + "/unit-test/test");
    DockerHelper.inst("").registry.removeImage(defaultDockerRegistryHost + "/unit-test/test_copy");
    DockerHelper.inst("").registry.deleteProject("unit-test");
    Assert.assertTrue(DockerHelper.inst("").registry.createProject("unit-test"));

    DockerHelper.inst("").image.pull("alpine:3.6", false);
    List<Image> images = DockerHelper.inst("").image.list("alpine:3.6");
    Assert.assertEquals("alpine:3.6", images.get(0).getRepoTags()[0]);
    DockerHelper.inst("").image.build("harbor.dew.test/unit-test/test:1.0", this.getClass().getResource("/").getPath());
    DockerHelper.inst("").image.copy("harbor.dew.test/unit-test/test:1.0", defaultDockerRegistryHost + "/unit-test/test:1.0");
    Assert.assertEquals(1, DockerHelper.inst("").image.list(defaultDockerRegistryHost + "/unit-test/test:1.0").size());
    DockerHelper.inst("").image.push(defaultDockerRegistryHost + "/unit-test/test:1.0", true);
    DockerHelper.inst("").image.remove(defaultDockerRegistryHost + "/unit-test/test:1.0");
    Assert.assertEquals(0, DockerHelper.inst("").image.list(defaultDockerRegistryHost + "/unit-test/test:1.0").size());
    Assert.assertTrue(DockerHelper.inst("").registry.existImage(defaultDockerRegistryHost + "/unit-test/test:1.0"));
    // Test Copy Image
    Assert.assertTrue(DockerHelper.inst("").registry.copyImage("unit-test/test:1.0", "unit-test","test_copy"));
    // Test Remove Image
    DockerHelper.inst("").registry.removeImage(defaultDockerRegistryHost + "/unit-test/test:1.0");
    Assert.assertFalse(DockerHelper.inst("").registry.existImage(defaultDockerRegistryHost + "/unit-test/test:1.0"));

    // Test label
    Assert.assertNull(DockerHelper.inst("").registry.getLabel("commit", Optional.of("unit-test")));
    Assert.assertTrue(DockerHelper.inst("").registry.createOrUpdateLabel("commit", "ssssss", Optional.of("unit-test")));
    Assert.assertEquals("ssssss", DockerHelper.inst("").registry.getLabel("commit", Optional.of("unit-test")).getDescription());
    Assert.assertTrue(DockerHelper.inst("").registry.createOrUpdateLabel("commit", "ccccc", Optional.of("unit-test")));
    Assert.assertEquals("ccccc", DockerHelper.inst("").registry.getLabel("commit", Optional.of("unit-test")).getDescription());

}
 
Example #25
Source File: DockerImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
List<Image> listAllImages() {
    try {
        return dockerClient.listImagesCmd().withShowAll(true).exec();
    } catch (RuntimeException e) {
        numberOfDockerApiFails.increment();
        throw new DockerException("Failed to list all images", e);
    }
}
 
Example #26
Source File: DockerImageGarbageCollector.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Set<String> getRecentlyUsedImageIds(List<Image> images, List<Container> containers, Duration minImageAgeToDelete) {
    final Instant now = clock.instant();

    // Add any already downloaded image to the list once
    images.forEach(image -> lastTimeUsedByImageId.putIfAbsent(image.getId(), now));

    // Update last used time for all current containers
    containers.forEach(container -> lastTimeUsedByImageId.put(container.getImageId(), now));

    // Return list of images that have been used within minImageAgeToDelete
    return lastTimeUsedByImageId.entrySet().stream()
            .filter(entry -> Duration.between(entry.getValue(), now).minus(minImageAgeToDelete).isNegative())
            .map(Map.Entry::getKey)
            .collect(Collectors.toSet());
}
 
Example #27
Source File: DockerImageGarbageCollector.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Attemps to make dockerImages which may be image tags or image ids to image ids. This only works
 * if the given tag is actually present locally. This is fine, because if it isn't - we can't delete
 * it, so no harm done.
 */
private Set<String> dockerImageToImageIds(List<DockerImage> dockerImages, List<Image> images) {
    Map<String, String> imageIdByImageTag = images.stream()
            .flatMap(image -> referencesOf(image).stream()
                                                 .map(repoTag -> new Pair<>(repoTag, image.getId())))
            .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond));

    return dockerImages.stream()
            .map(DockerImage::asString)
            .map(tag -> imageIdByImageTag.getOrDefault(tag, tag))
            .collect(Collectors.toSet());
}
 
Example #28
Source File: DockerImageGarbageCollector.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if ancestor is a parent or grand-parent or grand-grand-parent, etc. of img
 */
private boolean imageIsDescendantOf(Map<String, Image> imageIdToImage, String img, String ancestor) {
    while (imageIdToImage.containsKey(img)) {
        img = imageIdToImage.get(img).getParentId();
        if (img == null) return false;
        if (ancestor.equals(img)) return true;
    }
    return false;
}
 
Example #29
Source File: DockerImageGarbageCollector.java    From vespa with Apache License 2.0 5 votes vote down vote up
/**
 * Returns list of references to given image, preferring image tag(s), if any exist.
 *
 * If image is untagged, its ID is returned instead.
 */
private static List<String> referencesOf(Image image) {
    if (image.getRepoTags() == null) {
        return List.of(image.getId());
    }
    return Arrays.stream(image.getRepoTags())
                 // Docker API returns untagged images as having the tag "<none>:<none>".
                 .map(tag -> {
                     if ("<none>:<none>".equals(tag)) return image.getId();
                     return tag;
                 })
                 .collect(Collectors.toUnmodifiableList());
}
 
Example #30
Source File: DockerClientFactory.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
* Check whether the image is available locally and pull it otherwise
*/
 @SneakyThrows
 public void checkAndPullImage(DockerClient client, String image) {
     List<Image> images = client.listImagesCmd().withImageNameFilter(image).exec();
     if (images.isEmpty()) {
         client.pullImageCmd(image).exec(new TimeLimitedLoggedPullImageResultCallback(log)).awaitCompletion();
     }
 }