Skip to content

Commit abbedfb

Browse files
authored
Fix compatibility with configuration cache (#304)
* 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
1 parent 2638b04 commit abbedfb

File tree

9 files changed

+176
-43
lines changed

9 files changed

+176
-43
lines changed

native-gradle-plugin/src/functionalTest/groovy/org/graalvm/buildtools/gradle/JavaApplicationWithAgentFunctionalTest.groovy

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
package org.graalvm.buildtools.gradle
4343

4444
import org.graalvm.buildtools.gradle.fixtures.AbstractFunctionalTest
45-
import spock.lang.Issue
4645
import spock.lang.Unroll
4746

4847
class JavaApplicationWithAgentFunctionalTest extends AbstractFunctionalTest {
@@ -175,4 +174,39 @@ class JavaApplicationWithAgentFunctionalTest extends AbstractFunctionalTest {
175174
where:
176175
junitVersion = System.getProperty('versions.junit')
177176
}
177+
178+
@Unroll("plugin supports configuration cache (JUnit Platform #junitVersion)")
179+
def "supports configuration cache"() {
180+
debug = true
181+
var metadata_dir = 'src/main/resources/META-INF/native-image'
182+
given:
183+
withSample("java-application-with-reflection")
184+
185+
when:
186+
run 'run', '-Pagent', '--configuration-cache'
187+
188+
then:
189+
tasks {
190+
succeeded ':run'
191+
doesNotContain ':jar'
192+
}
193+
194+
and:
195+
['jni', 'proxy', 'reflect', 'resource', 'serialization'].each { name ->
196+
assert file("build/native/agent-output/run/${name}-config.json").exists()
197+
}
198+
199+
when:
200+
run'run', '-Pagent', '--configuration-cache', '--rerun-tasks'
201+
202+
then:
203+
tasks {
204+
succeeded ':run'
205+
doesNotContain ':jar'
206+
}
207+
outputContains "Reusing configuration cache"
208+
209+
where:
210+
junitVersion = System.getProperty('versions.junit')
211+
}
178212
}

native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/NativeImagePlugin.java

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@
5454
import org.graalvm.buildtools.gradle.internal.DefaultTestBinaryConfig;
5555
import org.graalvm.buildtools.gradle.internal.DeprecatedNativeImageOptions;
5656
import org.graalvm.buildtools.gradle.internal.GraalVMLogger;
57-
import org.graalvm.buildtools.gradle.internal.GradleUtils;
5857
import org.graalvm.buildtools.gradle.internal.GraalVMReachabilityMetadataService;
58+
import org.graalvm.buildtools.gradle.internal.GradleUtils;
5959
import org.graalvm.buildtools.gradle.internal.NativeConfigurations;
6060
import org.graalvm.buildtools.gradle.internal.agent.AgentConfigurationFactory;
6161
import org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask;
@@ -127,9 +127,13 @@
127127
import java.util.Objects;
128128
import java.util.Set;
129129
import java.util.function.Predicate;
130+
import java.util.function.Supplier;
130131
import java.util.regex.Pattern;
131132
import java.util.stream.Collectors;
132133

134+
import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializablePredicateOf;
135+
import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializableSupplierOf;
136+
import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializableTransformerOf;
133137
import static org.graalvm.buildtools.gradle.internal.GradleUtils.transitiveProjectArtifacts;
134138
import static org.graalvm.buildtools.gradle.internal.NativeImageExecutableLocator.graalvmHomeProvider;
135139
import static org.graalvm.buildtools.utils.SharedConstants.AGENT_PROPERTY;
@@ -199,7 +203,7 @@ public void apply(@Nonnull Project project) {
199203

200204
private void instrumentTasksWithAgent(Project project, DefaultGraalVmExtension graalExtension) {
201205
Provider<String> agentMode = agentProperty(project, graalExtension.getAgent());
202-
Predicate<? super Task> taskPredicate = graalExtension.getAgent().getTasksToInstrumentPredicate().get();
206+
Predicate<? super Task> taskPredicate = graalExtension.getAgent().getTasksToInstrumentPredicate().getOrElse(serializablePredicateOf(t -> true));
203207
project.getTasks().configureEach(t -> {
204208
if (isTaskInstrumentableByAgent(t) && taskPredicate.test(t)) {
205209
configureAgent(project, agentMode, graalExtension, getExecOperations(), getFileOperations(), t, (JavaForkOptions) t);
@@ -565,13 +569,13 @@ private static Provider<String> agentProperty(Project project, AgentOptions opti
565569
return project.getProviders()
566570
.gradleProperty(AGENT_PROPERTY)
567571
.forUseAtConfigurationTime()
568-
.map(v -> {
572+
.map(serializableTransformerOf(v -> {
569573
if (!v.isEmpty()) {
570574
return v;
571575
}
572576
return options.getDefaultMode().get();
573-
})
574-
.orElse(options.getEnabled().map(enabled -> enabled ? options.getDefaultMode().get() : "disabled"));
577+
}))
578+
.orElse(options.getEnabled().map(serializableTransformerOf(enabled -> enabled ? options.getDefaultMode().get() : "disabled")));
575579
}
576580

577581
private static void registerServiceProvider(Project project, Provider<NativeImageService> nativeImageServiceProvider) {
@@ -726,18 +730,18 @@ public void execute(@Nonnull Task task) {
726730
}
727731
});
728732
AgentCommandLineProvider cliProvider = project.getObjects().newInstance(AgentCommandLineProvider.class);
729-
cliProvider.getInputFiles().from(agentConfiguration.map(AgentConfiguration::getAgentFiles));
730-
cliProvider.getEnabled().set(agentConfiguration.map(AgentConfiguration::isEnabled));
733+
cliProvider.getInputFiles().from(agentConfiguration.map(serializableTransformerOf(AgentConfiguration::getAgentFiles)));
734+
cliProvider.getEnabled().set(agentConfiguration.map(serializableTransformerOf(AgentConfiguration::isEnabled)));
731735
cliProvider.getFilterableEntries().set(graalExtension.getAgent().getFilterableEntries());
732736
cliProvider.getAgentMode().set(agentMode);
733737

734738
Provider<Directory> outputDir = AgentConfigurationFactory.getAgentOutputDirectoryForTask(project.getLayout(), taskToInstrument.getName());
735-
Provider<Boolean> isMergingEnabled = agentConfiguration.map(AgentConfiguration::isEnabled);
736-
Provider<AgentMode> agentModeProvider = agentConfiguration.map(AgentConfiguration::getAgentMode);
737-
Provider<List<String>> mergeOutputDirs = outputDir.map(dir -> Collections.singletonList(dir.getAsFile().getAbsolutePath()));
738-
Provider<List<String>> mergeInputDirs = outputDir.map(NativeImagePlugin::agentSessionDirectories);
739+
Provider<Boolean> isMergingEnabled = agentConfiguration.map(serializableTransformerOf(AgentConfiguration::isEnabled));
740+
Provider<AgentMode> agentModeProvider = agentConfiguration.map(serializableTransformerOf(AgentConfiguration::getAgentMode));
741+
Supplier<List<String>> mergeInputDirs = serializableSupplierOf(() -> outputDir.map(serializableTransformerOf(NativeImagePlugin::agentSessionDirectories)).get());
742+
Supplier<List<String>> mergeOutputDirs = serializableSupplierOf(() -> outputDir.map(serializableTransformerOf(dir -> Collections.singletonList(dir.getAsFile().getAbsolutePath()))).get());
739743
cliProvider.getOutputDirectory().set(outputDir);
740-
cliProvider.getAgentOptions().set(agentConfiguration.map(AgentConfiguration::getAgentCommandLine));
744+
cliProvider.getAgentOptions().set(agentConfiguration.map(serializableTransformerOf(AgentConfiguration::getAgentCommandLine)));
741745
javaForkOptions.getJvmArgumentProviders().add(cliProvider);
742746

743747
taskToInstrument.doLast(new MergeAgentFilesAction(
@@ -749,8 +753,7 @@ public void execute(@Nonnull Task task) {
749753
mergeInputDirs,
750754
mergeOutputDirs,
751755
graalExtension.getToolchainDetection(),
752-
execOperations,
753-
project.getLogger()));
756+
execOperations));
754757

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

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* The Universal Permissive License (UPL), Version 1.0
6+
*
7+
* Subject to the condition set forth below, permission is hereby granted to any
8+
* person obtaining a copy of this software, associated documentation and/or
9+
* data (collectively the "Software"), free of charge and under any and all
10+
* copyright rights in the Software, and any and all patent rights owned or
11+
* freely licensable by each licensor hereunder covering either (i) the
12+
* unmodified Software as contributed to or provided by such licensor, or (ii)
13+
* the Larger Works (as defined below), to deal in both
14+
*
15+
* (a) the Software, and
16+
*
17+
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
18+
* one is included with the Software each a "Larger Work" to which the Software
19+
* is contributed by such licensors),
20+
*
21+
* without restriction, including without limitation the rights to copy, create
22+
* derivative works of, display, perform, and distribute the Software and make,
23+
* use, sell, offer for sale, import, export, have made, and have sold the
24+
* Software and the Larger Work(s), and to sublicense the foregoing rights on
25+
* either these or other terms.
26+
*
27+
* This license is subject to the following condition:
28+
*
29+
* The above copyright notice and either this complete permission notice or at a
30+
* minimum a reference to the UPL must be included in all copies or substantial
31+
* portions of the Software.
32+
*
33+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39+
* SOFTWARE.
40+
*/
41+
42+
package org.graalvm.buildtools.gradle.internal;
43+
44+
import org.gradle.api.Transformer;
45+
46+
import java.io.Serializable;
47+
import java.util.function.Predicate;
48+
import java.util.function.Supplier;
49+
50+
/**
51+
* Helper class to deal with Gradle configuration cache.
52+
*/
53+
public class ConfigurationCacheSupport {
54+
/**
55+
* Generates a serializable supplier lambda.
56+
* @param supplier the supplier
57+
* @return a serializable supplier
58+
* @param <T> the type of the supplier
59+
*/
60+
public static <T> Supplier<T> serializableSupplierOf(SerializableSupplier<T> supplier) {
61+
return supplier;
62+
}
63+
64+
/**
65+
* Generates a serializable predicate lambda.
66+
* @param predicate the predicate
67+
* @return a serializable predicate
68+
* @param <T> the type of the predicate
69+
*/
70+
public static <T> Predicate<T> serializablePredicateOf(SerializablePredicate<T> predicate) {
71+
return predicate;
72+
}
73+
74+
/**
75+
* Generates a serializable transformer lambda.
76+
* @param transformer the transformer
77+
* @return a serializable transformer
78+
* @param <OUT> the output type of the transformer
79+
* @param <IN> the input type of the transformer
80+
*/
81+
public static <OUT, IN> Transformer<OUT, IN> serializableTransformerOf(SerializableTransformer<OUT, IN> transformer) {
82+
return transformer;
83+
}
84+
85+
public interface SerializableSupplier<T> extends Supplier<T>, Serializable {
86+
87+
}
88+
89+
public interface SerializablePredicate<T> extends Predicate<T>, Serializable {
90+
91+
}
92+
93+
public interface SerializableTransformer<OUT, IN> extends Transformer<OUT, IN>, Serializable {
94+
95+
}
96+
97+
}

native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/internal/DefaultGraalVmExtension.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,9 @@
5959
import java.util.Arrays;
6060

6161
public abstract class DefaultGraalVmExtension implements GraalVMExtension {
62-
private final NamedDomainObjectContainer<NativeImageOptions> nativeImages;
63-
private final NativeImagePlugin plugin;
64-
private final Project project;
62+
private final transient NamedDomainObjectContainer<NativeImageOptions> nativeImages;
63+
private final transient NativeImagePlugin plugin;
64+
private final transient Project project;
6565
private final Property<JavaLauncher> defaultJavaLauncher;
6666

6767
@Inject
@@ -76,7 +76,6 @@ public DefaultGraalVmExtension(NamedDomainObjectContainer<NativeImageOptions> na
7676
nativeImages.configureEach(options -> options.getJavaLauncher().convention(defaultJavaLauncher));
7777
getTestSupport().convention(true);
7878
AgentOptions agentOpts = getAgent();
79-
agentOpts.getTasksToInstrumentPredicate().convention(t -> true);
8079
agentOpts.getDefaultMode().convention("standard");
8180
agentOpts.getEnabled().convention(false);
8281
agentOpts.getModes().getConditional().getParallel().convention(true);

native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/internal/agent/AgentConfigurationFactory.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,12 @@
5959
import java.util.Collections;
6060
import java.util.stream.Collectors;
6161

62+
import static org.graalvm.buildtools.gradle.internal.ConfigurationCacheSupport.serializableTransformerOf;
6263
import static org.graalvm.buildtools.utils.SharedConstants.AGENT_OUTPUT_FOLDER;
6364

6465
public class AgentConfigurationFactory {
6566
public static Provider<AgentConfiguration> getAgentConfiguration(Provider<String> modeName, AgentOptions options) {
66-
return modeName.map(name -> {
67+
return modeName.map(serializableTransformerOf(name -> {
6768
AgentMode agentMode;
6869
ConfigurableFileCollection callerFilterFiles = options.getCallerFilterFiles();
6970
ConfigurableFileCollection accessFilterFiles = options.getAccessFilterFiles();
@@ -95,7 +96,7 @@ public static Provider<AgentConfiguration> getAgentConfiguration(Provider<String
9596
options.getEnableExperimentalUnsafeAllocationTracing().get(),
9697
options.getTrackReflectionMetadata().get(),
9798
agentMode);
98-
});
99+
}));
99100
}
100101

101102
private static Collection<String> getFilePaths(ConfigurableFileCollection configurableFileCollection) {

native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/tasks/MetadataCopyTask.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
import java.io.File;
6363
import java.io.IOException;
6464
import java.nio.file.Files;
65+
import java.util.ArrayList;
6566
import java.util.List;
6667

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

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

131-
ListProperty<String> outputDirectories = objectFactory.listProperty(String.class);
132+
List<String> outputDirectories = new ArrayList<>();
132133
for (String dirName : getOutputDirectories().get()) {
133134
File dir = layout.dir(providerFactory.provider(() -> new File(dirName))).get().getAsFile();
134135
outputDirectories.add(dir.getAbsolutePath());
@@ -155,10 +156,9 @@ public void exec() {
155156
getMergeWithExisting(),
156157
objectFactory,
157158
graalvmHomeProvider(providerFactory),
158-
inputDirectories,
159-
outputDirectories,
159+
() -> inputDirectories,
160+
() -> outputDirectories,
160161
getToolchainDetection(),
161-
execOperations,
162-
getLogger()).execute(this);
162+
execOperations).execute(this);
163163
}
164164
}

native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/tasks/actions/CleanupAgentFilesAction.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,16 @@
4343
import org.gradle.api.Action;
4444
import org.gradle.api.Task;
4545
import org.gradle.api.file.FileSystemOperations;
46-
import org.gradle.api.provider.Provider;
4746

4847
import java.util.List;
48+
import java.util.function.Supplier;
4949

5050
public class CleanupAgentFilesAction implements Action<Task> {
5151

52-
private final Provider<List<String>> directoriesToCleanup;
52+
private final Supplier<List<String>> directoriesToCleanup;
5353
private final FileSystemOperations fileOperations;
5454

55-
public CleanupAgentFilesAction(Provider<List<String>> directoriesToCleanup, FileSystemOperations fileOperations) {
55+
public CleanupAgentFilesAction(Supplier<List<String>> directoriesToCleanup, FileSystemOperations fileOperations) {
5656
this.directoriesToCleanup = directoriesToCleanup;
5757
this.fileOperations = fileOperations;
5858
}

0 commit comments

Comments
 (0)