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

The following examples show how to use com.github.dockerjava.api.model.BuildResponseItem. 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: DockerOpt.java    From dew with Apache License 2.0 6 votes vote down vote up
/**
 * Build.
 *
 * @param imageName      the image name
 * @param dockerfilePath the dockerfile path
 * @param args           the args
 * @param labels         the labels
 * @return image id
 */
public String build(String imageName, String dockerfilePath, Map<String, String> args, Map<String, String> labels) {
    BuildImageCmd buildImageCmd = docker.buildImageCmd(new File(dockerfilePath));
    if (args != null && !args.isEmpty()) {
        args.forEach(buildImageCmd::withBuildArg);
    }
    if (labels != null && !labels.isEmpty()) {
        buildImageCmd.withLabels(labels);
    }
    buildImageCmd.withTags(new HashSet<>() {
        {
            add(imageName);
        }
    });
    return buildImageCmd.exec(new BuildImageResultCallback() {
        @Override
        public void onNext(BuildResponseItem item) {
            super.onNext(item);
            log.debug(item.toString());
        }
    }).awaitImageId();
}
 
Example #3
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 #4
Source File: DockerArtifactHandler.java    From module-ballerina-docker with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(BuildResponseItem item) {
    // handling error
    if (item.isErrorIndicated()) {
        StringBuilder errString = new StringBuilder("[build][error]: ");
        ResponseItem.ErrorDetail errDetail = item.getErrorDetail();
        if (null != errDetail && null != errDetail.getCode()) {
            errString.append("(").append(errDetail.getCode()).append(") ");
        }

        if (null != errDetail && null != errDetail.getMessage()) {
            errString.append(errDetail.getMessage());
        }

        String errorMessage = errString.toString();
        printDebug(errorMessage);
        dockerBuildError.setErrorMsg("unable to build docker image: " + errorMessage);
    }

    String streamLog = item.getStream();
    if (null != streamLog && !"".equals(streamLog.replaceAll("\n", ""))) {
        printDebug("[build][stream] " + streamLog.replaceAll("\n", ""));
    }

    String statusLog = item.getStatus();
    if (null != statusLog && !"".equals(statusLog.replaceAll("\n", ""))) {
        printDebug("[build][status] " + statusLog.replaceAll("\n", ""));
    }

    String imageIdLog = item.getImageId();
    if (null != imageIdLog) {
        printDebug("[build][image-id]: " + imageIdLog);
    }

    super.onNext(item);
}
 
Example #5
Source File: BuildImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(BuildResponseItem item) {
    if (item.isBuildSuccessIndicated()) {
        this.imageId = item.getImageId();
    } else if (item.isErrorIndicated()) {
        this.error = item.getError();
    }
    LOGGER.debug(item.toString());
}
 
Example #6
Source File: BuildImageResultCallback.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void onNext(BuildResponseItem item) {
    if (item.isBuildSuccessIndicated()) {
        this.imageId = item.getImageId();
    } else if (item.isErrorIndicated()) {
        this.error = item.getError();
    }
    LOGGER.debug(item.toString());
}
 
Example #7
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 #8
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 #9
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);
    }
}
 
Example #10
Source File: BuildImageCmdExec.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
protected Void execute0(BuildImageCmd command, ResultCallback<BuildResponseItem> resultCallback) {

    WebTarget webTarget = getBaseResource().path("/build");
    String dockerFilePath = command.getPathToDockerfile();

    if (dockerFilePath != null && command.getRemote() == null && !"Dockerfile".equals(dockerFilePath)) {
        webTarget = webTarget.queryParam("dockerfile", dockerFilePath);
    }

    if (command.getTags() != null && !command.getTags().isEmpty()) {
        webTarget = webTarget.queryParamsSet("t", command.getTags());
    } else if (isNotBlank(command.getTag())) {
        webTarget = webTarget.queryParam("t", command.getTag());
    }

    if (command.getCacheFrom() != null && !command.getCacheFrom().isEmpty()) {
        webTarget = webTarget.queryParam("cachefrom", jsonEncode(command.getCacheFrom()));
    }

    if (command.getRemote() != null) {
        webTarget = webTarget.queryParam("remote", command.getRemote().toString());
    }

    webTarget = booleanQueryParam(webTarget, "q", command.isQuiet());
    webTarget = booleanQueryParam(webTarget, "nocache", command.hasNoCacheEnabled());
    webTarget = booleanQueryParam(webTarget, "pull", command.hasPullEnabled());
    webTarget = booleanQueryParam(webTarget, "rm", command.hasRemoveEnabled());
    webTarget = booleanQueryParam(webTarget, "forcerm", command.isForcerm());

    // this has to be handled differently as it should switch to 'false'
    if (command.hasRemoveEnabled() == null || !command.hasRemoveEnabled()) {
        webTarget = webTarget.queryParam("rm", "false");
    }

    if (command.getMemory() != null) {
        webTarget = webTarget.queryParam("memory", command.getMemory());
    }
    if (command.getMemswap() != null) {
        webTarget = webTarget.queryParam("memswap", command.getMemswap());
    }
    if (command.getCpushares() != null) {
        webTarget = webTarget.queryParam("cpushares", command.getCpushares());
    }
    if (command.getCpusetcpus() != null) {
        webTarget = webTarget.queryParam("cpusetcpus", command.getCpusetcpus());
    }

    if (command.getBuildArgs() != null) {
        webTarget = webTarget.queryParamsJsonMap("buildargs", command.getBuildArgs());
    }

    if (command.getShmsize() != null) {
        webTarget = webTarget.queryParam("shmsize", command.getShmsize());
    }

    if (command.getLabels() != null) {
        webTarget = webTarget.queryParamsJsonMap("labels", command.getLabels());
    }

    if (command.getNetworkMode() != null) {
        webTarget = webTarget.queryParam("networkmode", command.getNetworkMode());
    }

    if (command.getPlatform() != null) {
        webTarget = webTarget.queryParam("platform", command.getPlatform());
    }

    if (command.getTarget() != null) {
        webTarget = webTarget.queryParam("target", command.getTarget());
    }

    if (command.getExtraHosts() != null) {
        webTarget = webTarget.queryParamsSet("extrahosts", command.getExtraHosts());
    }

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

    InvocationBuilder builder = resourceWithOptionalAuthConfig(command, webTarget.request())
            .accept(MediaType.APPLICATION_JSON)
            .header("Content-Type", "application/tar")
            .header("encoding", "gzip");

    builder.post(new TypeReference<BuildResponseItem>() {
    }, resultCallback, command.getTarInputStream());

    return null;
}