Search in sources :

Example 1 with JavaContainerBuilder

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

the class JibProcessor method createContainerBuilderFromLegacyJar.

private JibContainerBuilder createContainerBuilderFromLegacyJar(String baseJvmImage, JibConfig jibConfig, ContainerImageConfig containerImageConfig, JarBuildItem sourceJarBuildItem, OutputTargetBuildItem outputTargetBuildItem, MainClassBuildItem mainClassBuildItem, List<ContainerImageLabelBuildItem> containerImageLabels) {
    try {
        // not ideal since this has been previously zipped - we would like to just reuse it
        Path classesDir = outputTargetBuildItem.getOutputDirectory().resolve("jib");
        ZipUtils.unzip(sourceJarBuildItem.getPath(), classesDir);
        JavaContainerBuilder javaContainerBuilder = JavaContainerBuilder.from(toRegistryImage(ImageReference.parse(baseJvmImage), jibConfig.baseRegistryUsername, jibConfig.baseRegistryPassword)).addResources(classesDir, IS_CLASS_PREDICATE.negate()).addClasses(classesDir, IS_CLASS_PREDICATE);
        // when there is no custom entry point, we just set everything up for a regular java run
        if (!jibConfig.jvmEntrypoint.isPresent()) {
            javaContainerBuilder.addJvmFlags(determineEffectiveJvmArguments(jibConfig, Optional.empty())).setMainClass(mainClassBuildItem.getClassName());
        }
        if (sourceJarBuildItem.getLibraryDir() != null) {
            try (Stream<Path> dependenciesPaths = Files.list(sourceJarBuildItem.getLibraryDir())) {
                javaContainerBuilder.addDependencies(dependenciesPaths.filter(p -> Files.isRegularFile(p) && p.getFileName().toString().endsWith(".jar")).sorted(Comparator.comparing(Path::getFileName)).collect(Collectors.toList()));
            }
        }
        JibContainerBuilder jibContainerBuilder = javaContainerBuilder.toContainerBuilder().setEnvironment(getEnvironmentVariables(jibConfig)).setLabels(allLabels(jibConfig, containerImageConfig, containerImageLabels));
        if (jibConfig.useCurrentTimestamp) {
            jibContainerBuilder.setCreationTime(Instant.now());
        }
        if (jibConfig.jvmEntrypoint.isPresent()) {
            jibContainerBuilder.setEntrypoint(jibConfig.jvmEntrypoint.get());
        }
        return jibContainerBuilder;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (InvalidImageReferenceException e) {
        throw new RuntimeException(e);
    }
}
Also used : Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) ImageReference(com.google.cloud.tools.jib.api.ImageReference) ContainerImageBuilderBuildItem(io.quarkus.container.spi.ContainerImageBuilderBuildItem) JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) UpxCompressedBuildItem(io.quarkus.deployment.pkg.builditem.UpxCompressedBuildItem) Port(com.google.cloud.tools.jib.api.buildplan.Port) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) DirectoryStream(java.nio.file.DirectoryStream) Map(java.util.Map) Path(java.nio.file.Path) IsNormalNotRemoteDev(io.quarkus.deployment.IsNormalNotRemoteDev) ContainerImageLabelBuildItem(io.quarkus.container.spi.ContainerImageLabelBuildItem) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) NativeImageBuildItem(io.quarkus.deployment.pkg.builditem.NativeImageBuildItem) ZipUtils(io.quarkus.fs.util.ZipUtils) Predicate(java.util.function.Predicate) ContainerImagePushRequestBuildItem(io.quarkus.container.spi.ContainerImagePushRequestBuildItem) JarBuildItem(io.quarkus.deployment.pkg.builditem.JarBuildItem) PathsUtil.findMainSourcesRoot(io.quarkus.container.util.PathsUtil.findMainSourcesRoot) Collection(java.util.Collection) ContainerImageConfig(io.quarkus.container.image.deployment.ContainerImageConfig) Set(java.util.Set) FilePermissions(com.google.cloud.tools.jib.api.buildplan.FilePermissions) Instant(java.time.Instant) InvalidImageReferenceException(com.google.cloud.tools.jib.api.InvalidImageReferenceException) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) PackageConfig(io.quarkus.deployment.pkg.PackageConfig) ContainerImageInfoBuildItem(io.quarkus.container.spi.ContainerImageInfoBuildItem) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) Stream(java.util.stream.Stream) ConfigProvider(org.eclipse.microprofile.config.ConfigProvider) FileEntry(com.google.cloud.tools.jib.api.buildplan.FileEntry) ResolvedDependency(io.quarkus.maven.dependency.ResolvedDependency) Optional(java.util.Optional) NativeBinaryUtil(io.quarkus.container.image.deployment.util.NativeBinaryUtil) AvailableContainerImageExtensionBuildItem(io.quarkus.container.spi.AvailableContainerImageExtensionBuildItem) AppCDSResultBuildItem(io.quarkus.deployment.pkg.builditem.AppCDSResultBuildItem) AppCDSContainerImageBuildItem(io.quarkus.deployment.pkg.builditem.AppCDSContainerImageBuildItem) ContainerRuntimeUtil(io.quarkus.runtime.util.ContainerRuntimeUtil) DockerDaemonImage(com.google.cloud.tools.jib.api.DockerDaemonImage) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) Version(io.quarkus.builder.Version) Logger(org.jboss.logging.Logger) JibContainer(com.google.cloud.tools.jib.api.JibContainer) RegistryImage(com.google.cloud.tools.jib.api.RegistryImage) HashMap(java.util.HashMap) EnablementUtil.pushContainerImageNeeded(io.quarkus.container.image.deployment.util.EnablementUtil.pushContainerImageNeeded) CurateOutcomeBuildItem(io.quarkus.deployment.pkg.builditem.CurateOutcomeBuildItem) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) CompiledJavaVersionBuildItem(io.quarkus.deployment.pkg.builditem.CompiledJavaVersionBuildItem) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BuildStep(io.quarkus.deployment.annotations.BuildStep) Jib(com.google.cloud.tools.jib.api.Jib) CredentialRetrieverFactory(com.google.cloud.tools.jib.frontend.CredentialRetrieverFactory) ContainerImageBuildRequestBuildItem(io.quarkus.container.spi.ContainerImageBuildRequestBuildItem) Files(java.nio.file.Files) ArtifactResultBuildItem(io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem) IOException(java.io.IOException) NativeBuild(io.quarkus.deployment.pkg.steps.NativeBuild) LogEvent(com.google.cloud.tools.jib.api.LogEvent) Containerizer(com.google.cloud.tools.jib.api.Containerizer) Paths(java.nio.file.Paths) OutputTargetBuildItem(io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem) PathsUtil(io.quarkus.container.util.PathsUtil) EnablementUtil.buildContainerImageNeeded(io.quarkus.container.image.deployment.util.EnablementUtil.buildContainerImageNeeded) Comparator(java.util.Comparator) Collections(java.util.Collections) MainClassBuildItem(io.quarkus.deployment.builditem.MainClassBuildItem) JarResultBuildStep(io.quarkus.deployment.pkg.steps.JarResultBuildStep) JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) InvalidImageReferenceException(com.google.cloud.tools.jib.api.InvalidImageReferenceException) UncheckedIOException(java.io.UncheckedIOException) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException)

Example 2 with JavaContainerBuilder

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

the class GradleProjectPropertiesTest method setupBuildContext.

private BuildContext setupBuildContext() throws InvalidImageReferenceException, CacheDirectoryCreationException {
    JavaContainerBuilder javaContainerBuilder = JavaContainerBuilder.from(RegistryImage.named("base")).setAppRoot(AbsoluteUnixPath.get("/my/app")).setModificationTimeProvider((ignored1, ignored2) -> EPOCH_PLUS_32);
    JibContainerBuilder jibContainerBuilder = gradleProjectProperties.createJibContainerBuilder(javaContainerBuilder, ContainerizingMode.EXPLODED);
    return JibContainerBuilderTestHelper.toBuildContext(jibContainerBuilder, Containerizer.to(RegistryImage.named("to")));
}
Also used : JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder)

Example 3 with JavaContainerBuilder

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

the class GradleProjectProperties method createJibContainerBuilder.

@Override
public JibContainerBuilder createJibContainerBuilder(JavaContainerBuilder javaContainerBuilder, ContainerizingMode containerizingMode) {
    try {
        FileCollection projectDependencies = project.files(project.getConfigurations().getByName(configurationName).getResolvedConfiguration().getResolvedArtifacts().stream().filter(artifact -> artifact.getId().getComponentIdentifier() instanceof ProjectComponentIdentifier).map(ResolvedArtifact::getFile).collect(Collectors.toList()));
        if (isWarProject()) {
            String warFilePath = getWarFilePath();
            log(LogEvent.info("WAR project identified, creating WAR image from: " + warFilePath));
            Path explodedWarPath = tempDirectoryProvider.newDirectory();
            ZipUtil.unzip(Paths.get(warFilePath), explodedWarPath);
            return JavaContainerBuilderHelper.fromExplodedWar(javaContainerBuilder, explodedWarPath, projectDependencies.getFiles().stream().map(File::getName).collect(Collectors.toSet()));
        }
        SourceSet mainSourceSet = getMainSourceSet();
        FileCollection classesOutputDirectories = mainSourceSet.getOutput().getClassesDirs().filter(File::exists);
        Path resourcesOutputDirectory = mainSourceSet.getOutput().getResourcesDir().toPath();
        FileCollection allFiles = project.getConfigurations().getByName(configurationName).filter(File::exists);
        FileCollection nonProjectDependencies = allFiles.minus(classesOutputDirectories).minus(projectDependencies).filter(file -> !file.toPath().equals(resourcesOutputDirectory));
        FileCollection snapshotDependencies = nonProjectDependencies.filter(file -> file.getName().contains("SNAPSHOT"));
        FileCollection dependencies = nonProjectDependencies.minus(snapshotDependencies);
        // Adds dependency files
        javaContainerBuilder.addDependencies(dependencies.getFiles().stream().map(File::toPath).collect(Collectors.toList())).addSnapshotDependencies(snapshotDependencies.getFiles().stream().map(File::toPath).collect(Collectors.toList())).addProjectDependencies(projectDependencies.getFiles().stream().map(File::toPath).collect(Collectors.toList()));
        switch(containerizingMode) {
            case EXPLODED:
                // Adds resource files
                if (Files.exists(resourcesOutputDirectory)) {
                    javaContainerBuilder.addResources(resourcesOutputDirectory);
                }
                // Adds class files
                for (File classesOutputDirectory : classesOutputDirectories) {
                    javaContainerBuilder.addClasses(classesOutputDirectory.toPath());
                }
                if (classesOutputDirectories.isEmpty()) {
                    log(LogEvent.warn("No classes files were found - did you compile your project?"));
                }
                break;
            case PACKAGED:
                // Add a JAR
                Jar jarTask = (Jar) project.getTasks().findByName("jar");
                Path jarPath = jarTask.getArchiveFile().get().getAsFile().toPath();
                log(LogEvent.debug("Using JAR: " + jarPath));
                javaContainerBuilder.addToClasspath(jarPath);
                break;
            default:
                throw new IllegalStateException("unknown containerizing mode: " + containerizingMode);
        }
        return javaContainerBuilder.toContainerBuilder();
    } catch (IOException ex) {
        throw new GradleException("Obtaining project build output files failed", ex);
    }
}
Also used : JavaContainerBuilderHelper(com.google.cloud.tools.jib.plugins.common.JavaContainerBuilderHelper) ProjectComponentIdentifier(org.gradle.api.artifacts.component.ProjectComponentIdentifier) ImageReference(com.google.cloud.tools.jib.api.ImageReference) SingleThreadedExecutor(com.google.cloud.tools.jib.plugins.common.logging.SingleThreadedExecutor) ProgressEvent(com.google.cloud.tools.jib.event.events.ProgressEvent) PropertyNames(com.google.cloud.tools.jib.plugins.common.PropertyNames) JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) TimerEventHandler(com.google.cloud.tools.jib.plugins.common.TimerEventHandler) Task(org.gradle.api.Task) Provider(org.gradle.api.provider.Provider) TaskProvider(org.gradle.api.tasks.TaskProvider) Locale(java.util.Locale) Duration(java.time.Duration) Path(java.nio.file.Path) Verify(com.google.common.base.Verify) Project(org.gradle.api.Project) Predicate(java.util.function.Predicate) ServiceLoader(java.util.ServiceLoader) TimerEvent(com.google.cloud.tools.jib.event.events.TimerEvent) InvalidImageReferenceException(com.google.cloud.tools.jib.api.InvalidImageReferenceException) PluginExtensionLogger(com.google.cloud.tools.jib.plugins.common.PluginExtensionLogger) Collectors(java.util.stream.Collectors) JavaVersion(org.gradle.api.JavaVersion) ZipUtil(com.google.cloud.tools.jib.plugins.common.ZipUtil) ContainerizingMode(com.google.cloud.tools.jib.plugins.common.ContainerizingMode) ProjectProperties(com.google.cloud.tools.jib.plugins.common.ProjectProperties) List(java.util.List) ProgressDisplayGenerator(com.google.cloud.tools.jib.plugins.common.logging.ProgressDisplayGenerator) Optional(java.util.Optional) ContainerBuildPlan(com.google.cloud.tools.jib.api.buildplan.ContainerBuildPlan) ConsoleLogger(com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger) NullExtension(com.google.cloud.tools.jib.plugins.extension.NullExtension) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) WarPlugin(org.gradle.api.plugins.WarPlugin) JibPluginExtensionException(com.google.cloud.tools.jib.plugins.extension.JibPluginExtensionException) Supplier(java.util.function.Supplier) FileCollection(org.gradle.api.file.FileCollection) Logger(org.gradle.api.logging.Logger) ArrayList(java.util.ArrayList) SourceSet(org.gradle.api.tasks.SourceSet) ExtensionConfiguration(com.google.cloud.tools.jib.plugins.common.RawConfiguration.ExtensionConfiguration) TempDirectoryProvider(com.google.cloud.tools.jib.filesystem.TempDirectoryProvider) Nullable(javax.annotation.Nullable) ConsoleLoggerBuilder(com.google.cloud.tools.jib.plugins.common.logging.ConsoleLoggerBuilder) Action(org.gradle.api.Action) Files(java.nio.file.Files) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) ResolvedArtifact(org.gradle.api.artifacts.ResolvedArtifact) Jar(org.gradle.jvm.tasks.Jar) DirectoryWalker(com.google.cloud.tools.jib.filesystem.DirectoryWalker) IOException(java.io.IOException) ProgressEventHandler(com.google.cloud.tools.jib.event.progress.ProgressEventHandler) File(java.io.File) LogEvent(com.google.cloud.tools.jib.api.LogEvent) Os(org.apache.tools.ant.taskdefs.condition.Os) Containerizer(com.google.cloud.tools.jib.api.Containerizer) JibGradlePluginExtension(com.google.cloud.tools.jib.gradle.extension.JibGradlePluginExtension) Paths(java.nio.file.Paths) GradleException(org.gradle.api.GradleException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Path(java.nio.file.Path) SourceSet(org.gradle.api.tasks.SourceSet) ResolvedArtifact(org.gradle.api.artifacts.ResolvedArtifact) GradleException(org.gradle.api.GradleException) Jar(org.gradle.jvm.tasks.Jar) IOException(java.io.IOException) FileCollection(org.gradle.api.file.FileCollection) ProjectComponentIdentifier(org.gradle.api.artifacts.component.ProjectComponentIdentifier) File(java.io.File)

Example 4 with JavaContainerBuilder

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

the class PluginConfigurationProcessor method processCommonConfiguration.

@VisibleForTesting
static JibContainerBuilder processCommonConfiguration(RawConfiguration rawConfiguration, InferredAuthProvider inferredAuthProvider, ProjectProperties projectProperties) throws InvalidFilesModificationTimeException, InvalidAppRootException, IncompatibleBaseImageJavaVersionException, IOException, InvalidImageReferenceException, InvalidContainerizingModeException, MainClassInferenceException, InvalidPlatformException, InvalidContainerVolumeException, InvalidWorkingDirectoryException, InvalidCreationTimeException, ExtraDirectoryNotFoundException {
    // Create and configure JibContainerBuilder
    ModificationTimeProvider modificationTimeProvider = createModificationTimeProvider(rawConfiguration.getFilesModificationTime());
    JavaContainerBuilder javaContainerBuilder = getJavaContainerBuilderWithBaseImage(rawConfiguration, projectProperties, inferredAuthProvider).setAppRoot(getAppRootChecked(rawConfiguration, projectProperties)).setModificationTimeProvider(modificationTimeProvider);
    JibContainerBuilder jibContainerBuilder = projectProperties.createJibContainerBuilder(javaContainerBuilder, getContainerizingModeChecked(rawConfiguration, projectProperties));
    jibContainerBuilder.setFormat(rawConfiguration.getImageFormat()).setPlatforms(getPlatformsSet(rawConfiguration)).setEntrypoint(computeEntrypoint(rawConfiguration, projectProperties, jibContainerBuilder)).setProgramArguments(rawConfiguration.getProgramArguments().orElse(null)).setEnvironment(rawConfiguration.getEnvironment()).setExposedPorts(Ports.parse(rawConfiguration.getPorts())).setVolumes(getVolumesSet(rawConfiguration)).setLabels(rawConfiguration.getLabels()).setUser(rawConfiguration.getUser().orElse(null)).setCreationTime(getCreationTime(rawConfiguration.getCreationTime(), projectProperties));
    getWorkingDirectoryChecked(rawConfiguration).ifPresent(jibContainerBuilder::setWorkingDirectory);
    // Adds all the extra files.
    for (ExtraDirectoriesConfiguration extraDirectory : rawConfiguration.getExtraDirectories()) {
        Path from = extraDirectory.getFrom();
        if (Files.exists(from)) {
            jibContainerBuilder.addFileEntriesLayer(JavaContainerBuilderHelper.extraDirectoryLayerConfiguration(from, AbsoluteUnixPath.get(extraDirectory.getInto()), extraDirectory.getIncludesList(), extraDirectory.getExcludesList(), rawConfiguration.getExtraDirectoryPermissions(), modificationTimeProvider));
        } else if (!from.endsWith(DEFAULT_JIB_DIR)) {
            throw new ExtraDirectoryNotFoundException(from.toString(), from.toString());
        }
    }
    return jibContainerBuilder;
}
Also used : Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) ModificationTimeProvider(com.google.cloud.tools.jib.api.buildplan.ModificationTimeProvider) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) ExtraDirectoriesConfiguration(com.google.cloud.tools.jib.plugins.common.RawConfiguration.ExtraDirectoriesConfiguration) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with JavaContainerBuilder

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

the class MavenProjectPropertiesTest method setUpBuildContext.

private BuildContext setUpBuildContext(ContainerizingMode containerizingMode) throws InvalidImageReferenceException, IOException, CacheDirectoryCreationException {
    JavaContainerBuilder javaContainerBuilder = JavaContainerBuilder.from(RegistryImage.named("base")).setAppRoot(AbsoluteUnixPath.get("/my/app")).setModificationTimeProvider((ignored1, ignored2) -> EPOCH_PLUS_32);
    JibContainerBuilder jibContainerBuilder = mavenProjectProperties.createJibContainerBuilder(javaContainerBuilder, containerizingMode);
    return JibContainerBuilderTestHelper.toBuildContext(jibContainerBuilder, Containerizer.to(RegistryImage.named("to")));
}
Also used : JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder)

Aggregations

JavaContainerBuilder (com.google.cloud.tools.jib.api.JavaContainerBuilder)15 JibContainerBuilder (com.google.cloud.tools.jib.api.JibContainerBuilder)15 Path (java.nio.file.Path)11 AbsoluteUnixPath (com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath)7 IOException (java.io.IOException)7 Files (java.nio.file.Files)7 Paths (java.nio.file.Paths)7 List (java.util.List)7 Optional (java.util.Optional)7 Predicate (java.util.function.Predicate)7 DirectoryWalker (com.google.cloud.tools.jib.filesystem.DirectoryWalker)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)6 Containerizer (com.google.cloud.tools.jib.api.Containerizer)5 ImageReference (com.google.cloud.tools.jib.api.ImageReference)5 InvalidImageReferenceException (com.google.cloud.tools.jib.api.InvalidImageReferenceException)5 LogEvent (com.google.cloud.tools.jib.api.LogEvent)5 ContainerBuildPlan (com.google.cloud.tools.jib.api.buildplan.ContainerBuildPlan)4 ProgressEvent (com.google.cloud.tools.jib.event.events.ProgressEvent)4 TimerEvent (com.google.cloud.tools.jib.event.events.TimerEvent)4 ProgressEventHandler (com.google.cloud.tools.jib.event.progress.ProgressEventHandler)4