Apache Lucene open-source search software
More gradle convention plugins converted to Java (#15096)
Dawid Weiss095856e844e2
diff --git a/build-options.properties b/build-options.propertiesindex 57143d65e6f..b2c2339dacf 100644--- a/build-options.properties+++ b/build-options.properties@@ -14,3 +14,8 @@ version.suffix=SNAPSHOT# can override it manually to any x.y.z string to set an arbitrary# Lucene version.# version.release=+++# Enable gradle no-progress tracking, temporarily.+# https://github.com/apache/lucene/issues/15095+lucene.trackGradleState=truediff --git a/build-tools/build-infra/src/main/groovy/lucene.misc.measure-task-times.gradle b/build-tools/build-infra/src/main/groovy/lucene.misc.measure-task-times.gradledeleted file mode 100644index b967d239ef9..00000000000--- a/build-tools/build-infra/src/main/groovy/lucene.misc.measure-task-times.gradle+++ /dev/null@@ -1,78 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one or more- * contributor license agreements. See the NOTICE file distributed with- * this work for additional information regarding copyright ownership.- * The ASF licenses this file to You 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- *- * http://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 java.util.concurrent.ConcurrentHashMap-import java.util.concurrent.TimeUnit-import java.util.stream.Collectors--// Measure aggregate wall time of each task execution time (summed up across-// all projects).--if (project != project.rootProject) {- throw new GradleException("Applicable to rootProject only: " + project.path)-}--Provider<Boolean> taskTimesOption = buildOptions.addBooleanOption("task.times",- "Measures wall-time task execution and provides a summary of the longest tasks at " +- "the end of a successful build.",- false)--if (taskTimesOption.get()) {- gradle.taskGraph.whenReady { TaskExecutionGraph graph ->- def taskTimes = new ConcurrentHashMap<String, Long>()-- graph.addTaskExecutionListener(new TaskExecutionListener() {- @Override- void beforeExecute(Task task) {- def start = System.nanoTime()- taskTimes.put(task.path, start)- }-- @Override- void afterExecute(Task task, TaskState taskState) {- if (taskState.didWork) {- def stop = System.nanoTime()- taskTimes.compute(task.path, { k, v -> TimeUnit.NANOSECONDS.toMillis(stop - v) })- } else {- taskTimes.remove(task.path)- }- }- })-- // After the build is finished, check the test count.- gradle.buildFinished {- // Compute aggregate times of all task execution times.- def aggregates = taskTimes.entrySet().stream()- .collect(Collectors.groupingBy({e -> e.key.replaceAll(".*:", "")}))- .entrySet().stream()- .collect(Collectors.toMap(- {e -> e.key }, {e ->- e.value.stream().mapToLong({ entry -> entry.value }).sum()- }- ))-- logger.lifecycle("\nAggregate task times (possibly running in parallel!):\n"- + aggregates- .sort {a, b ->- Long.compare(b.value, a.value)- }- .collect { v ->- String.format(Locale.ROOT, " %6.2f sec. %s", v.value / 1000.0, v.key)- }- .join("\n"))- }- }-}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/DumpGradleStateOnStalledBuildsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/DumpGradleStateOnStalledBuildsPlugin.javanew file mode 100644index 00000000000..d3cb9bcf547--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/hacks/DumpGradleStateOnStalledBuildsPlugin.java@@ -0,0 +1,282 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You 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+ *+ * http://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.+ */+package org.apache.lucene.gradle.plugins.hacks;++import java.lang.management.LockInfo;+import java.lang.management.ManagementFactory;+import java.lang.management.MonitorInfo;+import java.lang.management.ThreadInfo;+import java.lang.management.ThreadMXBean;+import java.time.Duration;+import java.time.Instant;+import java.util.Locale;+import java.util.concurrent.TimeUnit;+import javax.inject.Inject;+import org.apache.lucene.gradle.SuppressForbidden;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.gradle.api.Project;+import org.gradle.api.logging.Logger;+import org.gradle.api.logging.Logging;+import org.gradle.api.provider.Provider;+import org.gradle.api.services.BuildService;+import org.gradle.api.services.BuildServiceParameters;+import org.gradle.build.event.BuildEventsListenerRegistry;+import org.gradle.tooling.events.FinishEvent;+import org.gradle.tooling.events.OperationCompletionListener;++/**+ * This tracks the build progress (looking at task completion updates) and emits some diagnostics if+ * no such progress can be observed.+ */+public class DumpGradleStateOnStalledBuildsPlugin extends LuceneGradlePlugin {+ /** Check for stalled progress every minute. */+ static final long checkIntervalMillis = TimeUnit.MINUTES.toMillis(1);++ /**+ * After the no-progress is detected, dump everything every 5 minutes (unless progress is+ * restored).+ */+ static final long recheckIntervalMillis = TimeUnit.MINUTES.toMillis(5);++ /** Consider 3 minutes of no-updates as no-progress. */+ static final long minDurationOfNoUpdates = TimeUnit.MINUTES.toNanos(3);++ public static final String OPT_TRACK_GRADLE_STATE = "lucene.trackGradleState";++ private final BuildEventsListenerRegistry listenerRegistry;++ @Inject+ public DumpGradleStateOnStalledBuildsPlugin(BuildEventsListenerRegistry listenerRegistry) {+ this.listenerRegistry = listenerRegistry;+ }++ @Override+ public void apply(Project project) {+ applicableToRootProjectOnly(project);++ var buildOptions = getBuildOptions(project);+ var trackStateOption =+ buildOptions.addBooleanOption(+ OPT_TRACK_GRADLE_STATE,+ "Track build progress and dump gradle jvm state diagnostics in case of no progress.",+ false);++ if (!trackStateOption.get()) {+ return;+ }++ Provider<TrackProgressService> service =+ project+ .getGradle()+ .getSharedServices()+ .registerIfAbsent("trackProgressService", TrackProgressService.class, _ -> {});++ listenerRegistry.onTaskCompletion(service);+ }++ /**+ * This service collects per-task durations and prints a summary when closed (at the end of the+ * build).+ */+ public abstract static class TrackProgressService+ implements BuildService<BuildServiceParameters.None>,+ OperationCompletionListener,+ AutoCloseable {+ private static final Logger LOGGER = Logging.getLogger(TrackProgressService.class);++ /** Execution time of all successful tasks. Keys are task paths, values are in millis. */+ private volatile long lastUpdateNanos = System.nanoTime();++ private final Thread trackerThread;+ private volatile boolean stop;++ public TrackProgressService() {+ this.trackerThread =+ new Thread("gradle-progress-tracker") {+ @Override+ public void run() {+ while (!stop) {+ try {+ sleepNow(checkIntervalMillis);++ long noUpdateTime = System.nanoTime() - lastUpdateNanos;+ if (noUpdateTime >= minDurationOfNoUpdates) {+ dumpGradleState(noUpdateTime);+ sleepNow(recheckIntervalMillis);+ }+ } catch (InterruptedException _) {+ // ignore.+ }+ }+ }++ @SuppressForbidden(reason = "legitimate sleep here.")+ private void sleepNow(long millis) throws InterruptedException {+ Thread.sleep(millis);+ }+ };+ trackerThread.setDaemon(true);+ trackerThread.start();+ }++ private void dumpGradleState(long noUpdateTimeNanos) {+ LOGGER.warn(+ "{}: Gradle panic: no status update in {}" + " seconds?",+ Instant.now(),+ Duration.ofNanos(noUpdateTimeNanos).toSeconds());++ String jvmDiags;+ try {+ jvmDiags = collectJvmDiagnostics();+ } catch (Throwable t) {+ jvmDiags = "Failed to collect jvm diagnostics: " + t.getMessage();+ }+ LOGGER.warn(jvmDiags);+ }++ /** Collects heap stats and a full thread dump into a single String. */+ public static String collectJvmDiagnostics() {+ StringBuilder sb = new StringBuilder(32_768);++ sb.append("====== GRADLE JVM DIAGNOSTICS ======\n");++ Runtime rt = Runtime.getRuntime();+ long max = rt.maxMemory();+ long total = rt.totalMemory();+ long free = rt.freeMemory();+ long used = total - free;++ sb.append("=== JVM Heap ===\n")+ .append("Max: ")+ .append(formatBytes(max))+ .append(" (")+ .append(max)+ .append(" bytes)\n")+ .append("Total: ")+ .append(formatBytes(total))+ .append(" (")+ .append(total)+ .append(" bytes)\n")+ .append("Free: ")+ .append(formatBytes(free))+ .append(" (")+ .append(free)+ .append(" bytes)\n")+ .append("Used: ")+ .append(formatBytes(used))+ .append(" (")+ .append(used)+ .append(" bytes)\n\n");++ // --- Thread dump ---+ ThreadMXBean tmx = ManagementFactory.getThreadMXBean();+ boolean withMonitors = tmx.isObjectMonitorUsageSupported();+ boolean withSyncs = tmx.isSynchronizerUsageSupported();++ ThreadInfo[] infos = tmx.dumpAllThreads(withMonitors, withSyncs);+ sb.append("=== Threads (").append(infos.length).append(") ===\n");++ for (ThreadInfo ti : infos) {+ if (ti == null) continue;++ sb.append('"')+ .append(ti.getThreadName())+ .append('"')+ .append(" Id=")+ .append(ti.getThreadId())+ .append(" ")+ .append(ti.getThreadState());+ if (ti.isSuspended()) sb.append(" (suspended)");+ if (ti.isInNative()) sb.append(" (in native)");+ sb.append('\n');++ // Stack trace with monitor/synchronizer details+ StackTraceElement[] stack = ti.getStackTrace();+ for (int i = 0; i < stack.length; i++) {+ StackTraceElement ste = stack[i];+ sb.append("\tat ").append(ste).append('\n');++ // Lock the thread is currently waiting on+ if (i == 0 && ti.getLockInfo() != null) {+ sb.append("\t- waiting on ").append(ti.getLockInfo()).append('\n');+ }+ // Monitors locked at this frame+ if (withMonitors) {+ for (MonitorInfo mi : ti.getLockedMonitors()) {+ if (mi.getLockedStackDepth() == i) {+ sb.append("\t- locked ").append(mi).append('\n');+ }+ }+ }+ }++ // Locked synchronizers (e.g., ReentrantLocks)+ if (withSyncs) {+ LockInfo[] locks = ti.getLockedSynchronizers();+ if (locks.length > 0) {+ sb.append("\n\tLocked synchronizers:\n");+ for (LockInfo li : locks) {+ sb.append("\t- ").append(li).append('\n');+ }+ }+ }+ sb.append('\n');+ }++ // --- Deadlock info (if any) ---+ long[] deadlocked = tmx.findDeadlockedThreads();+ if (deadlocked != null && deadlocked.length > 0) {+ sb.append("=== Deadlocked Threads ===\n");+ for (long id : deadlocked) {+ sb.append(" - Thread Id=").append(id).append('\n');+ }+ }++ sb.append("====== END: GRADLE JVM DIAGNOSTICS ======\n");++ return sb.toString();+ }++ private static String formatBytes(long bytes) {+ if (bytes < 1024) return bytes + " B";+ double v = bytes;+ String[] units = {"KB", "MB", "GB", "TB", "PB"};+ int i = 0;+ while (v >= 1024 && i < units.length - 1) {+ v /= 1024;+ i++;+ }+ return String.format(Locale.ROOT, "%.2f %s", v, units[i]);+ }++ @Override+ public void onFinish(FinishEvent event) {+ lastUpdateNanos = System.nanoTime();+ }++ @Override+ public void close() {+ try {+ this.stop = true;+ this.trackerThread.interrupt();+ this.trackerThread.join(Duration.ofSeconds(10));+ } catch (InterruptedException e) {+ LOGGER.warn("Interrupted while waiting for tracker thread to finish.", e);+ }+ }+ }+}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.javaindex f3ba9d58959..27b13c88447 100644--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/help/BuildOptionGroupsPlugin.java@@ -20,7 +20,9 @@ import com.carrotsearch.gradle.buildinfra.buildoptions.BuildOptionsTask;import java.util.regex.Pattern;import java.util.stream.Collectors;import java.util.stream.Stream;+import org.apache.lucene.gradle.plugins.hacks.DumpGradleStateOnStalledBuildsPlugin;import org.apache.lucene.gradle.plugins.ide.EclipseSupportPlugin;+import org.apache.lucene.gradle.plugins.misc.MeasureTaskTimesPlugin;import org.gradle.api.Plugin;import org.gradle.api.Project;@@ -84,7 +86,10 @@ public class BuildOptionGroupsPlugin implements Plugin<Project> {explicitList("lucene.spotlessGradleScripts","lucene.gjf.batchSize",- "task.times",+ MeasureTaskTimesPlugin.OPT_TASK_TIMES,+ MeasureTaskTimesPlugin.OPT_TASK_TIMES_LIMIT,+ MeasureTaskTimesPlugin.OPT_TASK_TIMES_AGGREGATE,+ DumpGradleStateOnStalledBuildsPlugin.OPT_TRACK_GRADLE_STATE,"javac.failOnWarnings","tests.slowestSuites","tests.slowestSuites.minTime",diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/MeasureTaskTimesPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/MeasureTaskTimesPlugin.javanew file mode 100644index 00000000000..cbec2138240--- /dev/null+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/MeasureTaskTimesPlugin.java@@ -0,0 +1,178 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You 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+ *+ * http://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.+ */+package org.apache.lucene.gradle.plugins.misc;++import java.util.Comparator;+import java.util.Locale;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;+import java.util.stream.Collectors;+import javax.inject.Inject;+import org.apache.lucene.gradle.plugins.LuceneGradlePlugin;+import org.gradle.api.Project;+import org.gradle.api.logging.Logger;+import org.gradle.api.logging.Logging;+import org.gradle.api.provider.Property;+import org.gradle.api.provider.Provider;+import org.gradle.api.services.BuildService;+import org.gradle.api.services.BuildServiceParameters;+import org.gradle.build.event.BuildEventsListenerRegistry;+import org.gradle.tooling.events.FinishEvent;+import org.gradle.tooling.events.OperationCompletionListener;+import org.gradle.tooling.events.task.TaskFailureResult;+import org.gradle.tooling.events.task.TaskFinishEvent;+import org.gradle.tooling.events.task.TaskSuccessResult;++/**+ * Prints aggregate wall-clock times for all executed gradle tasks (collected across all projects).+ */+public class MeasureTaskTimesPlugin extends LuceneGradlePlugin {+ public static final String OPT_TASK_TIMES = "task.times";+ public static final String OPT_TASK_TIMES_AGGREGATE = "task.times.aggregate";+ public static final String OPT_TASK_TIMES_LIMIT = "task.times.limit";++ private final BuildEventsListenerRegistry listenerRegistry;++ @Inject+ public MeasureTaskTimesPlugin(BuildEventsListenerRegistry listenerRegistry) {+ this.listenerRegistry = listenerRegistry;+ }++ @Override+ public void apply(Project project) {+ applicableToRootProjectOnly(project);++ var buildOptions = getBuildOptions(project);+ var taskTimesOption =+ buildOptions.addBooleanOption(+ OPT_TASK_TIMES,+ "Measures wall-time task execution and provides a summary of the longest tasks at "+ + "the end of a successful build.",+ false);++ var aggregateOption =+ buildOptions.addBooleanOption(+ OPT_TASK_TIMES_AGGREGATE,+ "Aggregate task times by unique name (across all projects). If false, unique task paths are printed.",+ true);++ var taskCountLimitOption =+ buildOptions.addIntOption(OPT_TASK_TIMES_LIMIT, "Limit the list to the top-N tasks.", 20);++ if (!taskTimesOption.get()) {+ return;+ }++ Provider<TaskTimesService> taskTimesService =+ project+ .getGradle()+ .getSharedServices()+ .registerIfAbsent(+ "taskTimesService",+ TaskTimesService.class,+ service -> {+ service.parameters(+ params -> {+ params.getAggregateByName().set(aggregateOption.get());+ params.getLimit().set(taskCountLimitOption.get());+ });+ });++ listenerRegistry.onTaskCompletion(taskTimesService);+ }++ /**+ * This service collects per-task durations and prints a summary when closed (at the end of the+ * build).+ */+ public abstract static class TaskTimesService+ implements BuildService<TaskTimesServiceParams>, OperationCompletionListener, AutoCloseable {+ private static final Logger LOGGER = Logging.getLogger(TaskTimesService.class);++ /** Execution time of all successful tasks. Keys are task paths, values are in millis. */+ private final ConcurrentHashMap<String, Long> taskTimes = new ConcurrentHashMap<>();++ private volatile boolean hadFailedTask;++ @Override+ public void onFinish(FinishEvent event) {+ if (event instanceof TaskFinishEvent tfe) {+ if (tfe.getResult() instanceof TaskSuccessResult successResult) {+ long durationMillis =+ Math.max(0, successResult.getEndTime() - successResult.getStartTime());+ String taskPath = tfe.getDescriptor().getTaskPath();+ taskTimes.compute(taskPath, (_, value) -> (value == null ? 0 : value) + durationMillis);+ }++ if (tfe.getResult() instanceof TaskFailureResult) {+ hadFailedTask = true;+ }+ }+ }++ private static String simpleTaskName(String path) {+ int idx = path.lastIndexOf(':');+ return (idx >= 0 && idx < path.length() - 1) ? path.substring(idx + 1) : path;+ }++ @Override+ public void close() {+ if (taskTimes.isEmpty() || hadFailedTask) return;++ var params = getParameters();++ Map<String, Long> localTaskTimes = taskTimes;++ if (params.getAggregateByName().get()) {+ localTaskTimes =+ localTaskTimes.entrySet().stream()+ .collect(Collectors.groupingBy(e -> simpleTaskName(e.getKey())))+ .entrySet()+ .stream()+ .collect(+ Collectors.toMap(+ Map.Entry::getKey,+ e -> e.getValue().stream().mapToLong(Map.Entry::getValue).sum()));+ }++ String report =+ localTaskTimes.entrySet().stream()+ .sorted(+ Comparator.comparingLong((Map.Entry<String, Long> e) -> e.getValue()).reversed())+ .map(+ e ->+ String.format(+ Locale.ROOT, " %6.2f sec. %s", e.getValue() / 1000.0, e.getKey()))+ .limit(params.getLimit().get())+ .collect(Collectors.joining("\n"));++ LOGGER.lifecycle(+ "\nSummary of top-{} task execution times ({}):\n{}",+ params.getLimit().get(),+ params.getAggregateByName().get()+ ? "aggregated by unique name, possibly running in parallel"+ : "unique task paths",+ report);+ }+ }++ public interface TaskTimesServiceParams extends BuildServiceParameters {+ Property<Boolean> getAggregateByName();++ Property<Integer> getLimit();+ }+}diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.javaindex d8e4ba18c50..3e44576a7d7 100644--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/RootProjectSetupPlugin.java@@ -24,6 +24,7 @@ import org.apache.lucene.gradle.plugins.eclint.EditorConfigLintPlugin;import org.apache.lucene.gradle.plugins.gitgrep.GitGrepPlugin;import org.apache.lucene.gradle.plugins.gitinfo.GitInfoPlugin;import org.apache.lucene.gradle.plugins.globals.RegisterBuildGlobalsPlugin;+import org.apache.lucene.gradle.plugins.hacks.DumpGradleStateOnStalledBuildsPlugin;import org.apache.lucene.gradle.plugins.hacks.HacksPlugin;import org.apache.lucene.gradle.plugins.hacks.TuneJvmOptionsPlugin;import org.apache.lucene.gradle.plugins.hacks.WipeGradleTempPlugin;@@ -82,6 +83,9 @@ public class RootProjectSetupPlugin extends LuceneGradlePlugin {plugins.apply(EclipseSupportPlugin.class);plugins.apply(IdeaSupportPlugin.class);+ plugins.apply(MeasureTaskTimesPlugin.class);+ plugins.apply(DumpGradleStateOnStalledBuildsPlugin.class);+// Apply more convention plugins to all projects.rootProject.getAllprojects()diff --git a/build.gradle b/build.gradleindex fd78dceaa9d..05b3d5425e2 100644--- a/build.gradle+++ b/build.gradle@@ -41,7 +41,6 @@ plugins {id "lucene.publications.maven-to-nexus-releases"id "lucene.publications.maven-to-nexus-snapshots"- id "lucene.misc.measure-task-times"id "lucene.misc.pylucene"id "lucene.datasets.external-datasets"