Search in sources :

Example 1 with GraalVMExtension

use of org.graalvm.buildtools.gradle.dsl.GraalVMExtension in project spring-native by spring-projects-experimental.

the class SpringAotGradlePlugin method apply.

@Override
public void apply(final Project project) {
    project.getPluginManager().apply(NativeImagePlugin.class);
    project.getPlugins().withType(JavaPlugin.class, javaPlugin -> {
        GraalVMExtension graal = project.getExtensions().findByType(GraalVMExtension.class);
        graal.getToolchainDetection().set(false);
        // Create the "springAot" DSL extension for user configuration
        project.getExtensions().create(EXTENSION_NAME, SpringAotExtension.class, project.getObjects());
        // Automatically add the spring-native dependency to the implementation configuration
        // as it's required for hints
        addSpringNativeDependency(project);
        Path generatedFilesPath = createGeneratedSourcesFolder(project);
        // deprecation replaced with new API introduced in Gradle 7.1
        // noinspection deprecation
        SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();
        // Create a detached configuration that holds dependencies for AOT generation
        SourceSet aotMainSourceSet = createAotMainSourceSet(sourceSets, project.getConfigurations(), generatedFilesPath);
        GenerateAotSources generateAotSources = createGenerateAotSourcesTask(project, sourceSets);
        project.getTasks().named(aotMainSourceSet.getCompileJavaTaskName(), JavaCompile.class, (aotCompileJava) -> {
            aotCompileJava.source(generateAotSources.getSourcesOutputDirectory());
        });
        project.getTasks().named(aotMainSourceSet.getProcessResourcesTaskName(), Copy.class, (aotProcessResources) -> {
            aotProcessResources.from(generateAotSources.getResourcesOutputDirectory());
            aotProcessResources.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE);
        });
        Jar generatedSourcesJar = project.getTasks().create(aotMainSourceSet.getJarTaskName(), Jar.class, jar -> {
            jar.from(aotMainSourceSet.getOutput());
            jar.setGroup(BasePlugin.BUILD_GROUP);
            jar.getArchiveClassifier().convention("aot");
        });
        createAotMainConfiguration(project, aotMainSourceSet);
        // Generated+compiled sources must be used by 'bootRun' and packaged by 'bootJar'
        project.getPlugins().withType(SpringBootPlugin.class, springBootPlugin -> {
            Provider<RegularFile> generatedSources = generatedSourcesJar.getArchiveFile();
            project.getTasks().named(SpringBootPlugin.BOOT_JAR_TASK_NAME, BootJar.class, (bootJar) -> {
                bootJar.setClasspath(project.files(generatedSources).plus(bootJar.getClasspath()));
            });
            project.getTasks().named("bootRun", BootRun.class, (bootRun) -> {
                bootRun.setClasspath(project.files(generatedSources).plus(bootRun.getClasspath()));
            });
        });
        // Create a detached configuration that holds dependencies for AOT test generation
        SourceSet aotTestSourceSet = createAotTestSourceSet(sourceSets, project.getConfigurations(), generatedFilesPath);
        GenerateAotTestSources generateAotTestSources = createGenerateAotTestSourcesTask(project, sourceSets);
        project.getTasks().named(aotTestSourceSet.getCompileJavaTaskName(), JavaCompile.class, (aotTestCompileJava) -> {
            aotTestCompileJava.source(generateAotTestSources.getGeneratedSourcesOutputDirectory());
        });
        project.getTasks().named(aotTestSourceSet.getProcessResourcesTaskName(), Copy.class, (aotTestProcessResources) -> {
            aotTestProcessResources.from(generateAotTestSources.getGeneratedResourcesOutputDirectory());
            aotTestProcessResources.setDuplicatesStrategy(DuplicatesStrategy.INCLUDE);
        });
        Jar generatedTestSourcesJar = project.getTasks().create(aotTestSourceSet.getJarTaskName(), Jar.class, jar -> {
            jar.from(aotTestSourceSet.getOutput());
            jar.setGroup(JavaBasePlugin.VERIFICATION_GROUP);
            jar.getArchiveClassifier().convention("aot-test");
        });
        // Create the aotTest task to allow execution of both regular and aotTest
        createAotTestTask(project, sourceSets, generatedTestSourcesJar);
        project.getPlugins().withType(NativeImagePlugin.class, nativeImagePlugin -> {
            project.getTasks().named(NativeImagePlugin.NATIVE_COMPILE_TASK_NAME).configure(nativeCompile -> {
                nativeCompile.dependsOn(generatedSourcesJar);
            });
            graal.getBinaries().named(NativeImagePlugin.NATIVE_MAIN_EXTENSION).configure(options -> {
                Provider<RegularFile> generatedSources = generatedSourcesJar.getArchiveFile();
                options.classpath(generatedSources);
            });
            graal.getBinaries().named(NativeImagePlugin.NATIVE_TEST_EXTENSION).configure(options -> {
                Provider<RegularFile> generatedTestSources = generatedTestSourcesJar.getArchiveFile();
                options.classpath(generatedTestSources);
                options.runtimeArgs("-Dspring.test.context.default.CacheAwareContextLoaderDelegate=" + "org.springframework.aot.test.AotCacheAwareContextLoaderDelegate");
            });
        });
        // Ensure that Kotlin compilation depends on AOT source generation
        project.getPlugins().withId("org.jetbrains.kotlin.jvm", kotlinPlugin -> {
            project.getTasks().named("compileAotMainKotlin").configure(compileKotlin -> compileKotlin.dependsOn(generateAotSources));
        });
    });
}
Also used : Path(java.nio.file.Path) SourceSet(org.gradle.api.tasks.SourceSet) GraalVMExtension(org.graalvm.buildtools.gradle.dsl.GraalVMExtension) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) RegularFile(org.gradle.api.file.RegularFile) BootJar(org.springframework.boot.gradle.tasks.bundling.BootJar) Jar(org.gradle.api.tasks.bundling.Jar) GenerateAotTestSources(org.springframework.aot.gradle.tasks.GenerateAotTestSources) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) GenerateAotSources(org.springframework.aot.gradle.tasks.GenerateAotSources)

Example 2 with GraalVMExtension

use of org.graalvm.buildtools.gradle.dsl.GraalVMExtension in project micronaut-gradle-plugin by micronaut-projects.

the class MicronautGraalPlugin method apply.

@Override
public void apply(Project project) {
    project.getPluginManager().apply(NativeImagePlugin.class);
    workaroundForResourcesDirectoryMissing(project);
    project.getPluginManager().withPlugin("io.micronaut.minimal.library", plugin -> {
        MicronautExtension extension = project.getExtensions().findByType(MicronautExtension.class);
        configureAnnotationProcessing(project, extension);
    });
    project.getPluginManager().withPlugin("io.micronaut.minimal.application", plugin -> {
        MicronautExtension extension = project.getExtensions().findByType(MicronautExtension.class);
        configureAnnotationProcessing(project, extension);
    });
    GraalVMExtension graal = project.getExtensions().findByType(GraalVMExtension.class);
    graal.getBinaries().configureEach(options -> options.resources(rsrc -> rsrc.autodetection(inf -> {
        inf.getEnabled().convention(true);
        inf.getIgnoreExistingResourcesConfigFile().convention(true);
        inf.getRestrictToProjectDependencies().convention(true);
    })));
    project.getPluginManager().withPlugin("application", plugin -> {
        TaskContainer tasks = project.getTasks();
        tasks.withType(BuildNativeImageTask.class).named("nativeCompile", nativeImageTask -> {
            MicronautRuntime mr = PluginsHelper.resolveRuntime(project);
            if (mr.isLambdaProvided()) {
                DependencySet implementation = project.getConfigurations().getByName("implementation").getDependencies();
                boolean isAwsApp = implementation.stream().noneMatch(dependency -> Objects.equals(dependency.getGroup(), "io.micronaut.aws") && dependency.getName().equals("micronaut-function-aws"));
                if (isAwsApp) {
                    nativeImageTask.getOptions().get().getMainClass().set("io.micronaut.function.aws.runtime.MicronautLambdaRuntime");
                }
            }
        });
        // We use `afterEvaluate` here in order to preserve laziness of task configuration
        // and because there is no API to allow reacting to registration of tasks.
        Set<String> alreadyRegisteredTaskNames = new HashSet<>();
        project.afterEvaluate(p -> tasks.withType(Test.class).getCollectionSchema().getElements().forEach(element -> {
            String testName = element.getName();
            registerTestAgainstNativeImageTask(alreadyRegisteredTaskNames, tasks, testName);
        }));
    });
}
Also used : ProcessResources(org.gradle.language.jvm.tasks.ProcessResources) Arrays(java.util.Arrays) BuildNativeImageTask(org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask) ListProperty(org.gradle.api.provider.ListProperty) DependencySet(org.gradle.api.artifacts.DependencySet) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) SourceSet(org.gradle.api.tasks.SourceSet) HashSet(java.util.HashSet) NativeImagePlugin(org.graalvm.buildtools.gradle.NativeImagePlugin) Provider(org.gradle.api.provider.Provider) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) PathSensitivity(org.gradle.api.tasks.PathSensitivity) MicronautExtension(io.micronaut.gradle.MicronautExtension) GraalVMExtension(org.graalvm.buildtools.gradle.dsl.GraalVMExtension) Test(org.gradle.api.tasks.testing.Test) Project(org.gradle.api.Project) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) PluginsHelper(io.micronaut.gradle.PluginsHelper) Set(java.util.Set) Collectors(java.util.stream.Collectors) File(java.io.File) Objects(java.util.Objects) TaskContainer(org.gradle.api.tasks.TaskContainer) RegularFile(org.gradle.api.file.RegularFile) InputFile(org.gradle.api.tasks.InputFile) PathSensitive(org.gradle.api.tasks.PathSensitive) MicronautRuntime(io.micronaut.gradle.MicronautRuntime) Collections(java.util.Collections) Plugin(org.gradle.api.Plugin) GraalVMExtension(org.graalvm.buildtools.gradle.dsl.GraalVMExtension) TaskContainer(org.gradle.api.tasks.TaskContainer) BuildNativeImageTask(org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask) MicronautExtension(io.micronaut.gradle.MicronautExtension) MicronautRuntime(io.micronaut.gradle.MicronautRuntime) DependencySet(org.gradle.api.artifacts.DependencySet) HashSet(java.util.HashSet)

Example 3 with GraalVMExtension

use of org.graalvm.buildtools.gradle.dsl.GraalVMExtension in project native-build-tools by graalvm.

the class NativeImagePlugin method configureJvmReachabilityConfigurationDirectories.

private void configureJvmReachabilityConfigurationDirectories(Project project, GraalVMExtension graalExtension, NativeImageOptions options, SourceSet sourceSet) {
    JvmReachabilityMetadataRepositoryExtension repositoryExtension = reachabilityExtensionOn(graalExtension);
    Provider<JvmReachabilityMetadataService> serviceProvider = project.getGradle().getSharedServices().registerIfAbsent("nativeConfigurationService", JvmReachabilityMetadataService.class, spec -> {
        LogLevel logLevel = determineLogLevel();
        spec.getParameters().getLogLevel().set(logLevel);
        spec.getParameters().getUri().set(repositoryExtension.getUri());
        spec.getParameters().getCacheDir().set(new File(project.getGradle().getGradleUserHomeDir(), "native-build-tools/repositories"));
    });
    options.getConfigurationFileDirectories().from(repositoryExtension.getEnabled().flatMap(enabled -> {
        if (enabled) {
            if (repositoryExtension.getUri().isPresent()) {
                Configuration classpath = project.getConfigurations().getByName(sourceSet.getRuntimeClasspathConfigurationName());
                Set<String> excludedModules = repositoryExtension.getExcludedModules().getOrElse(Collections.emptySet());
                Map<String, String> forcedVersions = repositoryExtension.getModuleToConfigVersion().getOrElse(Collections.emptyMap());
                return serviceProvider.map(repo -> repo.findConfigurationDirectoriesFor(query -> classpath.getIncoming().getResolutionResult().allComponents(component -> {
                    ModuleVersionIdentifier moduleVersion = component.getModuleVersion();
                    String module = moduleVersion.getGroup() + ":" + moduleVersion.getName();
                    if (!excludedModules.contains(module)) {
                        query.forArtifact(artifact -> {
                            artifact.gav(module + ":" + moduleVersion.getVersion());
                            if (forcedVersions.containsKey(module)) {
                                artifact.forceConfigVersion(forcedVersions.get(module));
                            }
                        });
                    }
                    query.useLatestConfigWhenVersionIsUntested();
                })).stream().map(Path::toAbsolutePath).map(Path::toFile).collect(Collectors.toList()));
            }
        }
        return project.getProviders().provider(Collections::emptySet);
    }));
}
Also used : GradleUtils(org.graalvm.buildtools.gradle.internal.GradleUtils) ConfigurableFileCollection(org.gradle.api.file.ConfigurableFileCollection) Arrays(java.util.Arrays) NativeImageExecutableLocator.graalvmHomeProvider(org.graalvm.buildtools.gradle.internal.NativeImageExecutableLocator.graalvmHomeProvider) BuildNativeImageTask(org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask) URISyntaxException(java.net.URISyntaxException) ListProperty(org.gradle.api.provider.ListProperty) JavaPlugin(org.gradle.api.plugins.JavaPlugin) NamedDomainObjectContainer(org.gradle.api.NamedDomainObjectContainer) NativeConfigurations(org.graalvm.buildtools.gradle.internal.NativeConfigurations) ApplicationPlugin(org.gradle.api.plugins.ApplicationPlugin) OutputDirectory(org.gradle.api.tasks.OutputDirectory) Task(org.gradle.api.Task) Provider(org.gradle.api.provider.Provider) ModuleVersionIdentifier(org.gradle.api.artifacts.ModuleVersionIdentifier) ConfigurationContainer(org.gradle.api.artifacts.ConfigurationContainer) TaskProvider(org.gradle.api.tasks.TaskProvider) NativeImageOptions(org.graalvm.buildtools.gradle.dsl.NativeImageOptions) Locale(java.util.Locale) Map(java.util.Map) DuplicatesStrategy(org.gradle.api.file.DuplicatesStrategy) ExtensionAware(org.gradle.api.plugins.ExtensionAware) GraalVMExtension(org.graalvm.buildtools.gradle.dsl.GraalVMExtension) URI(java.net.URI) Path(java.nio.file.Path) LogLevel(org.gradle.api.logging.LogLevel) Project(org.gradle.api.Project) SharedConstants(org.graalvm.buildtools.utils.SharedConstants) GenerateResourcesConfigFile(org.graalvm.buildtools.gradle.tasks.GenerateResourcesConfigFile) GraalVMLogger(org.graalvm.buildtools.gradle.internal.GraalVMLogger) Set(java.util.Set) JavaForkOptions(org.gradle.process.JavaForkOptions) GFileUtils(org.gradle.util.GFileUtils) Collectors(java.util.stream.Collectors) TaskContainer(org.gradle.api.tasks.TaskContainer) ArchiveOperations(org.gradle.api.file.ArchiveOperations) DefaultTestBinaryConfig(org.graalvm.buildtools.gradle.internal.DefaultTestBinaryConfig) AGENT_OUTPUT_FOLDER(org.graalvm.buildtools.utils.SharedConstants.AGENT_OUTPUT_FOLDER) JavaToolchainService(org.gradle.jvm.toolchain.JavaToolchainService) AgentConfiguration(org.graalvm.buildtools.gradle.dsl.AgentConfiguration) Callable(java.util.concurrent.Callable) AbstractArchiveTask(org.gradle.api.tasks.bundling.AbstractArchiveTask) FileCollection(org.gradle.api.file.FileCollection) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) SourceSet(org.gradle.api.tasks.SourceSet) Inject(javax.inject.Inject) Configuration(org.gradle.api.artifacts.Configuration) LifecycleBasePlugin(org.gradle.language.base.plugins.LifecycleBasePlugin) VersionInfo(org.graalvm.buildtools.VersionInfo) AttributeContainer(org.gradle.api.attributes.AttributeContainer) Attribute(org.gradle.api.attributes.Attribute) DirectoryProperty(org.gradle.api.file.DirectoryProperty) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) ProcessGeneratedGraalResourceFiles(org.graalvm.buildtools.gradle.internal.ProcessGeneratedGraalResourceFiles) Directory(org.gradle.api.file.Directory) JvmReachabilityMetadataRepositoryExtension(org.graalvm.buildtools.gradle.dsl.JvmReachabilityMetadataRepositoryExtension) Test(org.gradle.api.tasks.testing.Test) FileSystemLocation(org.gradle.api.file.FileSystemLocation) FileSystemOperations(org.gradle.api.file.FileSystemOperations) BaseNativeImageOptions(org.graalvm.buildtools.gradle.internal.BaseNativeImageOptions) Jar(org.gradle.api.tasks.bundling.Jar) AGENT_PROPERTY(org.graalvm.buildtools.utils.SharedConstants.AGENT_PROPERTY) Action(org.gradle.api.Action) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) AgentCommandLineProvider(org.graalvm.buildtools.gradle.internal.AgentCommandLineProvider) NativeRunTask(org.graalvm.buildtools.gradle.tasks.NativeRunTask) ExecOperations(org.gradle.process.ExecOperations) DeprecatedNativeImageOptions(org.graalvm.buildtools.gradle.internal.DeprecatedNativeImageOptions) JavaApplication(org.gradle.api.plugins.JavaApplication) File(java.io.File) Consumer(java.util.function.Consumer) ObjectFactory(org.gradle.api.model.ObjectFactory) GradleUtils.transitiveProjectArtifacts(org.graalvm.buildtools.gradle.internal.GradleUtils.transitiveProjectArtifacts) Property(org.gradle.api.provider.Property) DefaultGraalVmExtension(org.graalvm.buildtools.gradle.internal.DefaultGraalVmExtension) JavaExec(org.gradle.api.tasks.JavaExec) JvmReachabilityMetadataService(org.graalvm.buildtools.gradle.internal.JvmReachabilityMetadataService) Collections(java.util.Collections) Plugin(org.gradle.api.Plugin) ModuleVersionIdentifier(org.gradle.api.artifacts.ModuleVersionIdentifier) Path(java.nio.file.Path) Set(java.util.Set) SourceSet(org.gradle.api.tasks.SourceSet) AgentConfiguration(org.graalvm.buildtools.gradle.dsl.AgentConfiguration) Configuration(org.gradle.api.artifacts.Configuration) JvmReachabilityMetadataRepositoryExtension(org.graalvm.buildtools.gradle.dsl.JvmReachabilityMetadataRepositoryExtension) JvmReachabilityMetadataService(org.graalvm.buildtools.gradle.internal.JvmReachabilityMetadataService) GenerateResourcesConfigFile(org.graalvm.buildtools.gradle.tasks.GenerateResourcesConfigFile) File(java.io.File) Map(java.util.Map) LogLevel(org.gradle.api.logging.LogLevel)

Example 4 with GraalVMExtension

use of org.graalvm.buildtools.gradle.dsl.GraalVMExtension in project spring-boot by spring-projects.

the class NativeImagePluginAction method execute.

@Override
public void execute(Project project) {
    project.getPlugins().apply(SpringBootAotPlugin.class);
    project.getPlugins().withType(JavaPlugin.class).all((plugin) -> {
        JavaPluginExtension javaPluginExtension = project.getExtensions().getByType(JavaPluginExtension.class);
        SourceSetContainer sourceSets = javaPluginExtension.getSourceSets();
        SourceSet aotSourceSet = sourceSets.getByName(SpringBootAotPlugin.AOT_SOURCE_SET_NAME);
        project.getTasks().named(NativeImagePlugin.NATIVE_COMPILE_TASK_NAME, BuildNativeImageTask.class, (nativeCompile) -> nativeCompile.getOptions().get().classpath(aotSourceSet.getOutput()));
    });
    GraalVMExtension graalVmExtension = project.getExtensions().getByType(GraalVMExtension.class);
    graalVmExtension.getToolchainDetection().set(false);
}
Also used : SourceSet(org.gradle.api.tasks.SourceSet) GraalVMExtension(org.graalvm.buildtools.gradle.dsl.GraalVMExtension) JavaPlugin(org.gradle.api.plugins.JavaPlugin) JavaPluginExtension(org.gradle.api.plugins.JavaPluginExtension) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer)

Example 5 with GraalVMExtension

use of org.graalvm.buildtools.gradle.dsl.GraalVMExtension in project micronaut-gradle-plugin by micronaut-projects.

the class MicronautAotPlugin method registerOptimizedBinary.

private void registerOptimizedBinary(Project project, TaskProvider<MicronautAotOptimizerTask> prepareNative) {
    GraalVMExtension graalVMExtension = project.getExtensions().getByType(GraalVMExtension.class);
    NamedDomainObjectContainer<NativeImageOptions> binaries = graalVMExtension.getBinaries();
    binaries.create(OPTIMIZED_BINARY_NAME, binary -> {
        NativeImageOptions main = binaries.getByName(MAIN_BINARY_NAME);
        binary.getMainClass().set(main.getMainClass());
        binary.getClasspath().from(main.getClasspath());
        binary.getClasspath().from(prepareNative.map(MicronautAotOptimizerTask::getGeneratedClassesDirectory));
        project.getPlugins().withId("java-library", p -> binary.getSharedLibrary().convention(true));
    });
}
Also used : GraalVMExtension(org.graalvm.buildtools.gradle.dsl.GraalVMExtension) NativeImageOptions(org.graalvm.buildtools.gradle.dsl.NativeImageOptions)

Aggregations

GraalVMExtension (org.graalvm.buildtools.gradle.dsl.GraalVMExtension)8 NativeImageOptions (org.graalvm.buildtools.gradle.dsl.NativeImageOptions)5 File (java.io.File)4 Path (java.nio.file.Path)4 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4 BaseNativeImageOptions (org.graalvm.buildtools.gradle.internal.BaseNativeImageOptions)4 BuildNativeImageTask (org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask)4 Plugin (org.gradle.api.Plugin)4 Project (org.gradle.api.Project)4 SourceSet (org.gradle.api.tasks.SourceSet)4 SourceSetContainer (org.gradle.api.tasks.SourceSetContainer)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 Locale (java.util.Locale)3 Map (java.util.Map)3 Callable (java.util.concurrent.Callable)3 Consumer (java.util.function.Consumer)3