Skip to content

Commit b1463f1

Browse files
committed
Experimental support for layered images
This commit introduces a Gradle DSL to support layered images creation. As of now, this is mainly aimed towards a single use case which is incremental builds. The test project demonstrates how to use the DSL to create a base layer which includes the JDK "java.base" module as well as all external dependencies used by the project. The DSL builds on top of the binaries concept, by allowing them to declare either that they produce a layer, or that they use one or more layers. The DSL contains methods to make it easier to declare use or creation, as well as supports an easy way to declare that a layer should use only external dependencies. For example, this is how you would create a base layer and consume it from the main binary: ``` graalvmNative { binaries { libdependencies { createLayer { modules = ["java.base"] jars.from(externalDependenciesOf(configurations.runtimeClasspath)) } } main { useLayer("libdependencies") } } } ``` Note that there is a _binary_ named `libdependencies`, and as soon as the `createLayer` is called, it will offer additional options which are specific to layers (for example declaring the list of packages or modules). The DSL to create a layer contains the `packages` option, which could be used with automatic extraction of package names, which is why there is code to extract packages from jars, however, this code is currently unused for a reason: these packages can contain dependencies to "optional" modules, which cannot be figured out at build time. Typically, logback will support additional modules and load them dynamically, and if the package is included in the list and that the supporting dependencies are not on classpath, then the layer creation would fail. Therefore, the only reliable option right now is to use the `jars` property to set the list of jars which should belong to the layer.
1 parent ea84906 commit b1463f1

File tree

19 files changed

+1054
-225
lines changed

19 files changed

+1054
-225
lines changed

build-logic/common-plugins/src/main/kotlin/org.graalvm.build.java.gradle.kts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,16 @@ repositories {
6464
group = "org.graalvm.buildtools"
6565

6666
extensions.findByType<VersionCatalogsExtension>()?.also { catalogs ->
67-
val versionFromCatalog = catalogs.named("libs")
67+
if (catalogs.find("libs").isPresent) {
68+
val versionFromCatalog = catalogs.named("libs")
6869
.findVersion("nativeBuildTools")
69-
if (versionFromCatalog.isPresent()) {
70-
version = versionFromCatalog.get().requiredVersion
70+
if (versionFromCatalog.isPresent()) {
71+
version = versionFromCatalog.get().requiredVersion
72+
} else {
73+
throw GradleException("Version catalog doesn't define project version 'nativeBuildTools'")
74+
}
7175
} else {
72-
throw GradleException("Version catalog doesn't define project version 'nativeBuildTools'")
76+
version = "undefined"
7377
}
7478
}
7579

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* Copyright 2003-2021 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.graalvm.buildtools.utils;
17+
18+
import java.io.InputStream;
19+
import java.nio.file.Files;
20+
import java.nio.file.Path;
21+
import java.util.Arrays;
22+
import java.util.List;
23+
import java.util.Properties;
24+
25+
public class JarMetadata {
26+
private final List<String> packageList;
27+
28+
public JarMetadata(List<String> packageList) {
29+
this.packageList = packageList;
30+
}
31+
32+
public List<String> getPackageList() {
33+
return packageList;
34+
}
35+
36+
public static JarMetadata readFrom(Path propertiesFile) {
37+
Properties props = new Properties();
38+
try (InputStream is = Files.newInputStream(propertiesFile)) {
39+
props.load(is);
40+
} catch (Exception e) {
41+
throw new RuntimeException("Unable to read metadata from properties file " + propertiesFile, e);
42+
}
43+
String packages = (String) props.get("packages");
44+
List<String> packageList = packages == null ? List.of() : Arrays.asList(packages.split(","));
45+
return new JarMetadata(packageList);
46+
}
47+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* Copyright 2003-2021 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.graalvm.buildtools.utils;
17+
18+
import java.io.IOException;
19+
import java.io.PrintWriter;
20+
import java.io.Writer;
21+
import java.nio.file.FileSystem;
22+
import java.nio.file.FileSystems;
23+
import java.nio.file.Files;
24+
import java.nio.file.Path;
25+
import java.util.Set;
26+
import java.util.TreeSet;
27+
import java.util.stream.Stream;
28+
29+
/**
30+
* Performs scanning of a JAR file and extracts some metadata in the
31+
* form of a properties file. For now this type only extracts the list
32+
* of packages from a jar.
33+
*/
34+
public class JarScanner {
35+
/**
36+
* Scans a jar and creates a properties file with metadata about the jar contents.
37+
* @param inputJar the input jar
38+
* @param outputFile the output file
39+
* @throws IOException
40+
*/
41+
public static void scanJar(Path inputJar, Path outputFile) throws IOException {
42+
try (Writer fileWriter = Files.newBufferedWriter(outputFile); PrintWriter writer = new PrintWriter(fileWriter)) {
43+
Set<String> packageList = new TreeSet<>();
44+
try (FileSystem jarFileSystem = FileSystems.newFileSystem(inputJar, null)) {
45+
Path root = jarFileSystem.getPath("/");
46+
try (Stream<Path> files = Files.walk(root)) {
47+
files.forEach(path -> {
48+
if (path.toString().endsWith(".class") && !path.toString().contains("META-INF")) {
49+
Path relativePath = root.relativize(path);
50+
String className = relativePath.toString()
51+
.replace('/', '.')
52+
.replace('\\', '.')
53+
.replaceAll("[.]class$", "");
54+
var lastDot = className.lastIndexOf(".");
55+
if (lastDot > 0) {
56+
var packageName = className.substring(0, lastDot);
57+
packageList.add(packageName);
58+
}
59+
}
60+
});
61+
}
62+
}
63+
writer.println("packages=" + String.join(",", packageList));
64+
} catch (IOException ex) {
65+
throw new RuntimeException("Unable to write JAR analysis", ex);
66+
}
67+
}
68+
}

docs/src/docs/asciidoc/changelog.adoc

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
[[changelog]]
22
== Changelog
33

4+
== Release 0.10.7
5+
6+
=== Gradle plugin
7+
8+
- Added experimental support for layered images
9+
410
== Release 0.10.6
511

612
=== Gradle plugin
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
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
43+
44+
import org.graalvm.buildtools.gradle.fixtures.AbstractFunctionalTest
45+
import org.graalvm.buildtools.gradle.fixtures.GraalVMSupport
46+
import org.graalvm.buildtools.utils.NativeImageUtils
47+
import spock.lang.Requires
48+
49+
@Requires(
50+
{ NativeImageUtils.getMajorJDKVersion(GraalVMSupport.getGraalVMHomeVersionString()) >= 25 }
51+
)
52+
class LayeredApplicationFunctionalTest extends AbstractFunctionalTest {
53+
def "can build a native image using layers"() {
54+
def nativeApp = getExecutableFile("build/native/nativeCompile/layered-java-application")
55+
56+
given:
57+
withSample("layered-java-application")
58+
59+
when:
60+
run 'nativeLibdependenciesCompile'
61+
62+
then:
63+
tasks {
64+
succeeded ':nativeLibdependenciesCompile'
65+
}
66+
outputContains "'-H:LayerCreate' (origin(s): command line)"
67+
68+
when:
69+
run 'nativeRun', '-Pmessage="Hello, layered images!"'
70+
71+
then:
72+
tasks {
73+
upToDate ':nativeLibdependenciesCompile'
74+
succeeded ':nativeCompile'
75+
}
76+
nativeApp.exists()
77+
78+
and:
79+
outputContains "- '-H:LayerUse' (origin(s): command line)"
80+
outputContains "Hello, layered images!"
81+
82+
when: "Updating the application without changing the dependencies"
83+
file("src/main/java/org/graalvm/demo/Application.java").text = """
84+
package org.graalvm.demo;
85+
86+
import org.slf4j.Logger;
87+
import org.slf4j.LoggerFactory;
88+
89+
public class Application {
90+
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
91+
92+
public static void main(String[] args) {
93+
LOGGER.info("App started with args {}", String.join(", ", args));
94+
}
95+
96+
}
97+
98+
"""
99+
run 'nativeRun', '-Pmessage="Hello, layered images!"'
100+
101+
then:
102+
tasks {
103+
// Base layer is not rebuilt
104+
upToDate ':nativeLibdependenciesCompile'
105+
// Application layer is recompiled
106+
succeeded ':nativeCompile'
107+
}
108+
109+
outputContains "- '-H:LayerUse' (origin(s): command line)"
110+
outputContains "Hello, layered images!"
111+
}
112+
}

0 commit comments

Comments
 (0)