com.github.dockerjava.core.command.BuildImageResultCallback Java Examples

The following examples show how to use com.github.dockerjava.core.command.BuildImageResultCallback. 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: docker.java    From jbang with MIT License 6 votes vote down vote up
public static void main(String[] args)
{
    final var dockerClient = DockerClientBuilder.getInstance().build();

    BuildImageResultCallback callback = new BuildImageResultCallback()
    {
        @Override
        public void onNext(BuildResponseItem item)
        {
            System.out.print(item.getStream());
            super.onNext(item);
        }
    };

    dockerClient
            .listImagesCmd()
            .exec().stream()
                .filter(s->s!=null)
                .forEach(it -> System.out.println(it.getId() + " " +
                               String.join(",", Objects.requireNonNullElse(it.getRepoTags(), new String[0]))));
}
 
Example #2
Source File: DockerJavaUtil.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * @param client
 * @param tarPath
 * @param dockerTemplate
 * @param appBinName
 * @param args
 * @return
 * @throws IOException
 */
public static String buildImage(DockerClient client, Set<String> tags, File workSpace, Map<String, String> args) throws IOException, InterruptedException {
    //copyFile2WorkSpace(workSpace, dockerTemplate);
    for(String tag : tags){
        removeImage(client,tag);
    }

    makeDockerFile(new File(workSpace.getCanonicalPath() + "/Dockerfile"));

    BuildImageResultCallback callback = new BuildImageResultCallback() {
        @Override
        public void onNext(BuildResponseItem item) {
            System.out.println("" + item);
            super.onNext(item);
        }
    };
    BuildImageCmd buildImageCmd = client.buildImageCmd(workSpace).withTags(tags);
    for (Map.Entry<String, String> entry : args.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        buildImageCmd.withBuildArg(key, value);
    }

    return buildImageCmd.exec(callback).awaitImageId();
}
 
Example #3
Source File: DockerServiceImpl.java    From Dolphin with Apache License 2.0 6 votes vote down vote up
private boolean buildImage(DockerfileRequest request, DockerfileResponse response) throws Exception {
    logger.info(String.format("begin buildImage: %s", request));

    try {
        File dockerFileTemplate = new File(request.getDockerfileTemplateLocation());
        String dockerfileContent = templateService.getContentFromTemplateFile(dockerFileTemplate, request.getDockerfileParams());
        response.setDockerfileContent(dockerfileContent);

        File dockerfile = FileUtil.write(request.getDockerfileLocation(), dockerfileContent);

        String imageId = dockerClient.buildImageCmd(dockerfile).withTag(buildImageTag(request)).exec(new BuildImageResultCallback()).awaitImageId();
        response.setImageId(imageId);
        response.success();
    } catch (Exception e) {
        response.fail(e.toString());
        logger.error(String.format("error buildImage: %s", request), e);
    }

    logger.info(String.format("end buildImage: %s", response));

    return response.isSuccess();
}
 
Example #4
Source File: DockerUtil.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
 * 创建Docker镜像
 *
 * @param dockerFilePath dockerFile文件路径
 * @param tag 镜像的标签
 * @return
 */
public static String buildImage(String dockerFilePath, String tag) {
  DockerClient dockerClient = getDockerClient();

  BuildImageResultCallback callback =
      new BuildImageResultCallback() {
        @Override
        public void onNext(BuildResponseItem item) {
          logger.info(item.toString());
          super.onNext(item);
        }
      };

  String imageId =
      dockerClient
          .buildImageCmd()
          .withDockerfile(new File(dockerFilePath))
          .withTags(Sets.newHashSet(tag))
          .exec(callback)
          .awaitImageId();

  closeDockerClient(dockerClient);

  logger.info("build image success, imageId:" + imageId);

  return imageId;
}
 
Example #5
Source File: DockerBuilderPublisher.java    From docker-plugin with MIT License 5 votes vote down vote up
@Nonnull
private String buildImage() throws IOException, InterruptedException {
    final AuthConfigurations auths = new AuthConfigurations();
    final DockerRegistryEndpoint pullRegistry = getFromRegistry();
    if (pullRegistry != null && pullRegistry.getCredentialsId() != null) {
        auths.addConfig(DockerCloud.getAuthConfig(pullRegistry, run.getParent().getParent()));
    }
    log("Docker Build: building image at path " + fpChild.getRemote());
    final InputStream tar = fpChild.act(new DockerBuildCallable());
    BuildImageResultCallback resultCallback = new BuildImageResultCallback() {
        @Override
        public void onNext(BuildResponseItem item) {
            String text = item.getStream();
            if (text != null) {
                listener.getLogger().println(text);
            }
            super.onNext(item);
        }
    };
    final String imageId;
    try(final DockerClient client = getClientWithNoTimeout()) {
        imageId = client.buildImageCmd(tar)
                .withNoCache(noCache)
                .withPull(pull)
                .withBuildAuthConfigs(auths)
                .exec(resultCallback)
                .awaitImageId();
        if (imageId == null) {
            throw new AbortException("Built image id is null. Some error occured");
        }
        // tag built image with tags
        for (String thisTag : tagsToUse) {
            final NameParser.ReposTag reposTag = NameParser.parseRepositoryTag(thisTag);
            final String commitTag = isEmpty(reposTag.tag) ? "latest" : reposTag.tag;
            log("Tagging built image with " + reposTag.repos + ":" + commitTag);
            client.tagImageCmd(imageId, reposTag.repos, commitTag).withForce().exec();
        }
    }
    return imageId;
}
 
Example #6
Source File: ImageLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenBuildingImage_thenMustReturnImageId() {

    // when
    String imageId = dockerClient.buildImageCmd().withDockerfile(new File("src/test/resources/dockerapi/Dockerfile")).withPull(true).withNoCache(true).withTag("alpine:git").exec(new BuildImageResultCallback()).awaitImageId();

    // then
    assertThat(imageId, is(not(null)));
}
 
Example #7
Source File: CreateImageCommand.java    From cubeai with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws DockerException {
	if (dockerFolder == null) {
		logger.error( "dockerFolder is not configured");
		throw new IllegalArgumentException("dockerFolder is not configured");
	}
	if (imageName == null) {
		logger.error( "imageName is not configured");
		throw new IllegalArgumentException("imageName is not configured");
	}
	if (imageTag == null) {
		logger.error( "imageName is not configured");
		throw new IllegalArgumentException("imageTag is not configured");
	}
	if (!dockerFolder.exists()) {
		logger.error( "configured dockerFolder '" + dockerFolder + "' does not exist.");
		throw new IllegalArgumentException("configured dockerFolder '" + dockerFolder + "' does not exist.");
	}
	final Map<String, String> buildArgsMap = new HashMap<String, String>();
	if ((buildArgs != null) && (!buildArgs.trim().isEmpty())) {
		logger.debug("Parsing buildArgs: " + buildArgs);
		String[] split = buildArgs.split(",|;");
		for (String arg : split) {
			String[] pair = arg.split("=");
			if (pair.length == 2) {
				buildArgsMap.put(pair[0].trim(), pair[1].trim());
			} else {
				logger.error("Invalid format for " + arg + ". Buildargs should be formatted as key=value");
			}
		}
	}
	String dockerFile = this.dockerFile == null ? "Dockerfile" : this.dockerFile;
	File docker = new File(dockerFolder, dockerFile);
	if (!docker.exists()) {
		logger.error( "Configured Docker file '%s' does not exist. {}", dockerFile);
		throw new IllegalArgumentException(String.format("Configured Docker file '%s' does not exist.", dockerFile));
	}
	DockerClient client = getClient();
	try {
		BuildImageResultCallback callback = new BuildImageResultCallback() {
			@Override
			public void onNext(BuildResponseItem item) {
				super.onNext(item);
			}
		};

		BuildImageCmd buildImageCmd = client.buildImageCmd(docker)
				.withTags(new HashSet<>(Arrays.asList(imageName + ":" + imageTag))).withNoCache(noCache)
				.withRemove(rm); // .withTag(imageName + ":" + imageTag)
		if (!buildArgsMap.isEmpty()) {
			for (final Map.Entry<String, String> entry : buildArgsMap.entrySet()) {
				buildImageCmd = buildImageCmd.withBuildArg(entry.getKey(), entry.getValue());
			}
		}
		BuildImageResultCallback result = buildImageCmd.exec(callback);
		this.imageId = result.awaitImageId();

	} catch (Exception e) {
		logger.error( "Error {}", e.getMessage());
		throw new RuntimeException(e);
	}
}
 
Example #8
Source File: ImageFromDockerfile.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Override
protected final String resolve() {
    Logger logger = DockerLoggerFactory.getLogger(dockerImageName);

    DockerClient dockerClient = DockerClientFactory.instance().client();

    try {
        if (deleteOnExit) {
            ResourceReaper.instance().registerImageForCleanup(dockerImageName);
        }

        BuildImageResultCallback resultCallback = new BuildImageResultCallback() {
            @Override
            public void onNext(BuildResponseItem item) {
                super.onNext(item);

                if (item.isErrorIndicated()) {
                    logger.error(item.getErrorDetail().getMessage());
                } else {
                    logger.debug(StringUtils.chomp(item.getStream(), "\n"));
                }
            }
        };

        // We have to use pipes to avoid high memory consumption since users might want to build really big images
        @Cleanup PipedInputStream in = new PipedInputStream();
        @Cleanup PipedOutputStream out = new PipedOutputStream(in);

        BuildImageCmd buildImageCmd = dockerClient.buildImageCmd(in);
        configure(buildImageCmd);
        Map<String, String> labels = new HashMap<>();
        if (buildImageCmd.getLabels() != null) {
            labels.putAll(buildImageCmd.getLabels());
        }
        labels.putAll(DockerClientFactory.DEFAULT_LABELS);
        buildImageCmd.withLabels(labels);

        prePullDependencyImages(dependencyImageNames);

        BuildImageResultCallback exec = buildImageCmd.exec(resultCallback);

        long bytesToDockerDaemon = 0;

        // To build an image, we have to send the context to Docker in TAR archive format
        try (TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(new GZIPOutputStream(out))) {
            tarArchive.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

            for (Map.Entry<String, Transferable> entry : transferables.entrySet()) {
                Transferable transferable = entry.getValue();
                final String destination = entry.getKey();
                transferable.transferTo(tarArchive, destination);
                bytesToDockerDaemon += transferable.getSize();
            }
            tarArchive.finish();
        }

        log.info("Transferred {} to Docker daemon", FileUtils.byteCountToDisplaySize(bytesToDockerDaemon));
        if (bytesToDockerDaemon > FileUtils.ONE_MB * 50) // warn if >50MB sent to docker daemon
            log.warn("A large amount of data was sent to the Docker daemon ({}). Consider using a .dockerignore file for better performance.",
                    FileUtils.byteCountToDisplaySize(bytesToDockerDaemon));

        exec.awaitImageId();

        return dockerImageName;
    } catch(IOException e) {
        throw new RuntimeException("Can't close DockerClient", e);
    }
}