Skip to content

Commit

Permalink
Merge pull request #1661 from usethesource/reduce-maven-overhead
Browse files Browse the repository at this point in the history
Rework maven code for faster calculation of path config
  • Loading branch information
rodinaarssen authored Nov 26, 2024
2 parents 65610af + c82fbc9 commit b2a3042
Show file tree
Hide file tree
Showing 3 changed files with 148 additions and 92 deletions.
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;

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 {
/**
* 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");
}

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) {
// 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 @@ public class PathConfig {
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 ISourceLocation setTargetScheme(ISourceLocation projectLoc) {
*/
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 -> {
try {
return URIUtil.createFileLocation(elem);
}
catch (URISyntaxException e) {
return null;
}
})
.filter(Objects::nonNull)
.collect(vf.listWriter());
}
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

0 comments on commit b2a3042

Please sign in to comment.