Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
Gradle 8.11
  • Loading branch information
altro3 committed Nov 17, 2024
1 parent b9874a5 commit 75419e6
Show file tree
Hide file tree
Showing 32 changed files with 156 additions and 241 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ public final void execute() throws IOException {
FileCollection classpath = getOptimizerClasspath().plus(getClasspath());
spec.setClasspath(aotClasspath);
spec.getMainClass().set("io.micronaut.aot.cli.Main");
List<String> args = new ArrayList<>(Arrays.asList(
"--classpath", classpath.getAsPath(),
"--runtime", getTargetRuntime().get().name().toUpperCase(),
"--package", getTargetPackage().get()
var args = new ArrayList<>(Arrays.asList(
"--classpath", classpath.getAsPath(),
"--runtime", getTargetRuntime().get().name().toUpperCase(),
"--package", getTargetPackage().get()
));
maybeAddOptimizerClasspath(args, getClasspath());
configureExtraArguments(args);
boolean useArgFile = true;
try (PrintWriter wrt = new PrintWriter(new FileWriter(argFile))) {
try (var wrt = new PrintWriter(new FileWriter(argFile))) {
args.forEach(arg -> wrt.println(escapeArg(arg)));
} catch (IOException e) {
useArgFile = false;
Expand All @@ -107,7 +107,7 @@ public final void execute() throws IOException {
spec.args(args);
}
getLogger().info("Running AOT optimizer {} with parameters: {}", useArgFile ? "using arg file" : "directly", args);
List<String> jvmArgs = new ArrayList<>();
var jvmArgs = new ArrayList<String>();
if (Boolean.TRUE.equals(getDebug().get())) {
getLogger().info("Running with debug enabled");
jvmArgs.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ static void registerShadowJar(Project project,
Jar mainJar = tasks.named("jar", Jar.class).get();
shadow.getManifest().inheritFrom(mainJar.getManifest());
if (javaApplication != null) {
// This is the reason why we use an afterEvalute:
// This is the reason why we use an afterEvaluate:
// The shadow plugin apparently does something with attributes,
// breaking support for providers
shadow.getManifest().getAttributes().put("Main-Class", javaApplication.getMainClass().get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ public void execute() {
for (Map.Entry<String, List<File>> entry : perService.entrySet()) {
String serviceType = entry.getKey();
List<File> files = entry.getValue();
File mergedServiceFile = new File(outputDir, serviceType);
try (PrintWriter wrt = new PrintWriter(new OutputStreamWriter(new FileOutputStream(mergedServiceFile), StandardCharsets.UTF_8))) {
var mergedServiceFile = new File(outputDir, serviceType);
try (var wrt = new PrintWriter(new OutputStreamWriter(new FileOutputStream(mergedServiceFile), StandardCharsets.UTF_8))) {
for (File file : files) {
Files.readAllLines(file.toPath()).forEach(wrt::println);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ private static void stringParameter(Properties props, String parameter, Property

@TaskAction
void writeConfigFile() {
Properties props = new Properties();
var props = new Properties();
if (getUserConfiguration().isPresent()) {
try (InputStream in = new FileInputStream(getUserConfiguration().getAsFile().get())) {
try (var in = new FileInputStream(getUserConfiguration().getAsFile().get())) {
props.load(in);
} catch (IOException e) {
throw new GradleException("Unable to parse configuration file", e);
Expand Down Expand Up @@ -152,12 +152,7 @@ void writeConfigFile() {
String content = baos.toString();
try (var writer = new PrintWriter(Files.newBufferedWriter(outputFile.toPath()))) {
content.lines()
.filter(line -> {
if (line.startsWith("#") && !line.contains(GENERATED_BY_GRADLE_COMMENT)) {
return false;
}
return true;
})
.filter(line -> !line.startsWith("#") || line.contains(GENERATED_BY_GRADLE_COMMENT))
.forEach(writer::println);
} catch (IOException e) {
throw new GradleException("Unable to write output file: " + outputFile, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.application.CreateStartScripts;
import org.gradle.api.tasks.bundling.Jar;
import org.jetbrains.annotations.NotNull;

import javax.inject.Inject;
import java.io.File;
Expand All @@ -71,7 +72,6 @@
import static org.codehaus.groovy.runtime.StringGroovyMethods.capitalize;
import static org.gradle.api.plugins.JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME;

@SuppressWarnings("Convert2Lambda")
public abstract class MicronautAotPlugin implements Plugin<Project> {

public static final String DEFAULT_AOT_VERSION = Versions.AOT_VERSION;
Expand Down Expand Up @@ -214,7 +214,7 @@ private void registerDockerImage(Project project, TaskProvider<Jar> optimizedJar
Attributes attrs = manifest.getAttributes();
attrs.put("Main-Class", javaApplication.getMainClass());
attrs.put("Class-Path", project.getProviders().provider(() -> {
List<String> classpath = new ArrayList<>();
var classpath = new ArrayList<String>();
Configuration runtimeClasspath = project.getConfigurations()
.getByName(RUNTIME_CLASSPATH_CONFIGURATION_NAME);

Expand Down Expand Up @@ -316,18 +316,15 @@ private void registerJavaExecOptimizedRun(Project project,
// https://github.com/micronaut-projects/micronaut-gradle-plugin/issues/385
task.getOutputs().upToDateWhen(t -> false);
task.setClasspath(project.files(jarTask, optimizedRuntimeClasspath));
task.doFirst(new Action<>() {
@Override
public void execute(Task t) {
if (task.getLogger().isDebugEnabled()) {
task.getLogger().debug(
"Running optimized entry point: {}\nClasspath:\n {}",
task.getMainClass().get(), task.getClasspath().getFiles()
.stream()
.map(File::getName)
.collect(Collectors.joining("\n "))
);
}
task.doFirst(t -> {
if (task.getLogger().isDebugEnabled()) {
task.getLogger().debug(
"Running optimized entry point: {}\nClasspath:\n {}",
task.getMainClass().get(), task.getClasspath().getFiles()
.stream()
.map(File::getName)
.collect(Collectors.joining("\n "))
);
}
});
});
Expand Down Expand Up @@ -419,7 +416,7 @@ private JarExclusionSpec(Provider<RegularFile> filterFile,
}

@Override
public void execute(FileCopyDetails details) {
public void execute(@NotNull FileCopyDetails details) {
if (excludes == null) {
File resourceFilter = filterFile.get().getAsFile();
try {
Expand All @@ -444,15 +441,10 @@ private static String normalizePath(String path) {
}
}

private static final class Configurations {
private final Configuration aotOptimizerRuntimeClasspath;
private final Configuration aotApplication;
private final Configuration aotApplicationClasspath;

private Configurations(Configuration aotOptimizerRuntimeClasspath, Configuration aotApplication, Configuration aotApplicationClasspath) {
this.aotOptimizerRuntimeClasspath = aotOptimizerRuntimeClasspath;
this.aotApplication = aotApplication;
this.aotApplicationClasspath = aotApplicationClasspath;
}
private record Configurations(
Configuration aotOptimizerRuntimeClasspath,
Configuration aotApplication,
Configuration aotApplicationClasspath
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected void configureExtraArguments(List<String> args) {

@Override
protected void onSuccess(File outputDir) {
File sampleFile = new File(outputDir, getTargetRuntime().map(runtime -> runtime.getSimpleName() + ".properties").orElse("sample.properties").get());
var sampleFile = new File(outputDir, getTargetRuntime().map(runtime -> runtime.getSimpleName() + ".properties").orElse("sample.properties").get());
if (sampleFile.exists()) {
getLogger().lifecycle("Sample configuration file written to {}", Strings.clickableUrl(sampleFile));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ private void setupInstructions(List<Instruction> additionalInstructions) {
getInstructions().addAll(additionalInstructions);
if (getInstructions().get().stream().noneMatch(instruction -> instruction.getKeyword().equals(EntryPointInstruction.KEYWORD))) {
entryPoint(getArgs().map(strings -> {
List<String> newList = new ArrayList<>(strings.size() + 3);
var newList = new ArrayList<String>(strings.size() + 3);
newList.add("/home/app/checkpoint.sh");
newList.addAll(strings);
return newList;
Expand All @@ -160,7 +160,7 @@ void setupDockerfileInstructions() {
*/
void setupTaskPostEvaluate() {
// Get any custom instructions the user may or may not have entered, but ignoring our 'from' placeholder
List<Instruction> additionalInstructions = new ArrayList<>(getInstructions().get().subList(1, getInstructions().get().size()));
var additionalInstructions = new ArrayList<>(getInstructions().get().subList(1, getInstructions().get().size()));
// Reset the instructions to empty
getInstructions().set(new ArrayList<>());
setupInstructions(additionalInstructions);
Expand All @@ -170,11 +170,13 @@ static void setupResources(CRaCCheckpointDockerfile task) {
String workDir = DEFAULT_WORKING_DIR;
task.workingDir(workDir);
task.instruction("# Add required libraries");
task.runCommand("apt-get update && apt-get install -y \\\n" +
" curl \\\n" +
" jq \\\n" +
" libnl-3-200 \\\n" +
" && rm -rf /var/lib/apt/lists/*");
task.runCommand("""
apt-get update && apt-get install -y \\
curl \\
jq \\
libnl-3-200 \\
&& rm -rf /var/lib/apt/lists/*
""");
task.instruction("# Install latest CRaC OpenJDK");

// Limit the architecture, Azul doesn't support x86_64 https://api.azul.com/metadata/v1/docs/swagger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,11 @@ private void setupResources() {
String workDir = DEFAULT_WORKING_DIR;
workingDir(workDir);
instruction("# Add required libraries");
runCommand("apt-get update && apt-get install -y \\\n" +
" libnl-3-200 \\\n" +
" && rm -rf /var/lib/apt/lists/*");
runCommand("""
apt-get update && apt-get install -y \\
libnl-3-200 \\
&& rm -rf /var/lib/apt/lists/*
""");
instruction("# Copy CRaC JDK from the checkpoint image (to save a download)");
copyFile("--from=" + createCheckpointImageName(getProject()) + " /azul-crac-jdk", "/azul-crac-jdk");
instruction("# Copy layers");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@
import io.micronaut.gradle.docker.DockerBuildStrategy;
import io.micronaut.gradle.docker.model.MicronautDockerImage;
import io.micronaut.gradle.docker.tasks.BuildLayersTask;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.RegularFile;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.plugins.PluginManager;
Expand Down Expand Up @@ -64,7 +62,7 @@ private void configurePlugin(Project project) {
ExtensionContainer extensions = project.getExtensions();
MicronautExtension micronautExtension = extensions.getByType(MicronautExtension.class);
CRaCConfiguration configuration = createCRaCConfiguration(project);
NamedDomainObjectContainer<MicronautDockerImage> dockerImages = (NamedDomainObjectContainer<MicronautDockerImage>) micronautExtension.getExtensions().findByName("dockerImages");
var dockerImages = (NamedDomainObjectContainer<MicronautDockerImage>) micronautExtension.getExtensions().findByName("dockerImages");
createCheckpointDockerImage(project, dockerImages.findByName("main"), configuration);
}

Expand Down Expand Up @@ -209,19 +207,16 @@ private CheckpointTasksOfNote configureCheckpointDockerBuild(Project project,
task.getContainerId().set(start.flatMap(DockerExistingContainer::getContainerId));
task.getSink().fileValue(checkpointFile);
// Do not use lambda, or it's not compatible with Gradle's config cache
task.doLast(new Action<>() {
@Override
public void execute(Task t) {
List<String> lines;
try {
lines = Files.readAllLines(checkpointFile.toPath());
} catch (IOException e) {
throw new GradleException("Checkpoint container failed");
}
lines.forEach(task.getLogger()::lifecycle);
if (lines.stream().noneMatch(l -> l.contains("Snapshotting complete"))) {
throw new GradleException("Checkpoint container failed");
}
task.doLast(t -> {
List<String> lines;
try {
lines = Files.readAllLines(checkpointFile.toPath());
} catch (IOException e) {
throw new GradleException("Checkpoint container failed");
}
lines.forEach(task.getLogger()::lifecycle);
if (lines.stream().noneMatch(l -> l.contains("Snapshotting complete"))) {
throw new GradleException("Checkpoint container failed");
}
});
});
Expand All @@ -233,22 +228,15 @@ static String createCheckpointImageName(Project project) {
return (project.getRootProject().getName() + project.getPath() + "-checkpoint").replace(":", "-");
}

private static class CheckpointTasksOfNote {

private final TaskProvider<CRaCCheckpointDockerfile> checkpointDockerBuild;
private final TaskProvider<DockerStartContainer> start;

private CheckpointTasksOfNote(
@Nullable TaskProvider<CRaCCheckpointDockerfile> checkpointDockerBuild,
TaskProvider<DockerStartContainer> start
) {
this.checkpointDockerBuild = checkpointDockerBuild;
this.start = start;
}
private record CheckpointTasksOfNote(
@Nullable
TaskProvider<CRaCCheckpointDockerfile> checkpointDockerBuild,
TaskProvider<DockerStartContainer> start
) {

Optional<TaskProvider<CRaCCheckpointDockerfile>> getCheckpointDockerBuild() {
return Optional.ofNullable(checkpointDockerBuild);
}
return Optional.ofNullable(checkpointDockerBuild);
}
}

private Optional<TaskProvider<CRaCFinalDockerfile>> configureFinalDockerBuild(Project project,
Expand Down Expand Up @@ -289,13 +277,10 @@ private Optional<TaskProvider<CRaCFinalDockerfile>> configureFinalDockerBuild(Pr
}
task.getImages().set(Collections.singletonList(project.getName()));
task.getInputDir().set(dockerFileTask.flatMap(Dockerfile::getDestDir));
task.doLast(new Action<>() {
@Override
public void execute(Task t) {
t.getLogger().warn("**********************************************************");
t.getLogger().warn(" CRaC checkpoint files may contain sensitive information.");
t.getLogger().warn("**********************************************************");
}
task.doLast(t -> {
t.getLogger().warn("**********************************************************");
t.getLogger().warn(" CRaC checkpoint files may contain sensitive information.");
t.getLogger().warn("**********************************************************");
});
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.micronaut.gradle.crac;

import org.gradle.api.logging.Logger;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.StringWriter;
Expand All @@ -18,7 +19,7 @@ public TeeStringWriter(Logger logger) {

@Override
@SuppressWarnings("java:S2629") // This is done by Gradle
public void write(char[] cbuf, int off, int len) {
public void write(char @NotNull [] cbuf, int off, int len) {
delegate.write(cbuf, off, len);
logger.lifecycle(new String(cbuf, off, len).trim());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ void perform() throws IOException {
Provider<RegularFile> checkpointFile = getOutputDir().file("checkpoint.sh");
Path checkpointScriptPath = checkpointFile.get().getAsFile().toPath();

FilterSet filterSet = new FilterSet();
var filterSet = new FilterSet();
filterSet.addFilter("READINESS", getPreCheckpointReadinessCommand().get());

try (InputStream stream = getCheckpointFile().isPresent() ?
try (var stream = getCheckpointFile().isPresent() ?
Files.newInputStream(getCheckpointFile().get().getAsFile().toPath()) :
CheckpointScriptTask.class.getResourceAsStream("/checkpoint.sh");
Reader reader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter writer = Files.newBufferedWriter(checkpointScriptPath, StandardCharsets.UTF_8)) {
var bufferedReader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = Files.newBufferedWriter(checkpointScriptPath, StandardCharsets.UTF_8)
) {
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.write(filterSet.replaceTokens(line));
Expand Down
Loading

0 comments on commit 75419e6

Please sign in to comment.