Search in sources :

Example 1 with SourceFilesConfiguration

use of com.google.cloud.tools.jib.builder.SourceFilesConfiguration in project jib by google.

the class BuildImageMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    validateParameters();
    ProjectProperties projectProperties = new ProjectProperties(project, getLog());
    if (mainClass == null) {
        mainClass = projectProperties.getMainClassFromMavenJarPlugin();
        if (mainClass == null) {
            throwMojoExecutionExceptionWithHelpMessage(new MojoFailureException("Could not find main class specified in maven-jar-plugin"), "add a `mainClass` configuration to jib-maven-plugin");
        }
    }
    SourceFilesConfiguration sourceFilesConfiguration = projectProperties.getSourceFilesConfiguration();
    // Parses 'from' into image reference.
    ImageReference baseImage = getBaseImageReference();
    // Checks Maven settings for registry credentials.
    session.getSettings().getServer(baseImage.getRegistry());
    Map<String, Authorization> registryCredentials = new HashMap<>(2);
    // Retrieves credentials for the base image registry.
    Authorization baseImageRegistryCredentials = getRegistryCredentialsFromSettings(baseImage.getRegistry());
    if (baseImageRegistryCredentials != null) {
        registryCredentials.put(baseImage.getRegistry(), baseImageRegistryCredentials);
    }
    // Retrieves credentials for the target registry.
    Authorization targetRegistryCredentials = getRegistryCredentialsFromSettings(registry);
    if (targetRegistryCredentials != null) {
        registryCredentials.put(registry, targetRegistryCredentials);
    }
    RegistryCredentials mavenSettingsCredentials = RegistryCredentials.from("Maven settings", registryCredentials);
    ImageReference targetImageReference = ImageReference.of(registry, repository, tag);
    ImageFormat imageFormatToEnum = ImageFormat.valueOf(imageFormat);
    BuildConfiguration buildConfiguration = BuildConfiguration.builder(new MavenBuildLogger(getLog())).setBaseImage(baseImage).setTargetImage(targetImageReference).setCredentialHelperNames(credHelpers).setKnownRegistryCredentials(mavenSettingsCredentials).setMainClass(mainClass).setEnableReproducibleBuilds(enableReproducibleBuilds).setJvmFlags(jvmFlags).setEnvironment(environment).setTargetFormat(imageFormatToEnum.getManifestTemplateClass()).build();
    // Uses a directory in the Maven build cache as the Jib cache.
    Path cacheDirectory = Paths.get(project.getBuild().getDirectory(), CACHE_DIRECTORY_NAME);
    if (!Files.exists(cacheDirectory)) {
        try {
            Files.createDirectory(cacheDirectory);
        } catch (IOException ex) {
            throw new MojoExecutionException("Could not create cache directory: " + cacheDirectory, ex);
        }
    }
    Caches.Initializer cachesInitializer = Caches.newInitializer(cacheDirectory);
    if (useOnlyProjectCache) {
        cachesInitializer.setBaseCacheDirectory(cacheDirectory);
    }
    getLog().info("");
    getLog().info("Pushing image as " + targetImageReference);
    getLog().info("");
    // TODO: Instead of disabling logging, have authentication credentials be provided
    // Disables annoying Apache HTTP client logging.
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "error");
    RegistryClient.setUserAgentSuffix(USER_AGENT_SUFFIX);
    buildImage(new BuildImageSteps(buildConfiguration, sourceFilesConfiguration, cachesInitializer));
    getLog().info("");
    getLog().info("Built and pushed image as " + targetImageReference);
    getLog().info("");
}
Also used : Path(java.nio.file.Path) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) BuildImageSteps(com.google.cloud.tools.jib.builder.BuildImageSteps) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) Caches(com.google.cloud.tools.jib.cache.Caches) RegistryCredentials(com.google.cloud.tools.jib.registry.credentials.RegistryCredentials) Authorization(com.google.cloud.tools.jib.http.Authorization) BuildConfiguration(com.google.cloud.tools.jib.builder.BuildConfiguration) SourceFilesConfiguration(com.google.cloud.tools.jib.builder.SourceFilesConfiguration) ImageReference(com.google.cloud.tools.jib.image.ImageReference)

Example 2 with SourceFilesConfiguration

use of com.google.cloud.tools.jib.builder.SourceFilesConfiguration in project jib by google.

the class ProjectProperties method getSourceFilesConfiguration.

/**
 * @return the {@link SourceFilesConfiguration} based on the current project
 */
SourceFilesConfiguration getSourceFilesConfiguration() throws MojoExecutionException {
    try {
        SourceFilesConfiguration sourceFilesConfiguration = MavenSourceFilesConfiguration.getForProject(project);
        // Logs the different source files used.
        log.info("");
        log.info("Containerizing application with the following files:");
        log.info("");
        log.info("\tDependencies:");
        log.info("");
        sourceFilesConfiguration.getDependenciesFiles().forEach(dependencyFile -> log.info("\t\t" + dependencyFile));
        log.info("\tResources:");
        log.info("");
        sourceFilesConfiguration.getResourcesFiles().forEach(resourceFile -> log.info("\t\t" + resourceFile));
        log.info("\tClasses:");
        log.info("");
        sourceFilesConfiguration.getClassesFiles().forEach(classesFile -> log.info("\t\t" + classesFile));
        log.info("");
        return sourceFilesConfiguration;
    } catch (IOException ex) {
        throw new MojoExecutionException("Obtaining project build output files failed; make sure you have compiled your project " + "before trying to build the image. (Did you accidentally run \"mvn clean " + "jib:build\" instead of \"mvn clean compile jib:build\"?)", ex);
    }
}
Also used : SourceFilesConfiguration(com.google.cloud.tools.jib.builder.SourceFilesConfiguration) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) IOException(java.io.IOException)

Example 3 with SourceFilesConfiguration

use of com.google.cloud.tools.jib.builder.SourceFilesConfiguration in project jib by google.

the class BuildImageTask method getSourceFilesConfiguration.

/**
 * @return the {@link SourceFilesConfiguration} based on the current project
 */
@Internal
private SourceFilesConfiguration getSourceFilesConfiguration() {
    try {
        SourceFilesConfiguration sourceFilesConfiguration = GradleSourceFilesConfiguration.getForProject(getProject());
        // Logs the different source files used.
        getLogger().lifecycle("");
        getLogger().lifecycle("Containerizing application with the following files:");
        getLogger().lifecycle("");
        getLogger().lifecycle("\tDependencies:");
        getLogger().lifecycle("");
        sourceFilesConfiguration.getDependenciesFiles().forEach(dependencyFile -> getLogger().lifecycle("\t\t" + dependencyFile));
        getLogger().lifecycle("\tResources:");
        getLogger().lifecycle("");
        sourceFilesConfiguration.getResourcesFiles().forEach(resourceFile -> getLogger().lifecycle("\t\t" + resourceFile));
        getLogger().lifecycle("\tClasses:");
        getLogger().lifecycle("");
        sourceFilesConfiguration.getClassesFiles().forEach(classesFile -> getLogger().lifecycle("\t\t" + classesFile));
        getLogger().lifecycle("");
        return sourceFilesConfiguration;
    } catch (IOException ex) {
        throw new GradleException("Obtaining project build output files failed", ex);
    }
}
Also used : SourceFilesConfiguration(com.google.cloud.tools.jib.builder.SourceFilesConfiguration) GradleException(org.gradle.api.GradleException) IOException(java.io.IOException) Internal(org.gradle.api.tasks.Internal)

Example 4 with SourceFilesConfiguration

use of com.google.cloud.tools.jib.builder.SourceFilesConfiguration in project jib by google.

the class BuildImageTask method buildImage.

@TaskAction
public void buildImage() throws InvalidImageReferenceException, IOException {
    // Asserts required @Input parameters are not null.
    Preconditions.checkNotNull(from);
    Preconditions.checkNotNull(from.getImage());
    Preconditions.checkNotNull(to);
    Preconditions.checkNotNull(to.getImage());
    Preconditions.checkNotNull(jvmFlags);
    Preconditions.checkNotNull(format);
    ImageReference baseImageReference = ImageReference.parse(from.getImage());
    ImageReference targetImageReference = ImageReference.parse(to.getImage());
    ProjectProperties projectProperties = new ProjectProperties(getProject(), getLogger());
    String mainClass = this.mainClass;
    if (mainClass == null) {
        mainClass = projectProperties.getMainClassFromJarTask();
        if (mainClass == null) {
            throw new GradleException("Could not find main class specified in a 'jar' task");
        }
    }
    SourceFilesConfiguration sourceFilesConfiguration = getSourceFilesConfiguration();
    // TODO: These should be passed separately - one for base image, one for target image.
    List<String> credHelpers = new ArrayList<>();
    if (from.getCredHelper() != null) {
        credHelpers.add(from.getCredHelper());
    }
    if (to.getCredHelper() != null) {
        credHelpers.add(to.getCredHelper());
    }
    BuildConfiguration buildConfiguration = BuildConfiguration.builder(new GradleBuildLogger(getLogger())).setBaseImage(baseImageReference).setTargetImage(targetImageReference).setCredentialHelperNames(credHelpers).setMainClass(mainClass).setEnableReproducibleBuilds(reproducible).setJvmFlags(jvmFlags).setTargetFormat(format).build();
    // Uses a directory in the Gradle build cache as the Jib cache.
    Path cacheDirectory = getProject().getBuildDir().toPath().resolve(CACHE_DIRECTORY_NAME);
    if (!Files.exists(cacheDirectory)) {
        Files.createDirectory(cacheDirectory);
    }
    Caches.Initializer cachesInitializer = Caches.newInitializer(cacheDirectory);
    if (getUseOnlyProjectCache()) {
        cachesInitializer.setBaseCacheDirectory(cacheDirectory);
    }
    getLogger().lifecycle("Pushing image as " + targetImageReference);
    getLogger().lifecycle("");
    getLogger().lifecycle("");
    // TODO: Instead of disabling logging, have authentication credentials be provided
    // Disables annoying Apache HTTP client logging.
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "error");
    // Disables Google HTTP client logging.
    Logger logger = Logger.getLogger(HttpTransport.class.getName());
    logger.setLevel(Level.OFF);
    RegistryClient.setUserAgentSuffix(USER_AGENT_SUFFIX);
    doBuildImage(new BuildImageSteps(buildConfiguration, sourceFilesConfiguration, cachesInitializer));
    getLogger().lifecycle("");
    getLogger().lifecycle("Built and pushed image as " + targetImageReference);
    getLogger().lifecycle("");
}
Also used : Path(java.nio.file.Path) BuildImageSteps(com.google.cloud.tools.jib.builder.BuildImageSteps) ArrayList(java.util.ArrayList) Caches(com.google.cloud.tools.jib.cache.Caches) Logger(java.util.logging.Logger) BuildConfiguration(com.google.cloud.tools.jib.builder.BuildConfiguration) SourceFilesConfiguration(com.google.cloud.tools.jib.builder.SourceFilesConfiguration) HttpTransport(com.google.api.client.http.HttpTransport) ImageReference(com.google.cloud.tools.jib.image.ImageReference) GradleException(org.gradle.api.GradleException) TaskAction(org.gradle.api.tasks.TaskAction)

Example 5 with SourceFilesConfiguration

use of com.google.cloud.tools.jib.builder.SourceFilesConfiguration in project jib by google.

the class DockerContextMojo method createDockerContext.

// TODO: Move most of this to jib-core.
/**
 * Creates the Docker context in {@link #targetDir}.
 */
private void createDockerContext(ProjectProperties projectProperties) throws MojoExecutionException, MojoFailureException {
    SourceFilesConfiguration sourceFilesConfiguration = projectProperties.getSourceFilesConfiguration();
    try {
        Path targetDirPath = Paths.get(targetDir);
        // Deletes the targetDir if it exists.
        if (Files.exists(targetDirPath)) {
            MoreFiles.deleteDirectoryContents(targetDirPath);
        }
        Files.createDirectory(targetDirPath);
        // Creates the directories.
        Path dependenciesDir = targetDirPath.resolve("libs");
        Path resourcesDIr = targetDirPath.resolve("resources");
        Path classesDir = targetDirPath.resolve("classes");
        Files.createDirectory(dependenciesDir);
        Files.createDirectory(resourcesDIr);
        Files.createDirectory(classesDir);
        // Copies dependencies.
        copyFiles(sourceFilesConfiguration.getDependenciesFiles(), dependenciesDir);
        copyFiles(sourceFilesConfiguration.getResourcesFiles(), resourcesDIr);
        copyFiles(sourceFilesConfiguration.getClassesFiles(), classesDir);
        // Creates the Dockerfile.
        Files.write(targetDirPath.resolve("Dockerfile"), makeDockerfile(sourceFilesConfiguration).getBytes(StandardCharsets.UTF_8));
        projectProperties.getLog().info("Created Docker context at " + targetDir);
    } catch (InsecureRecursiveDeleteException ex) {
        throwMojoExecutionExceptionWithHelpMessage(ex, "cannot clear directory '" + targetDir + "' safely - clear it manually before creating the Docker context");
    } catch (IOException ex) {
        throwMojoExecutionExceptionWithHelpMessage(ex, "check if `targetDir` is set correctly");
    }
}
Also used : Path(java.nio.file.Path) SourceFilesConfiguration(com.google.cloud.tools.jib.builder.SourceFilesConfiguration) IOException(java.io.IOException) InsecureRecursiveDeleteException(com.google.common.io.InsecureRecursiveDeleteException)

Aggregations

SourceFilesConfiguration (com.google.cloud.tools.jib.builder.SourceFilesConfiguration)5 IOException (java.io.IOException)4 Path (java.nio.file.Path)3 BuildConfiguration (com.google.cloud.tools.jib.builder.BuildConfiguration)2 BuildImageSteps (com.google.cloud.tools.jib.builder.BuildImageSteps)2 Caches (com.google.cloud.tools.jib.cache.Caches)2 ImageReference (com.google.cloud.tools.jib.image.ImageReference)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 GradleException (org.gradle.api.GradleException)2 HttpTransport (com.google.api.client.http.HttpTransport)1 Authorization (com.google.cloud.tools.jib.http.Authorization)1 RegistryCredentials (com.google.cloud.tools.jib.registry.credentials.RegistryCredentials)1 InsecureRecursiveDeleteException (com.google.common.io.InsecureRecursiveDeleteException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Logger (java.util.logging.Logger)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 Internal (org.gradle.api.tasks.Internal)1 TaskAction (org.gradle.api.tasks.TaskAction)1