-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbuild.gradle
261 lines (219 loc) · 11.7 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2020-2024 CROZ d.o.o, the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.apache.tools.ant.filters.ReplaceTokens
import org.gradle.internal.deprecation.DeprecatableConfiguration
plugins {
id "klokwrk-gradle-plugin-convention-base"
id "klokwrk-gradle-plugin-convention-groovy"
id "klokwrk-gradle-plugin-convention-micronaut-app-minimal"
}
config {
coverage {
jacoco {
setExcludes(["org/klokwrk/tool/gradle/source/repack/graal/**"] as Set<String>)
}
}
}
micronaut {
testRuntime("spock2")
processing {
incremental(true)
annotations("org.klokwrk.tool.gradle.source.repack.*")
}
}
application {
mainClass.set("org.klokwrk.tool.gradle.source.repack.GradleSourceRepackCommand")
}
// Processes resources/version.properties and replaces tokens with provided values.
processResources {
filteringCharset = "UTF-8"
filter(ReplaceTokens, tokens: [moduleName: project.name, moduleVersion: project.version])
}
configurations {
graalNativeImageDependencies
groovydocMicronautClasspath
}
groovydoc {
groovyClasspath = project.configurations.groovydocMicronautClasspath
}
dependencies {
graalNativeImageDependencies platform(project(":klokwrk-platform-micronaut"))
groovydocMicronautClasspath platform(project(":klokwrk-platform-micronaut"))
implementation platform(project(":klokwrk-platform-micronaut"))
graalNativeImageDependencies "io.github.classgraph:classgraph"
groovydocMicronautClasspath "com.github.javaparser:javaparser-core"
groovydocMicronautClasspath "org.apache.groovy:groovy"
groovydocMicronautClasspath "org.apache.groovy:groovy-ant"
groovydocMicronautClasspath "org.apache.groovy:groovy-templates"
compileOnly "info.picocli:picocli-codegen"
compileOnly "io.github.classgraph:classgraph"
compileOnly "org.graalvm.nativeimage:svm"
implementation "info.picocli:picocli"
implementation "io.micronaut:micronaut-core"
implementation "io.micronaut:micronaut-http-client-core"
implementation "io.micronaut:micronaut-jackson-databind"
implementation "io.micronaut.picocli:micronaut-picocli"
implementation "io.micronaut.reactor:micronaut-reactor-http-client"
implementation "jakarta.inject:jakarta.inject-api"
implementation "org.apache.groovy:groovy"
implementation "org.slf4j:slf4j-api"
testImplementation "ch.qos.logback:logback-classic"
testImplementation "org.wiremock:wiremock"
testImplementation "com.google.jimfs:jimfs"
testImplementation "org.spockframework:spock-core"
testRuntimeOnly "net.bytebuddy:byte-buddy"
testRuntimeOnly "org.objenesis:objenesis"
runtimeOnly "ch.qos.logback:logback-classic"
}
Boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows")
}
// Simple custom graal image builder task used because of some bugs/missing features in Micronaut task.
// Can be replaced by the Micronaut's one when at least the first of the following bugs is fixed:
// - https://github.com/micronaut-projects/micronaut-gradle-plugin/issues/92
// - https://github.com/micronaut-projects/micronaut-gradle-plugin/issues/93
//
// In addition there is also an issue with missing resources in Micronaut task that causes native image build failing in the presence of both java and groovy source sets. Didn't reported that yet,
// but I guess it will not get much attention since native image for Groovy is not supported.
tasks.register("kwrkNativeImage", Exec) { Exec thisExecTask ->
def project = thisExecTask.getProject()
def shadowJar = project.tasks.named("shadowJar", ShadowJar).get()
thisExecTask.dependsOn shadowJar
String nativeImageBuilderClasspath = null
project.configurations { ConfigurationContainer configurationContainer ->
Set<Configuration> filteredConfigurations = configurationContainer
.findAll({ Configuration configuration ->
if (configuration instanceof DeprecatableConfiguration) {
DeprecatableConfiguration deprecatableConfiguration = (DeprecatableConfiguration) configuration
if (deprecatableConfiguration.resolutionAlternatives != null) {
return false
}
}
return true
})
.findAll { Configuration configuration ->
return configuration.canBeResolved
}
.findAll({ Configuration configuration ->
return ["graalNativeImageDependencies"].contains(configuration.name)
})
Set<File> resolvedDependencies = filteredConfigurations.collectMany { Configuration configuration -> configuration.resolve() }
nativeImageBuilderClasspath = project.files(resolvedDependencies, shadowJar.archiveFile).asPath
return
}
File workingDir = new File(project.layout.buildDirectory.get().asFile, "native-image")
workingDir.mkdirs()
JavaApplication javaApplication = project.extensions.getByType(JavaApplication)
String mainClass = javaApplication.getMainClass().get()
File mainGraalSourceSetDir = new File(project.projectDir, "src/main/graal")
String executable = isWindows() ? "native-image.cmd" : "native-image"
thisExecTask.setExecutable(executable)
thisExecTask.setWorkingDir(workingDir)
thisExecTask.setArgs([
// Enables verbose output that display full configuration used for creating a native image.
"--verbose",
// A separated list of directories, JAR archives, and ZIP archives to search for class files.
"--class-path=$nativeImageBuilderClasspath",
// Report usage of unsupported methods and fields at runtime when they are accessed the first time, instead of as an error during image building.
//
// Necessary for compiling Groovy apps since Groovy core, even when statically compiled, still exposes many code paths used only with dynamic Groovy. Even if they are not used with statically
// compiled Groovy, they are still reachable by GraalVM native image analysis. In some cases GraalVM native image compiler cannot reduce those multiple code paths to a single method call which
// results with GraalVM UnsupportedFeatureException during native image compilation.
"--report-unsupported-elements-at-runtime",
"--features=".concat(String.join(",", [
"org.klokwrk.tool.gradle.source.repack.graal.GroovyDgmClassesRegistrationFeature",
"org.klokwrk.tool.gradle.source.repack.graal.GroovyApplicationRegistrationFeature",
])),
// A comma-separated list of packages and classes (and implicitly all of their superclasses) that are initialized during image generation. An empty string designates all packages.
// As of Graal 21.2, this list should not be empty (https://www.graalvm.org/release-notes/21_2/#native-image)
"--initialize-at-build-time=".concat(String.join(",", [
"com.sun.beans",
"groovy.lang",
"groovyjarjarantlr4.v4",
"java.beans",
"org.apache.groovy",
"org.codehaus.groovy",
"ch.qos.logback",
"org.slf4j"
])),
// A comma-separated list of packages and classes (and implicitly all of their subclasses) that must be initialized at runtime and not during image building. An empty string is currently not
// supported.
"--initialize-at-run-time=".concat(String.join(",", [
"org.codehaus.groovy.control.XStreamUtils",
"org.codehaus.groovy.vmplugin.v8.Java8\$LookupHolder",
"groovy.grape.GrapeIvy",
"io.netty.handler.ssl.BouncyCastleAlpnSslUtils",
"io.netty.handler.ssl.JdkSslServerContext"
])),
// Do not fallback on plain JVM when AOT native image compilation fails. Throw an error instead.
"--no-fallback",
"-H:+UnlockExperimentalVMOptions",
// Comma separated list of directories containing GraalVM native image builder configuration files that are not part of the classpath. This directory may contain all four files configuration
// files: jni-config.json, reflect-config.json, proxy-config.json and resource-config.json.
"-H:ConfigurationFileDirectories=${ mainGraalSourceSetDir.absolutePath }",
// // Enables creation of detailed reports about GraalVM code analysis.
// "-H:+PrintAnalysisCallTree",
//
// // Enables creation of detailed report about objects included in the native image heap.
// "-H:+PrintImageObjectTree",
//
// // Defines the path for GraalVM Dashboard (https://www.graalvm.org/docs/tools/dashboard/) dump file
// "-H:DashboardDump=${ workingDir.absolutePath }/dashboard-dump",
//
// // Three options bellow dump all available data in GraalVM Dashboard dump file.
//// "-H:+DashboardHeap", // This one causes error at the moment in my environment. If this is also your case, comment it out.
// "-H:+DashboardCode",
// "-H:+DashboardPointsTo",
// Print stacktrace of underlying exceptions.
"-H:+ReportExceptionStackTraces",
// Included locales (comma separated list)
"-H:IncludeLocales=en",
// Configure default language and locale
"-J-Duser.language=en",
// The directory where the generated executable is placed.
"-H:Path=${ workingDir.absolutePath }",
// The class containing the default entry point method.
"-H:Class=${ mainClass }",
// The name of the executable file that is generated.
"-H:Name=${ project.name }",
// Configure max heap
"-J-Xmx10g",
// I'm not entirely sure about the exact cause of the problem the Groovy has when executing as a native image built with GraalVM, so I will try to describe the issue according to my current
// understanding.
//
// In the native image built with GraalVM, when executing some methods repeatedly for a huge number of times (more than 10000), Groovy can cause the following exception:
//
// com.oracle.svm.core.jdk.UnsupportedFeatureError: Unsupported method java.lang.invoke.MethodHandleNatives.setCallSiteTargetNormal(CallSite, MethodHandle) is reachable
//
// The exception is caused by
//
// org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(IndyInterface.java:315)
//
// method. When looking at the source, the corresponding "if" branch is triggered, besides other things, because "INDY_OPTIMIZE_THRESHOLD" is exceeded. After looking at the definition of the
// constant, it is visible that it is read from the "groovy.indy.optimize.threshold" system property and has a default of 10_000. Unfortunately, that system property cannot be just passed to
// the native executable but rather must be set during native image building to become effective.
//
// Along with "groovy.indy.optimize.threshold," there is also a related "groovy.indy.fallback.threshold" system property (relation was concluded from inspecting the source, the values of
// properties, and the fact they were changed at the same time in the past). Therefore, we are changing both properties by setting them to 100_000, which is substantially larger than the
// default value of 10_000. After those changes, the created native image no longer throws the above mentioned exception.
//
"-J-Dgroovy.indy.optimize.threshold=100000",
"-J-Dgroovy.indy.fallback.threshold=100000"
])
}