Search in sources :

Example 1 with JibContainer

use of com.google.cloud.tools.jib.api.JibContainer in project jib by GoogleContainerTools.

the class War method call.

@Override
public Integer call() {
    commonCliOptions.validate();
    SingleThreadedExecutor executor = new SingleThreadedExecutor();
    ConsoleLogger logger = CliLogger.newLogger(commonCliOptions.getVerbosity(), commonCliOptions.getHttpTrace(), commonCliOptions.getConsoleOutput(), spec.commandLine().getOut(), spec.commandLine().getErr(), executor);
    Future<Optional<String>> updateCheckFuture = Futures.immediateFuture(Optional.empty());
    try {
        JibCli.configureHttpLogging(commonCliOptions.getHttpTrace().toJulLevel());
        GlobalConfig globalConfig = GlobalConfig.readConfig();
        updateCheckFuture = JibCli.newUpdateChecker(globalConfig, commonCliOptions.getVerbosity(), logEvent -> logger.log(logEvent.getLevel(), logEvent.getMessage()));
        if (!Files.exists(warFile)) {
            logger.log(LogEvent.Level.ERROR, "The file path provided does not exist: " + warFile);
            return 1;
        }
        if (Files.isDirectory(warFile)) {
            logger.log(LogEvent.Level.ERROR, "The file path provided is for a directory. Please provide a path to a WAR: " + warFile);
            return 1;
        }
        Path warFileParentDir = Verify.verifyNotNull(warFile.toAbsolutePath().getParent());
        CacheDirectories cacheDirectories = CacheDirectories.from(commonCliOptions, warFileParentDir);
        ArtifactProcessor processor = ArtifactProcessors.fromWar(warFile, cacheDirectories, this, commonContainerConfigCliOptions);
        JibContainerBuilder containerBuilder = WarFiles.toJibContainerBuilder(processor, commonCliOptions, commonContainerConfigCliOptions, logger);
        Containerizer containerizer = Containerizers.from(commonCliOptions, logger, cacheDirectories);
        // Enable registry mirrors
        Multimaps.asMap(globalConfig.getRegistryMirrors()).forEach(containerizer::addRegistryMirrors);
        JibContainer jibContainer = containerBuilder.containerize(containerizer);
        JibCli.writeImageJson(commonCliOptions.getImageJsonPath(), jibContainer);
    } catch (InterruptedException ex) {
        JibCli.logTerminatingException(logger, ex, commonCliOptions.isStacktrace());
        Thread.currentThread().interrupt();
        return 1;
    } catch (Exception ex) {
        JibCli.logTerminatingException(logger, ex, commonCliOptions.isStacktrace());
        return 1;
    } finally {
        JibCli.finishUpdateChecker(logger, updateCheckFuture);
        executor.shutDownAndAwaitTermination(Duration.ofSeconds(3));
    }
    return 0;
}
Also used : AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) Verify(com.google.common.base.Verify) SingleThreadedExecutor(com.google.cloud.tools.jib.plugins.common.logging.SingleThreadedExecutor) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) WarFiles(com.google.cloud.tools.jib.cli.war.WarFiles) GlobalConfig(com.google.cloud.tools.jib.plugins.common.globalconfig.GlobalConfig) Files(java.nio.file.Files) JibContainer(com.google.cloud.tools.jib.api.JibContainer) Callable(java.util.concurrent.Callable) Multimaps(com.google.common.collect.Multimaps) LogEvent(com.google.cloud.tools.jib.api.LogEvent) Futures(com.google.common.util.concurrent.Futures) Future(java.util.concurrent.Future) CliLogger(com.google.cloud.tools.jib.cli.logging.CliLogger) Containerizer(com.google.cloud.tools.jib.api.Containerizer) Duration(java.time.Duration) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Path(java.nio.file.Path) ConsoleLogger(com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger) CommandLine(picocli.CommandLine) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) Path(java.nio.file.Path) Optional(java.util.Optional) GlobalConfig(com.google.cloud.tools.jib.plugins.common.globalconfig.GlobalConfig) JibContainer(com.google.cloud.tools.jib.api.JibContainer) SingleThreadedExecutor(com.google.cloud.tools.jib.plugins.common.logging.SingleThreadedExecutor) ConsoleLogger(com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger) Containerizer(com.google.cloud.tools.jib.api.Containerizer) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder)

Example 2 with JibContainer

use of com.google.cloud.tools.jib.api.JibContainer in project quarkus by quarkusio.

the class JibProcessor method buildFromNative.

@BuildStep(onlyIf = { IsNormalNotRemoteDev.class, JibBuild.class, NativeBuild.class })
public void buildFromNative(ContainerImageConfig containerImageConfig, JibConfig jibConfig, ContainerImageInfoBuildItem containerImage, NativeImageBuildItem nativeImage, OutputTargetBuildItem outputTarget, Optional<ContainerImageBuildRequestBuildItem> buildRequest, Optional<ContainerImagePushRequestBuildItem> pushRequest, List<ContainerImageLabelBuildItem> containerImageLabels, // used to ensure that we work with the compressed native binary if compression was enabled
Optional<UpxCompressedBuildItem> upxCompressed, BuildProducer<ArtifactResultBuildItem> artifactResultProducer, BuildProducer<ContainerImageBuilderBuildItem> containerImageBuilder) {
    boolean buildContainerImage = buildContainerImageNeeded(containerImageConfig, buildRequest);
    boolean pushContainerImage = pushContainerImageNeeded(containerImageConfig, pushRequest);
    if (!buildContainerImage && !pushContainerImage) {
        return;
    }
    if (!NativeBinaryUtil.nativeIsLinuxBinary(nativeImage)) {
        throw new RuntimeException("The native binary produced by the build is not a Linux binary and therefore cannot be used in a Linux container image. Consider adding \"quarkus.native.container-build=true\" to your configuration");
    }
    JibContainerBuilder jibContainerBuilder = createContainerBuilderFromNative(jibConfig, containerImageConfig, nativeImage, containerImageLabels);
    setUser(jibConfig, jibContainerBuilder);
    setPlatforms(jibConfig, jibContainerBuilder);
    handleExtraFiles(outputTarget, jibContainerBuilder);
    log.info("Starting (local) container image build for native binary using jib.");
    JibContainer container = containerize(containerImageConfig, jibConfig, containerImage, jibContainerBuilder, pushRequest.isPresent());
    writeOutputFiles(container, jibConfig, outputTarget);
    artifactResultProducer.produce(new ArtifactResultBuildItem(null, "native-container", Map.of("container-image", container.getTargetImage().toString(), "pull-required", "" + pushContainerImage)));
    containerImageBuilder.produce(new ContainerImageBuilderBuildItem(JIB));
}
Also used : ContainerImageBuilderBuildItem(io.quarkus.container.spi.ContainerImageBuilderBuildItem) JibContainer(com.google.cloud.tools.jib.api.JibContainer) ArtifactResultBuildItem(io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) BuildStep(io.quarkus.deployment.annotations.BuildStep) JarResultBuildStep(io.quarkus.deployment.pkg.steps.JarResultBuildStep)

Example 3 with JibContainer

use of com.google.cloud.tools.jib.api.JibContainer in project quarkus by quarkusio.

the class JibProcessor method buildFromJar.

@BuildStep(onlyIf = { IsNormalNotRemoteDev.class, JibBuild.class }, onlyIfNot = NativeBuild.class)
public void buildFromJar(ContainerImageConfig containerImageConfig, JibConfig jibConfig, PackageConfig packageConfig, ContainerImageInfoBuildItem containerImage, JarBuildItem sourceJar, MainClassBuildItem mainClass, OutputTargetBuildItem outputTarget, CurateOutcomeBuildItem curateOutcome, CompiledJavaVersionBuildItem compiledJavaVersion, Optional<ContainerImageBuildRequestBuildItem> buildRequest, Optional<ContainerImagePushRequestBuildItem> pushRequest, List<ContainerImageLabelBuildItem> containerImageLabels, Optional<AppCDSResultBuildItem> appCDSResult, BuildProducer<ArtifactResultBuildItem> artifactResultProducer, BuildProducer<ContainerImageBuilderBuildItem> containerImageBuilder) {
    boolean buildContainerImage = buildContainerImageNeeded(containerImageConfig, buildRequest);
    boolean pushContainerImage = pushContainerImageNeeded(containerImageConfig, pushRequest);
    if (!buildContainerImage && !pushContainerImage) {
        return;
    }
    JibContainerBuilder jibContainerBuilder;
    String packageType = packageConfig.type;
    if (packageConfig.isLegacyJar() || packageType.equalsIgnoreCase(PackageConfig.UBER_JAR)) {
        jibContainerBuilder = createContainerBuilderFromLegacyJar(determineBaseJvmImage(jibConfig, compiledJavaVersion), jibConfig, containerImageConfig, sourceJar, outputTarget, mainClass, containerImageLabels);
    } else if (packageConfig.isFastJar()) {
        jibContainerBuilder = createContainerBuilderFromFastJar(determineBaseJvmImage(jibConfig, compiledJavaVersion), jibConfig, containerImageConfig, sourceJar, curateOutcome, containerImageLabels, appCDSResult);
    } else {
        throw new IllegalArgumentException("Package type '" + packageType + "' is not supported by the container-image-jib extension");
    }
    setUser(jibConfig, jibContainerBuilder);
    setPlatforms(jibConfig, jibContainerBuilder);
    handleExtraFiles(outputTarget, jibContainerBuilder);
    log.info("Starting (local) container image build for jar using jib.");
    JibContainer container = containerize(containerImageConfig, jibConfig, containerImage, jibContainerBuilder, pushRequest.isPresent());
    writeOutputFiles(container, jibConfig, outputTarget);
    artifactResultProducer.produce(new ArtifactResultBuildItem(null, "jar-container", Map.of("container-image", container.getTargetImage().toString(), "pull-required", Boolean.toString(pushContainerImage))));
    containerImageBuilder.produce(new ContainerImageBuilderBuildItem(JIB));
}
Also used : ContainerImageBuilderBuildItem(io.quarkus.container.spi.ContainerImageBuilderBuildItem) JibContainer(com.google.cloud.tools.jib.api.JibContainer) ArtifactResultBuildItem(io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) BuildStep(io.quarkus.deployment.annotations.BuildStep) JarResultBuildStep(io.quarkus.deployment.pkg.steps.JarResultBuildStep)

Example 4 with JibContainer

use of com.google.cloud.tools.jib.api.JibContainer in project jib by GoogleContainerTools.

the class JibBuildRunnerTest method testBuildImage_pass.

@Test
public void testBuildImage_pass() throws BuildStepsExecutionException, IOException, CacheDirectoryCreationException {
    JibContainer buildResult = testJibBuildRunner.runBuild();
    Assert.assertNull(buildResult);
}
Also used : JibContainer(com.google.cloud.tools.jib.api.JibContainer) Test(org.junit.Test)

Example 5 with JibContainer

use of com.google.cloud.tools.jib.api.JibContainer in project jib by GoogleContainerTools.

the class JibBuildRunner method runBuild.

/**
 * Runs the Jib build.
 *
 * @return the built {@link JibContainer}
 * @throws BuildStepsExecutionException if another exception is thrown during the build
 * @throws IOException if an I/O exception occurs
 * @throws CacheDirectoryCreationException if the cache directory could not be created
 */
public JibContainer runBuild() throws BuildStepsExecutionException, IOException, CacheDirectoryCreationException {
    try {
        logger.accept(LogEvent.lifecycle(""));
        logger.accept(LogEvent.lifecycle(startupMessage));
        JibContainer jibContainer = jibContainerBuilder.containerize(containerizer);
        logger.accept(LogEvent.lifecycle(""));
        logger.accept(LogEvent.lifecycle(successMessage));
        // when an image is built, write out the digest and id
        if (imageDigestOutputPath != null) {
            String imageDigest = jibContainer.getDigest().toString();
            Files.write(imageDigestOutputPath, imageDigest.getBytes(StandardCharsets.UTF_8));
        }
        if (imageIdOutputPath != null) {
            String imageId = jibContainer.getImageId().toString();
            Files.write(imageIdOutputPath, imageId.getBytes(StandardCharsets.UTF_8));
        }
        if (imageJsonOutputPath != null) {
            ImageMetadataOutput metadataOutput = ImageMetadataOutput.fromJibContainer(jibContainer);
            String imageJson = metadataOutput.toJson();
            Files.write(imageJsonOutputPath, imageJson.getBytes(StandardCharsets.UTF_8));
        }
        return jibContainer;
    } catch (HttpHostConnectException ex) {
        // Failed to connect to registry.
        throw new BuildStepsExecutionException(helpfulSuggestions.forHttpHostConnect(), ex);
    } catch (RegistryUnauthorizedException ex) {
        handleRegistryUnauthorizedException(ex, helpfulSuggestions);
    } catch (RegistryCredentialsNotSentException ex) {
        throw new BuildStepsExecutionException(helpfulSuggestions.forCredentialsNotSent(), ex);
    } catch (RegistryAuthenticationFailedException ex) {
        if (ex.getCause() instanceof ResponseException) {
            handleRegistryUnauthorizedException(new RegistryUnauthorizedException(ex.getServerUrl(), ex.getImageName(), (ResponseException) ex.getCause()), helpfulSuggestions);
        } else {
            // Unknown cause
            throw new BuildStepsExecutionException(helpfulSuggestions.none(), ex);
        }
    } catch (UnknownHostException ex) {
        throw new BuildStepsExecutionException(helpfulSuggestions.forUnknownHost(), ex);
    } catch (InsecureRegistryException ex) {
        throw new BuildStepsExecutionException(helpfulSuggestions.forInsecureRegistry(), ex);
    } catch (RegistryException ex) {
        // keep null-away happy
        String message = Verify.verifyNotNull(ex.getMessage());
        throw new BuildStepsExecutionException(message, ex);
    } catch (ExecutionException ex) {
        String message = ex.getCause().getMessage();
        throw new BuildStepsExecutionException(message == null ? "(null exception message)" : message, ex.getCause());
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new BuildStepsExecutionException(helpfulSuggestions.none(), ex);
    }
    throw new IllegalStateException("unreachable");
}
Also used : RegistryAuthenticationFailedException(com.google.cloud.tools.jib.api.RegistryAuthenticationFailedException) UnknownHostException(java.net.UnknownHostException) ResponseException(com.google.cloud.tools.jib.http.ResponseException) JibContainer(com.google.cloud.tools.jib.api.JibContainer) InsecureRegistryException(com.google.cloud.tools.jib.api.InsecureRegistryException) RegistryException(com.google.cloud.tools.jib.api.RegistryException) InsecureRegistryException(com.google.cloud.tools.jib.api.InsecureRegistryException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) RegistryUnauthorizedException(com.google.cloud.tools.jib.api.RegistryUnauthorizedException) RegistryCredentialsNotSentException(com.google.cloud.tools.jib.registry.RegistryCredentialsNotSentException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

JibContainer (com.google.cloud.tools.jib.api.JibContainer)14 JibContainerBuilder (com.google.cloud.tools.jib.api.JibContainerBuilder)9 Containerizer (com.google.cloud.tools.jib.api.Containerizer)8 LogEvent (com.google.cloud.tools.jib.api.LogEvent)6 CliLogger (com.google.cloud.tools.jib.cli.logging.CliLogger)6 GlobalConfig (com.google.cloud.tools.jib.plugins.common.globalconfig.GlobalConfig)6 ConsoleLogger (com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger)6 SingleThreadedExecutor (com.google.cloud.tools.jib.plugins.common.logging.SingleThreadedExecutor)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)6 Multimaps (com.google.common.collect.Multimaps)6 Futures (com.google.common.util.concurrent.Futures)6 Files (java.nio.file.Files)6 Path (java.nio.file.Path)6 Duration (java.time.Duration)6 Optional (java.util.Optional)6 Callable (java.util.concurrent.Callable)6 Future (java.util.concurrent.Future)6 CommandLine (picocli.CommandLine)6 Verify (com.google.common.base.Verify)4 Collections (java.util.Collections)4