Skip to content

Commit

Permalink
Fix compatibility with configuration cache (#304)
Browse files Browse the repository at this point in the history
* Fix compatibility with configuration cache

This commit reworks the agent task actions so that they are compatible
with the configuration cache. The problem was that when the configuration
cache is enabled, it will try to serialize the task actions that we add,
so that if the task is not up-to-date and that the configuration didn't
change, it can replay the action.

The problem was that our task action used, as an input, a `Provider<List<String>>`,
where those strings represented paths which do _not_ exist when the
action is serialized yet. In practice, we don't care, because those
are implementation details of the task action: the directories will
not exist _before_ the task is executed, and not _after_, they only
exist during task execution.

The configuration cache, however, wants to know about all inputs.
We could have changed the action so that it uses a _root directory_
instead of a list of directories as input, and make the computation
of the `session-` directories _during_ the task action: this would
have worked because the only input would be the "output directory"
that we pass as root. However, the task action is also used in another
task which uses completely different inputs, which are not derived
from a single directory.

At the same time, we _don't_ need the `Provider` semantics in the
task action: all we care about is to have a supplier which will
generate a list of directories. Therefore, we changed the `Provider`
type to a `Supplier` one: the lambda will be serialized, but the
only thing it will capture is the `outputDir` provider which is
fine, configuration-cache wise.

Now, let me take a pill.

Fixes #302

* More configuration cache fixes

Lambdas must be serializable in order to be configuration cache
compatible.

* More configuration cache fixes
  • Loading branch information
melix committed Sep 19, 2022
1 parent 2638b04 commit abbedfb
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 43 deletions.
Expand Up @@ -42,7 +42,6 @@
package org.graalvm.buildtools.gradle

import org.graalvm.buildtools.gradle.fixtures.AbstractFunctionalTest
import spock.lang.Issue
import spock.lang.Unroll

class JavaApplicationWithAgentFunctionalTest extends AbstractFunctionalTest {
Expand Down Expand Up @@ -175,4 +174,39 @@ class JavaApplicationWithAgentFunctionalTest extends AbstractFunctionalTest {
where:
junitVersion = System.getProperty('versions.junit')
}

@Unroll("plugin supports configuration cache (JUnit Platform #junitVersion)")
def "supports configuration cache"() {
debug = true
var metadata_dir = 'src/main/resources/META-INF/native-image'
given:
withSample("java-application-with-reflection")

when:
run 'run', '-Pagent', '--configuration-cache'

then:
tasks {
succeeded ':run'
doesNotContain ':jar'
}

and:
['jni', 'proxy', 'reflect', 'resource', 'serialization'].each { name ->
assert file("build/native/agent-output/run/${name}-config.json").exists()
}

when:
run'run', '-Pagent', '--configuration-cache', '--rerun-tasks'

then:
tasks {
succeeded ':run'
doesNotContain ':jar'
}
outputContains "Reusing configuration cache"

where:
junitVersion = System.getProperty('versions.junit')
}
}
Expand Up @@ -54,8 +54,8 @@
import org.graalvm.buildtools.gradle.internal.DefaultTestBinaryConfig;
import org.graalvm.buildtools.gradle.internal.DeprecatedNativeImageOptions;
import org.graalvm.buildtools.gradle.internal.GraalVMLogger;
import org.graalvm.buildtools.gradle.internal.GradleUtils;
import org.graalvm.buildtools.gradle.internal.GraalVMReachabilityMetadataService;
import org.graalvm.buildtools.gradle.internal.GradleUtils;
import org.graalvm.buildtools.gradle.internal.NativeConfigurations;
import org.graalvm.buildtools.gradle.internal.agent.AgentConfigurationFactory;
import org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask;
Expand Down Expand Up @@ -127,9 +127,13 @@
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializablePredicateOf;
import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializableSupplierOf;
import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializableTransformerOf;
import static org.graalvm.buildtools.gradle.internal.GradleUtils.transitiveProjectArtifacts;
import static org.graalvm.buildtools.gradle.internal.NativeImageExecutableLocator.graalvmHomeProvider;
import static org.graalvm.buildtools.utils.SharedConstants.AGENT_PROPERTY;
Expand Down Expand Up @@ -199,7 +203,7 @@ public void apply(@Nonnull Project project) {

private void instrumentTasksWithAgent(Project project, DefaultGraalVmExtension graalExtension) {
Provider<String> agentMode = agentProperty(project, graalExtension.getAgent());
Predicate<? super Task> taskPredicate = graalExtension.getAgent().getTasksToInstrumentPredicate().get();
Predicate<? super Task> taskPredicate = graalExtension.getAgent().getTasksToInstrumentPredicate().getOrElse(serializablePredicateOf(t -> true));
project.getTasks().configureEach(t -> {
if (isTaskInstrumentableByAgent(t) && taskPredicate.test(t)) {
configureAgent(project, agentMode, graalExtension, getExecOperations(), getFileOperations(), t, (JavaForkOptions) t);
Expand Down Expand Up @@ -565,13 +569,13 @@ private static Provider<String> agentProperty(Project project, AgentOptions opti
return project.getProviders()
.gradleProperty(AGENT_PROPERTY)
.forUseAtConfigurationTime()
.map(v -> {
.map(serializableTransformerOf(v -> {
if (!v.isEmpty()) {
return v;
}
return options.getDefaultMode().get();
})
.orElse(options.getEnabled().map(enabled -> enabled ? options.getDefaultMode().get() : "disabled"));
}))
.orElse(options.getEnabled().map(serializableTransformerOf(enabled -> enabled ? options.getDefaultMode().get() : "disabled")));
}

private static void registerServiceProvider(Project project, Provider<NativeImageService> nativeImageServiceProvider) {
Expand Down Expand Up @@ -726,18 +730,18 @@ public void execute(@Nonnull Task task) {
}
});
AgentCommandLineProvider cliProvider = project.getObjects().newInstance(AgentCommandLineProvider.class);
cliProvider.getInputFiles().from(agentConfiguration.map(AgentConfiguration::getAgentFiles));
cliProvider.getEnabled().set(agentConfiguration.map(AgentConfiguration::isEnabled));
cliProvider.getInputFiles().from(agentConfiguration.map(serializableTransformerOf(AgentConfiguration::getAgentFiles)));
cliProvider.getEnabled().set(agentConfiguration.map(serializableTransformerOf(AgentConfiguration::isEnabled)));
cliProvider.getFilterableEntries().set(graalExtension.getAgent().getFilterableEntries());
cliProvider.getAgentMode().set(agentMode);

Provider<Directory> outputDir = AgentConfigurationFactory.getAgentOutputDirectoryForTask(project.getLayout(), taskToInstrument.getName());
Provider<Boolean> isMergingEnabled = agentConfiguration.map(AgentConfiguration::isEnabled);
Provider<AgentMode> agentModeProvider = agentConfiguration.map(AgentConfiguration::getAgentMode);
Provider<List<String>> mergeOutputDirs = outputDir.map(dir -> Collections.singletonList(dir.getAsFile().getAbsolutePath()));
Provider<List<String>> mergeInputDirs = outputDir.map(NativeImagePlugin::agentSessionDirectories);
Provider<Boolean> isMergingEnabled = agentConfiguration.map(serializableTransformerOf(AgentConfiguration::isEnabled));
Provider<AgentMode> agentModeProvider = agentConfiguration.map(serializableTransformerOf(AgentConfiguration::getAgentMode));
Supplier<List<String>> mergeInputDirs = serializableSupplierOf(() -> outputDir.map(serializableTransformerOf(NativeImagePlugin::agentSessionDirectories)).get());
Supplier<List<String>> mergeOutputDirs = serializableSupplierOf(() -> outputDir.map(serializableTransformerOf(dir -> Collections.singletonList(dir.getAsFile().getAbsolutePath()))).get());
cliProvider.getOutputDirectory().set(outputDir);
cliProvider.getAgentOptions().set(agentConfiguration.map(AgentConfiguration::getAgentCommandLine));
cliProvider.getAgentOptions().set(agentConfiguration.map(serializableTransformerOf(AgentConfiguration::getAgentCommandLine)));
javaForkOptions.getJvmArgumentProviders().add(cliProvider);

taskToInstrument.doLast(new MergeAgentFilesAction(
Expand All @@ -749,8 +753,7 @@ public void execute(@Nonnull Task task) {
mergeInputDirs,
mergeOutputDirs,
graalExtension.getToolchainDetection(),
execOperations,
project.getLogger()));
execOperations));

taskToInstrument.doLast(new CleanupAgentFilesAction(mergeInputDirs, fileOperations));

Expand Down
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package org.graalvm.buildtools.gradle.internal;

import org.gradle.api.Transformer;

import java.io.Serializable;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
* Helper class to deal with Gradle configuration cache.
*/
public class ConfigurationCacheSupport {
/**
* Generates a serializable supplier lambda.
* @param supplier the supplier
* @return a serializable supplier
* @param <T> the type of the supplier
*/
public static <T> Supplier<T> serializableSupplierOf(SerializableSupplier<T> supplier) {
return supplier;
}

/**
* Generates a serializable predicate lambda.
* @param predicate the predicate
* @return a serializable predicate
* @param <T> the type of the predicate
*/
public static <T> Predicate<T> serializablePredicateOf(SerializablePredicate<T> predicate) {
return predicate;
}

/**
* Generates a serializable transformer lambda.
* @param transformer the transformer
* @return a serializable transformer
* @param <OUT> the output type of the transformer
* @param <IN> the input type of the transformer
*/
public static <OUT, IN> Transformer<OUT, IN> serializableTransformerOf(SerializableTransformer<OUT, IN> transformer) {
return transformer;
}

public interface SerializableSupplier<T> extends Supplier<T>, Serializable {

}

public interface SerializablePredicate<T> extends Predicate<T>, Serializable {

}

public interface SerializableTransformer<OUT, IN> extends Transformer<OUT, IN>, Serializable {

}

}
Expand Up @@ -59,9 +59,9 @@
import java.util.Arrays;

public abstract class DefaultGraalVmExtension implements GraalVMExtension {
private final NamedDomainObjectContainer<NativeImageOptions> nativeImages;
private final NativeImagePlugin plugin;
private final Project project;
private final transient NamedDomainObjectContainer<NativeImageOptions> nativeImages;
private final transient NativeImagePlugin plugin;
private final transient Project project;
private final Property<JavaLauncher> defaultJavaLauncher;

@Inject
Expand All @@ -76,7 +76,6 @@ public DefaultGraalVmExtension(NamedDomainObjectContainer<NativeImageOptions> na
nativeImages.configureEach(options -> options.getJavaLauncher().convention(defaultJavaLauncher));
getTestSupport().convention(true);
AgentOptions agentOpts = getAgent();
agentOpts.getTasksToInstrumentPredicate().convention(t -> true);
agentOpts.getDefaultMode().convention("standard");
agentOpts.getEnabled().convention(false);
agentOpts.getModes().getConditional().getParallel().convention(true);
Expand Down
Expand Up @@ -59,11 +59,12 @@
import java.util.Collections;
import java.util.stream.Collectors;

import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializableTransformerOf;
import static org.graalvm.buildtools.utils.SharedConstants.AGENT_OUTPUT_FOLDER;

public class AgentConfigurationFactory {
public static Provider<AgentConfiguration> getAgentConfiguration(Provider<String> modeName, AgentOptions options) {
return modeName.map(name -> {
return modeName.map(serializableTransformerOf(name -> {
AgentMode agentMode;
ConfigurableFileCollection callerFilterFiles = options.getCallerFilterFiles();
ConfigurableFileCollection accessFilterFiles = options.getAccessFilterFiles();
Expand Down Expand Up @@ -95,7 +96,7 @@ public static Provider<AgentConfiguration> getAgentConfiguration(Provider<String
options.getEnableExperimentalUnsafeAllocationTracing().get(),
options.getTrackReflectionMetadata().get(),
agentMode);
});
}));
}

private static Collection<String> getFilePaths(ConfigurableFileCollection configurableFileCollection) {
Expand Down
Expand Up @@ -62,6 +62,7 @@
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import static org.graalvm.buildtools.gradle.internal.NativeImageExecutableLocator.graalvmHomeProvider;
Expand Down Expand Up @@ -112,7 +113,7 @@ public void overrideOutputDirectories(List<String> outputDirectories) {
@TaskAction
public void exec() {
StringBuilder builder = new StringBuilder();
ListProperty<String> inputDirectories = objectFactory.listProperty(String.class);
List<String> inputDirectories = new ArrayList<>();

for (String taskName : getInputTaskNames().get()) {
File dir = AgentConfigurationFactory.getAgentOutputDirectoryForTask(layout, taskName).get().getAsFile();
Expand All @@ -128,7 +129,7 @@ public void exec() {
throw new GradleException(errorString);
}

ListProperty<String> outputDirectories = objectFactory.listProperty(String.class);
List<String> outputDirectories = new ArrayList<>();
for (String dirName : getOutputDirectories().get()) {
File dir = layout.dir(providerFactory.provider(() -> new File(dirName))).get().getAsFile();
outputDirectories.add(dir.getAbsolutePath());
Expand All @@ -155,10 +156,9 @@ public void exec() {
getMergeWithExisting(),
objectFactory,
graalvmHomeProvider(providerFactory),
inputDirectories,
outputDirectories,
() -> inputDirectories,
() -> outputDirectories,
getToolchainDetection(),
execOperations,
getLogger()).execute(this);
execOperations).execute(this);
}
}
Expand Up @@ -43,16 +43,16 @@
import org.gradle.api.Action;
import org.gradle.api.Task;
import org.gradle.api.file.FileSystemOperations;
import org.gradle.api.provider.Provider;

import java.util.List;
import java.util.function.Supplier;

public class CleanupAgentFilesAction implements Action<Task> {

private final Provider<List<String>> directoriesToCleanup;
private final Supplier<List<String>> directoriesToCleanup;
private final FileSystemOperations fileOperations;

public CleanupAgentFilesAction(Provider<List<String>> directoriesToCleanup, FileSystemOperations fileOperations) {
public CleanupAgentFilesAction(Supplier<List<String>> directoriesToCleanup, FileSystemOperations fileOperations) {
this.directoriesToCleanup = directoriesToCleanup;
this.fileOperations = fileOperations;
}
Expand Down

0 comments on commit abbedfb

Please sign in to comment.