Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework maven code for faster calculation of path config #1661

Merged
merged 21 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
1fc579d
Added fast path to avoid starting maven just to install dependencies
DavyLandman Oct 3, 2022
0e8b61a
Rewrote to using internal maven engine instead of forking jvm
DavyLandman Oct 4, 2022
f574853
Rewrote to calling maven without changing global properties (but sadl…
DavyLandman Oct 4, 2022
fb3c978
Merge branch 'main' into reduce-maven-overhead
rodinaarssen Jul 22, 2024
6dc6715
Fixed path normalization for embedded maven
rodinaarssen Jul 22, 2024
a2ce678
Updated maven library version
rodinaarssen Jul 22, 2024
df9a698
Added another necessary dependency for maven-embedder
rodinaarssen Jul 30, 2024
d5cff33
Configured maven-shade-plugin to correctly shade required files for d…
rodinaarssen Aug 20, 2024
0bcadda
Fixed regular expression to obtain the classpath from Maven's output
rodinaarssen Aug 20, 2024
cb9851d
Layout
rodinaarssen Aug 20, 2024
c9fc81e
Merge branch 'main' into reduce-maven-overhead
rodinaarssen Aug 20, 2024
d5c655b
No longer manipulating System.out and System.err streams, instead wri…
rodinaarssen Aug 20, 2024
2aab716
Correctly extracting class path from maven output
rodinaarssen Aug 27, 2024
d374969
Merge branch 'main' into reduce-maven-overhead
rodinaarssen Aug 27, 2024
90271d3
Changed slf4j dependency to suppress maven output to the REPL
rodinaarssen Sep 10, 2024
0529f26
Removed now-redundant constant
rodinaarssen Sep 10, 2024
d30a696
Created separate class for Maven interaction
rodinaarssen Sep 11, 2024
d181d88
Fully qualified dependency plugin; removed quiet argument from maven …
rodinaarssen Sep 17, 2024
badd6e0
Make sure that maven-dependency-plugin is downloaded when not yet pre…
rodinaarssen Sep 17, 2024
dd327ad
Merge branch 'main' into reduce-maven-overhead
rodinaarssen Nov 25, 2024
c82fbc9
Added missing license header
rodinaarssen Nov 25, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<lucence-version>7.5.0</lucence-version>
<maven-version>3.9.8</maven-version>
<exec.mainClass>org.rascalmpl.shell.RascalShell</exec.mainClass>
<rascal.test.memory>2</rascal.test.memory>
<maven.compiler.release>11</maven.compiler.release>
Expand Down Expand Up @@ -317,9 +318,10 @@
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>org/rascalmpl/uri/resolvers.config</resource>
<resource>io/usethesource/vallang/type/types.config </resource>
<resource>META-INF/sisu/javax.inject.Named</resource> <!-- Needed for dependency injection in MavenCli -->
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer">
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer"/> <!-- Needed for dependency injection in MavenCli -->
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheLicenseResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ApacheNoticeResourceTransformer">
<addHeader>false</addHeader>
</transformer>
Expand Down Expand Up @@ -514,5 +516,30 @@
<artifactId>icu4j</artifactId>
<version>74.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-embedder</artifactId>
<version>${maven-version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.7.1</version>
</dependency>
<dependency> <!-- needed for maven-embedder-->
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.36</version>
</dependency>
<dependency> <!-- needed for maven-embedder-->
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>${maven-version}</version>
</dependency>
<dependency> <!-- needed for maven-embedder-->
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>${maven-version}</version>
</dependency>
</dependencies>
</project>
96 changes: 96 additions & 0 deletions src/org/rascalmpl/library/util/Maven.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* Copyright (c) 2024, Rodin Aarssen, Swat.engineering
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.rascalmpl.library.util;
rodinaarssen marked this conversation as resolved.
Show resolved Hide resolved

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;

import org.apache.maven.cli.CliRequest;
import org.apache.maven.cli.MavenCli;
import org.codehaus.plexus.classworlds.ClassWorld;
import org.rascalmpl.uri.URIResolverRegistry;
import org.rascalmpl.uri.URIUtil;

import io.usethesource.vallang.ISourceLocation;

public class Maven {

Check warning on line 30 in src/org/rascalmpl/library/util/Maven.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/Maven.java#L30

Added line #L30 was not covered by tests
/**
* Calls maven with the provided arguments. The working directory will be set to `manifestRoot`,
* which should contain a `pom.xml` file. If `outputFile` refers to an existing file, its contents
* will the read and returned after Maven concludes.
*
* Maven's output is fully suppressed. However, it is often possible to redirect (parts of) the output
* to a file. For instance, the output of `mvn dependency:build-classpath` can be redicted to a file
* by providing an additional argument `-Dmdep.outputFile=/path/to/file`.
*/
public static List<String> runCommand(List<String> args, ISourceLocation manifestRoot, Path outputFile) {
try {
ISourceLocation pomxml = URIUtil.getChildLocation(manifestRoot, "pom.xml");
pomxml = URIResolverRegistry.getInstance().logicalToPhysical(pomxml);
manifestRoot = URIResolverRegistry.getInstance().logicalToPhysical(manifestRoot);

if (!"file".equals(manifestRoot.getScheme())) {
throw new IllegalArgumentException("`manifestRoot` could not be resolved");
}

if (!URIResolverRegistry.getInstance().exists(pomxml)) {
throw new IllegalArgumentException("`manifestRoot` does not contain pom.xml");

Check warning on line 51 in src/org/rascalmpl/library/util/Maven.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/Maven.java#L51

Added line #L51 was not covered by tests
}

var maven = new MavenCli();
maven.doMain(buildRequest(args.toArray(String[]::new), manifestRoot));

if (outputFile != null && Files.exists(outputFile)) {
return Files.readAllLines(outputFile);
}
} catch (IOException | ReflectiveOperationException e) {

Check warning on line 60 in src/org/rascalmpl/library/util/Maven.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/Maven.java#L60

Added line #L60 was not covered by tests
// Fall through to return the empty list
}

return Collections.emptyList();
}

/**
* Calls maven with the provided arguments. The working directory will be set to `manifestRoot`,
* which should contain a `pom.xml` file. Maven's output is fully suppressed.
*/
public static void runCommand(List<String> args, ISourceLocation manifestRoot) {
runCommand(args, manifestRoot, null);
}

private static void setField(CliRequest req, String fieldName, Object value) throws ReflectiveOperationException {
var field = CliRequest.class.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(req, value);
}

private static CliRequest buildRequest(String[] args, ISourceLocation manifestRoot) throws ReflectiveOperationException {
// we need to set a field that the default class doesn't set
// it's a work around around a bug in the MavenCli code
var cons = CliRequest.class.getDeclaredConstructor(String[].class, ClassWorld.class);
cons.setAccessible(true);
var result = cons.newInstance(args, null);
var manifestRootFile = new File(manifestRoot.getPath());
setField(result, "workingDirectory", manifestRootFile.getPath());
setField(result, "multiModuleProjectDirectory", manifestRootFile);
return result;
}

public static Path getTempFile(String kind) throws IOException {
return Files.createTempFile("rascal-maven-" + kind + "-", ".tmp");
}
}
113 changes: 23 additions & 90 deletions src/org/rascalmpl/library/util/PathConfig.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package org.rascalmpl.library.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URISyntaxException;
Expand All @@ -14,6 +12,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.rascalmpl.interpreter.Configuration;
Expand Down Expand Up @@ -62,8 +61,6 @@
private static List<ISourceLocation> defaultClassloaders;
private static ISourceLocation defaultBin;

private static final String WINDOWS_ROOT_TRUSTSTORE_TYPE_DEFINITION = "-Djavax.net.ssl.trustStoreType=WINDOWS-ROOT";

public static enum RascalConfigMode {
INTERPETER,
COMPILER
Expand Down Expand Up @@ -638,97 +635,33 @@
*/
private static IList getPomXmlCompilerClasspath(ISourceLocation manifestRoot) {
try {
ISourceLocation pomxml = URIUtil.getChildLocation(manifestRoot, "pom.xml");
pomxml = URIResolverRegistry.getInstance().logicalToPhysical(pomxml);
manifestRoot = URIResolverRegistry.getInstance().logicalToPhysical(manifestRoot);

if (!"file".equals(manifestRoot.getScheme())) {
return vf.list();
}

if (!URIResolverRegistry.getInstance().exists(pomxml)) {
return vf.list();
}

String mvnCommand = computeMavenCommandName();

installNecessaryMavenPlugins(mvnCommand);

// Note how we try to do this "offline" using the "-o" flag
ProcessBuilder processBuilder = new ProcessBuilder(mvnCommand,
"--batch-mode",
"-o",
"dependency:build-classpath",
"-DincludeScope=compile",
trustStoreFix()
);

processBuilder.directory(new File(manifestRoot.getPath()));
processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home", System.getenv("JAVA_HOME")));

Process process = processBuilder.start();

try (BufferedReader processOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
return processOutputReader.lines()
.filter(line -> !line.startsWith("["))
.filter(line -> !line.contains("-----"))
.flatMap(line -> Arrays.stream(line.split(File.pathSeparator)))
.filter(fileName -> new File(fileName).exists())
.map(elem -> {
try {
return URIUtil.createFileLocation(elem);
}
catch (URISyntaxException e) {
return null;
}
})
.filter(e -> e != null)
.collect(vf.listWriter());
}
String mavenDependencyPlugin = "org.apache.maven.plugins:maven-dependency-plugin:3.8.0";
// First, make sure that maven-dependency-plugin is downloaded when not available
Maven.runCommand(List.of(mavenDependencyPlugin + ":do-nothing"), manifestRoot);

// Now, actually let maven build the classpath. Note that this is in offline mode as to not download any dependencies
var tempFile = Maven.getTempFile("classpath");
var mavenOutput = Maven.runCommand(List.of("-o", mavenDependencyPlugin + ":build-classpath", "-DincludeScope=compile", "-Dmdep.outputFile=" + tempFile.toString()), manifestRoot, tempFile);

// The classpath will be written to the temp file on a single line
return Arrays.stream(mavenOutput.get(0).split(File.pathSeparator))
.filter(fileName -> new File(fileName).exists())
.map(elem -> {

Check warning on line 649 in src/org/rascalmpl/library/util/PathConfig.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/PathConfig.java#L647-L649

Added lines #L647 - L649 were not covered by tests
try {
return URIUtil.createFileLocation(elem);

Check warning on line 651 in src/org/rascalmpl/library/util/PathConfig.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/PathConfig.java#L651

Added line #L651 was not covered by tests
}
catch (URISyntaxException e) {
return null;

Check warning on line 654 in src/org/rascalmpl/library/util/PathConfig.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/PathConfig.java#L653-L654

Added lines #L653 - L654 were not covered by tests
}
})
.filter(Objects::nonNull)
.collect(vf.listWriter());

Check warning on line 658 in src/org/rascalmpl/library/util/PathConfig.java

View check run for this annotation

Codecov / codecov/patch

src/org/rascalmpl/library/util/PathConfig.java#L657-L658

Added lines #L657 - L658 were not covered by tests
}
catch (IOException e) {
catch (IOException | RuntimeException e) {
return vf.list();
}
}

private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("win");
}

private static String computeMavenCommandName() {
if (System.getProperty("os.name", "generic").startsWith("Windows")) {
return "mvn.cmd";
}
else {
return "mvn";
}
}

private static void installNecessaryMavenPlugins(String mvnCommand) {
try {
ProcessBuilder processBuilder = new ProcessBuilder(mvnCommand,
"-q",
"dependency:get",
"-DgroupId=org.apache.maven.plugins",
"-DartifactId=maven-dependency-plugin",
"-Dversion=2.8",
trustStoreFix());
processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home", System.getenv("JAVA_HOME")));

Process process = processBuilder.start();
if (process.waitFor() != 0) {
throw new IOException("mvn dependency:get returned non-zero");
}
}
catch (IOException | InterruptedException e) {
System.err.println("[WARNING] Could not install exec-maven-plugin; classpath resolution may be incomplete hereafter: " + e.getMessage());
}
}

private static String trustStoreFix() {
return isWindows() ? WINDOWS_ROOT_TRUSTSTORE_TYPE_DEFINITION : "-Dnothing_to_see_here";
}

public ISourceLocation getBin() {
return bin;
}
Expand Down
Loading