Search in sources :

Example 16 with Containerizer

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

the class Jar 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(jarFile)) {
            logger.log(LogEvent.Level.ERROR, "The file path provided does not exist: " + jarFile);
            return 1;
        }
        if (Files.isDirectory(jarFile)) {
            logger.log(LogEvent.Level.ERROR, "The file path provided is for a directory. Please provide a path to a JAR: " + jarFile);
            return 1;
        }
        if (!commonContainerConfigCliOptions.getEntrypoint().isEmpty() && !jvmFlags.isEmpty()) {
            logger.log(LogEvent.Level.WARN, "--jvm-flags is ignored when --entrypoint is specified");
        }
        Path jarFileParentDir = Verify.verifyNotNull(jarFile.toAbsolutePath().getParent());
        CacheDirectories cacheDirectories = CacheDirectories.from(commonCliOptions, jarFileParentDir);
        ArtifactProcessor processor = ArtifactProcessors.fromJar(jarFile, cacheDirectories, this, commonContainerConfigCliOptions);
        JibContainerBuilder containerBuilder = JarFiles.toJibContainerBuilder(processor, this, 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 : Verify(com.google.common.base.Verify) SingleThreadedExecutor(com.google.cloud.tools.jib.plugins.common.logging.SingleThreadedExecutor) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) 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) JarFiles(com.google.cloud.tools.jib.cli.jar.JarFiles) Multimaps(com.google.common.collect.Multimaps) LogEvent(com.google.cloud.tools.jib.api.LogEvent) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) Future(java.util.concurrent.Future) ProcessingMode(com.google.cloud.tools.jib.cli.jar.ProcessingMode) 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) CommandSpec(picocli.CommandLine.Model.CommandSpec) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Path(java.nio.file.Path) Collections(java.util.Collections) ConsoleLogger(com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger) CommandLine(picocli.CommandLine) 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 17 with Containerizer

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

the class PluginConfigurationProcessorTest method testPluginConfigurationProcessor_defaults.

@Test
public void testPluginConfigurationProcessor_defaults() throws InvalidImageReferenceException, IOException, MainClassInferenceException, InvalidAppRootException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, NumberFormatException, InvalidContainerizingModeException, InvalidFilesModificationTimeException, InvalidCreationTimeException, ExtraDirectoryNotFoundException {
    ContainerBuildPlan buildPlan = processCommonConfiguration();
    assertThat(buildPlan.getEntrypoint()).containsExactly("java", "-cp", "/app/resources:/app/classes:/app/libs/*", "java.lang.Object").inOrder();
    verify(containerizer).setBaseImageLayersCache(Containerizer.DEFAULT_BASE_CACHE_DIRECTORY);
    verify(containerizer).setApplicationLayersCache(appCacheDirectory);
    ArgumentMatcher<LogEvent> isLogWarn = logEvent -> logEvent.getLevel() == LogEvent.Level.WARN;
    verify(logger, never()).accept(argThat(isLogWarn));
}
Also used : CredHelperConfiguration(com.google.cloud.tools.jib.plugins.common.RawConfiguration.CredHelperConfiguration) Arrays(java.util.Arrays) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) URISyntaxException(java.net.URISyntaxException) FileTime(java.nio.file.attribute.FileTime) PlatformConfiguration(com.google.cloud.tools.jib.plugins.common.RawConfiguration.PlatformConfiguration) JavaContainerBuilder(com.google.cloud.tools.jib.api.JavaContainerBuilder) ExtraDirectoriesConfiguration(com.google.cloud.tools.jib.plugins.common.RawConfiguration.ExtraDirectoriesConfiguration) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArgumentMatcher(org.mockito.ArgumentMatcher) JUnitParamsRunner(junitparams.JUnitParamsRunner) Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) JibContainerBuilderTestHelper(com.google.cloud.tools.jib.api.JibContainerBuilderTestHelper) FilePermissions(com.google.cloud.tools.jib.api.buildplan.FilePermissions) InvalidImageReferenceException(com.google.cloud.tools.jib.api.InvalidImageReferenceException) Instant(java.time.Instant) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) FileEntry(com.google.cloud.tools.jib.api.buildplan.FileEntry) Optional(java.util.Optional) ContainerBuildPlan(com.google.cloud.tools.jib.api.buildplan.ContainerBuildPlan) Platform(com.google.cloud.tools.jib.api.buildplan.Platform) Parameters(junitparams.Parameters) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) ImageConfiguration(com.google.cloud.tools.jib.configuration.ImageConfiguration) Mock(org.mockito.Mock) Assert.assertThrows(org.junit.Assert.assertThrows) RegistryImage(com.google.cloud.tools.jib.api.RegistryImage) RunWith(org.junit.runner.RunWith) FileEntriesLayer(com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer) Jib(com.google.cloud.tools.jib.api.Jib) CacheDirectoryCreationException(com.google.cloud.tools.jib.api.CacheDirectoryCreationException) ImmutableList(com.google.common.collect.ImmutableList) MockitoJUnit(org.mockito.junit.MockitoJUnit) Truth8.assertThat(com.google.common.truth.Truth8.assertThat) Nullable(javax.annotation.Nullable) Before(org.junit.Before) Answers(org.mockito.Answers) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) ModificationTimeProvider(com.google.cloud.tools.jib.api.buildplan.ModificationTimeProvider) File(java.io.File) Mockito.verify(org.mockito.Mockito.verify) Correspondence(com.google.common.truth.Correspondence) Consumer(java.util.function.Consumer) LogEvent(com.google.cloud.tools.jib.api.LogEvent) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) Rule(org.junit.Rule) Containerizer(com.google.cloud.tools.jib.api.Containerizer) Paths(java.nio.file.Paths) DateTimeFormatter(java.time.format.DateTimeFormatter) RestoreSystemProperties(org.junit.contrib.java.lang.system.RestoreSystemProperties) MockitoRule(org.mockito.junit.MockitoRule) Collections(java.util.Collections) TemporaryFolder(org.junit.rules.TemporaryFolder) LogEvent(com.google.cloud.tools.jib.api.LogEvent) ContainerBuildPlan(com.google.cloud.tools.jib.api.buildplan.ContainerBuildPlan) Test(org.junit.Test)

Example 18 with Containerizer

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

the class PluginConfigurationProcessor method createJibBuildRunnerForDockerDaemonImage.

/**
 * Generate a runner for image builds to docker daemon.
 *
 * @param rawConfiguration the raw configuration from the plugin
 * @param inferredAuthProvider the plugin specific auth provider
 * @param projectProperties an plugin specific implementation of {@link ProjectProperties}
 * @param globalConfig the Jib global config
 * @param helpfulSuggestions a plugin specific instance of {@link HelpfulSuggestions}
 * @return new {@link JibBuildRunner} to execute a build
 * @throws InvalidImageReferenceException if the image reference is invalid
 * @throws MainClassInferenceException if a main class could not be found
 * @throws InvalidAppRootException if the specific path for application root is invalid
 * @throws IOException if an error occurs creating the container builder
 * @throws InvalidWorkingDirectoryException if the working directory specified for the build is
 *     invalid
 * @throws InvalidPlatformException if there exists a {@link PlatformConfiguration} in the
 *     specified platforms list that is missing required fields or has invalid values
 * @throws InvalidContainerVolumeException if a specific container volume is invalid
 * @throws IncompatibleBaseImageJavaVersionException if the base image java version cannot support
 *     this build
 * @throws NumberFormatException if a string to number conversion operation fails
 * @throws InvalidContainerizingModeException if an invalid {@link ContainerizingMode} was
 *     specified
 * @throws InvalidFilesModificationTimeException if configured modification time could not be
 *     parsed
 * @throws InvalidCreationTimeException if configured creation time could not be parsed
 * @throws JibPluginExtensionException if an error occurred while running plugin extensions
 * @throws ExtraDirectoryNotFoundException if the extra directory specified for the build is not
 *     found
 */
public static JibBuildRunner createJibBuildRunnerForDockerDaemonImage(RawConfiguration rawConfiguration, InferredAuthProvider inferredAuthProvider, ProjectProperties projectProperties, GlobalConfig globalConfig, HelpfulSuggestions helpfulSuggestions) throws InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, IOException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, NumberFormatException, InvalidContainerizingModeException, InvalidFilesModificationTimeException, InvalidCreationTimeException, ExtraDirectoryNotFoundException, JibPluginExtensionException {
    ImageReference targetImageReference = getGeneratedTargetDockerTag(rawConfiguration, projectProperties, helpfulSuggestions);
    DockerDaemonImage targetImage = DockerDaemonImage.named(targetImageReference);
    Optional<Path> dockerExecutable = rawConfiguration.getDockerExecutable();
    if (dockerExecutable.isPresent()) {
        targetImage.setDockerExecutable(dockerExecutable.get());
    }
    targetImage.setDockerEnvironment(rawConfiguration.getDockerEnvironment());
    Containerizer containerizer = Containerizer.to(targetImage);
    Multimaps.asMap(globalConfig.getRegistryMirrors()).forEach(containerizer::addRegistryMirrors);
    JibContainerBuilder jibContainerBuilder = processCommonConfiguration(rawConfiguration, inferredAuthProvider, projectProperties, containerizer);
    JibContainerBuilder updatedContainerBuilder = projectProperties.runPluginExtensions(rawConfiguration.getPluginExtensions(), jibContainerBuilder).setFormat(ImageFormat.Docker);
    return JibBuildRunner.forBuildToDockerDaemon(updatedContainerBuilder, containerizer, projectProperties::log, helpfulSuggestions, targetImageReference, rawConfiguration.getToTags()).writeImageDigest(rawConfiguration.getDigestOutputPath()).writeImageId(rawConfiguration.getImageIdOutputPath()).writeImageJson(rawConfiguration.getImageJsonOutputPath());
}
Also used : Path(java.nio.file.Path) AbsoluteUnixPath(com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath) ImageReference(com.google.cloud.tools.jib.api.ImageReference) Containerizer(com.google.cloud.tools.jib.api.Containerizer) DockerDaemonImage(com.google.cloud.tools.jib.api.DockerDaemonImage) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder)

Example 19 with Containerizer

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

the class PluginConfigurationProcessor method createJibBuildRunnerForRegistryImage.

/**
 * Generate a runner for image builds to registries.
 *
 * @param rawConfiguration the raw configuration from the plugin
 * @param inferredAuthProvider the plugin specific auth provider
 * @param projectProperties an plugin specific implementation of {@link ProjectProperties}
 * @param globalConfig the Jib global config
 * @param helpfulSuggestions a plugin specific instance of {@link HelpfulSuggestions}
 * @return new {@link JibBuildRunner} to execute a build
 * @throws InvalidImageReferenceException if the image reference is invalid
 * @throws MainClassInferenceException if a main class could not be found
 * @throws InvalidAppRootException if the specific path for application root is invalid
 * @throws IOException if an error occurs creating the container builder
 * @throws InvalidWorkingDirectoryException if the working directory specified for the build is
 *     invalid
 * @throws InvalidPlatformException if there exists a {@link PlatformConfiguration} in the
 *     specified platforms list that is missing required fields or has invalid values
 * @throws InvalidContainerVolumeException if a specific container volume is invalid
 * @throws IncompatibleBaseImageJavaVersionException if the base image java version cannot support
 *     this build
 * @throws NumberFormatException if a string to number conversion operation fails
 * @throws InvalidContainerizingModeException if an invalid {@link ContainerizingMode} was
 *     specified
 * @throws InvalidFilesModificationTimeException if configured modification time could not be
 *     parsed
 * @throws InvalidCreationTimeException if configured creation time could not be parsed
 * @throws JibPluginExtensionException if an error occurred while running plugin extensions
 * @throws ExtraDirectoryNotFoundException if the extra directory specified for the build is not
 *     found
 */
public static JibBuildRunner createJibBuildRunnerForRegistryImage(RawConfiguration rawConfiguration, InferredAuthProvider inferredAuthProvider, ProjectProperties projectProperties, GlobalConfig globalConfig, HelpfulSuggestions helpfulSuggestions) throws InvalidImageReferenceException, MainClassInferenceException, InvalidAppRootException, IOException, InvalidWorkingDirectoryException, InvalidPlatformException, InvalidContainerVolumeException, IncompatibleBaseImageJavaVersionException, NumberFormatException, InvalidContainerizingModeException, InvalidFilesModificationTimeException, InvalidCreationTimeException, JibPluginExtensionException, ExtraDirectoryNotFoundException {
    Optional<String> image = rawConfiguration.getToImage();
    Preconditions.checkArgument(image.isPresent());
    ImageReference targetImageReference = ImageReference.parse(image.get());
    RegistryImage targetImage = RegistryImage.named(targetImageReference);
    configureCredentialRetrievers(rawConfiguration, projectProperties, targetImage, targetImageReference, PropertyNames.TO_AUTH_USERNAME, PropertyNames.TO_AUTH_PASSWORD, rawConfiguration.getToAuth(), inferredAuthProvider, rawConfiguration.getToCredHelper());
    boolean alwaysCacheBaseImage = Boolean.parseBoolean(rawConfiguration.getProperty(PropertyNames.ALWAYS_CACHE_BASE_IMAGE).orElse("false"));
    Containerizer containerizer = Containerizer.to(targetImage).setAlwaysCacheBaseImage(alwaysCacheBaseImage);
    Multimaps.asMap(globalConfig.getRegistryMirrors()).forEach(containerizer::addRegistryMirrors);
    JibContainerBuilder jibContainerBuilder = processCommonConfiguration(rawConfiguration, inferredAuthProvider, projectProperties, containerizer);
    JibContainerBuilder updatedContainerBuilder = projectProperties.runPluginExtensions(rawConfiguration.getPluginExtensions(), jibContainerBuilder);
    return JibBuildRunner.forBuildImage(updatedContainerBuilder, containerizer, projectProperties::log, helpfulSuggestions, targetImageReference, rawConfiguration.getToTags()).writeImageDigest(rawConfiguration.getDigestOutputPath()).writeImageId(rawConfiguration.getImageIdOutputPath()).writeImageJson(rawConfiguration.getImageJsonOutputPath());
}
Also used : ImageReference(com.google.cloud.tools.jib.api.ImageReference) Containerizer(com.google.cloud.tools.jib.api.Containerizer) JibContainerBuilder(com.google.cloud.tools.jib.api.JibContainerBuilder) RegistryImage(com.google.cloud.tools.jib.api.RegistryImage)

Example 20 with Containerizer

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

the class JibProcessor method createContainerizer.

private Containerizer createContainerizer(ContainerImageConfig containerImageConfig, JibConfig jibConfig, ContainerImageInfoBuildItem containerImage, boolean pushRequested) {
    Containerizer containerizer;
    ImageReference imageReference = ImageReference.of(containerImage.getRegistry().orElse(null), containerImage.getRepository(), containerImage.getTag());
    if (pushRequested || containerImageConfig.isPushExplicitlyEnabled()) {
        if (!containerImageConfig.registry.isPresent()) {
            log.info("No container image registry was set, so 'docker.io' will be used");
        }
        RegistryImage registryImage = toRegistryImage(imageReference, containerImageConfig.username, containerImageConfig.password);
        containerizer = Containerizer.to(registryImage);
    } else {
        DockerDaemonImage dockerDaemonImage = DockerDaemonImage.named(imageReference);
        Optional<String> dockerConfigExecutableName = ConfigProvider.getConfig().getOptionalValue("quarkus.docker.executable-name", String.class);
        Optional<String> jibConfigExecutableName = jibConfig.dockerExecutableName;
        if (jibConfigExecutableName.isPresent()) {
            dockerDaemonImage.setDockerExecutable(Paths.get(jibConfigExecutableName.get()));
        } else if (dockerConfigExecutableName.isPresent()) {
            dockerDaemonImage.setDockerExecutable(Paths.get(dockerConfigExecutableName.get()));
        } else {
            // detect the container runtime instead of falling back to 'docker' as the default
            ContainerRuntimeUtil.ContainerRuntime detectedContainerRuntime = ContainerRuntimeUtil.detectContainerRuntime();
            log.infof("Using %s to run the native image builder", detectedContainerRuntime.getExecutableName());
            dockerDaemonImage.setDockerExecutable(Paths.get(detectedContainerRuntime.getExecutableName()));
        }
        containerizer = Containerizer.to(dockerDaemonImage);
    }
    containerizer.setToolName("Quarkus");
    containerizer.setToolVersion(Version.getVersion());
    containerizer.addEventHandler(LogEvent.class, (e) -> {
        if (!e.getMessage().isEmpty()) {
            log.log(toJBossLoggingLevel(e.getLevel()), e.getMessage());
        }
    });
    containerizer.setAllowInsecureRegistries(containerImageConfig.insecure);
    containerizer.setAlwaysCacheBaseImage(jibConfig.alwaysCacheBaseImage);
    containerizer.setOfflineMode(jibConfig.offlineMode);
    return containerizer;
}
Also used : ImageReference(com.google.cloud.tools.jib.api.ImageReference) Containerizer(com.google.cloud.tools.jib.api.Containerizer) DockerDaemonImage(com.google.cloud.tools.jib.api.DockerDaemonImage) RegistryImage(com.google.cloud.tools.jib.api.RegistryImage)

Aggregations

Containerizer (com.google.cloud.tools.jib.api.Containerizer)22 JibContainerBuilder (com.google.cloud.tools.jib.api.JibContainerBuilder)16 LogEvent (com.google.cloud.tools.jib.api.LogEvent)11 Path (java.nio.file.Path)11 ImageReference (com.google.cloud.tools.jib.api.ImageReference)10 Files (java.nio.file.Files)9 Optional (java.util.Optional)9 JibContainer (com.google.cloud.tools.jib.api.JibContainer)8 ConsoleLogger (com.google.cloud.tools.jib.plugins.common.logging.ConsoleLogger)8 InvalidImageReferenceException (com.google.cloud.tools.jib.api.InvalidImageReferenceException)7 RegistryImage (com.google.cloud.tools.jib.api.RegistryImage)7 AbsoluteUnixPath (com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath)7 List (java.util.List)7 Future (java.util.concurrent.Future)7 CliLogger (com.google.cloud.tools.jib.cli.logging.CliLogger)6 GlobalConfig (com.google.cloud.tools.jib.plugins.common.globalconfig.GlobalConfig)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