slawekjaranowski commented on code in PR #347:
URL:
https://github.com/apache/maven-clean-plugin/pull/347#discussion_r4111520730
##########
src/main/java/org/apache/maven/plugins/clean/BackgroundCleaner.java:
##########
@@ -255,18 +381,156 @@ boolean fastDelete(Path baseDir) throws IOException {
}
/**
- * Deletes the given directory without logging messages and without
throwing {@link IOException}.
- * The exceptions are stored for reporting after the end of the session.
+ * Deletes the given directory in a background thread using batch retry.
+ * Unlike the foreground {@link Cleaner}, this method does not call {@code
System.gc()}
+ * or sleep per file, avoiding the stop-the-world JVM pauses that caused
the performance
+ * regression described in MCLEAN-102.
+ *
+ * <p>The deletion proceeds in two passes:</p>
+ * <ol>
+ * <li><b>Walk:</b> traverse the file tree and attempt to delete each
file/directory once.
+ * Failures are silently collected without retrying.</li>
+ * <li><b>Batch retry:</b> if {@code retryOnError} is enabled and there
were failures,
+ * sleep once ({@value #BATCH_RETRY_DELAY_MS}ms) to let external
processes release
+ * file locks, then retry all failures together.</li>
+ * </ol>
+ *
+ * <p>Any files that still cannot be deleted after the batch retry will be
cleaned up
+ * by the {@linkplain #scanForLeftovers() leftover scan} on the next
build.</p>
*
* <h4>Thread safety</h4>
- * Contrarily to most other methods in {@code BackgroundCleaner}, this
method is
- * thread-safe because it uses a copy of this cleaner for walking in the
file tree.
+ * This method is designed to run in the background executor thread. It
does not share
+ * any mutable state with the main thread except through {@link
#errorOccurred(IOException)},
+ * which is synchronized.
+ *
+ * @param dir the directory to delete
+ * @param force whether to force the deletion of read-only files
+ * @param retryOnError whether to undertake a batch retry of failed
deletions
*/
- private void deleteSilently(final Path dir) {
+ private void deleteInBackground(Path dir, boolean force, boolean
retryOnError) {
+ logger.debug("Deleting " + dir + " in background.");
+ List<Path> failures = new ArrayList<>();
try {
- Files.walkFileTree(dir, Set.of(), Integer.MAX_VALUE, new
Cleaner(this));
+ Files.walkFileTree(dir, Set.of(), Integer.MAX_VALUE, new
SimpleFileVisitor<>() {
+ /**
+ * Current depth relative to the root directory, used by
{@link Cleaner#setWritable}
+ * to walk up to the parent when the file itself is already
writable.
+ */
+ int depth;
+
+ @Override
+ public FileVisitResult preVisitDirectory(Path d,
BasicFileAttributes attrs) {
+ if (ON_WINDOWS && attrs.isOther()) {
+ // MCLEAN-93: NTFS junctions have isDirectory() and
isOther() attributes set.
+ // Delete the junction itself and skip its contents to
avoid deleting the
+ // contents of the junction target, which may be
outside the project.
+ if (!tryDeleteOnce(d, force, depth)) {
+ failures.add(d);
+ }
+ return FileVisitResult.SKIP_SUBTREE;
+ }
+ depth++;
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
+ if (!tryDeleteOnce(file, force, depth)) {
+ failures.add(file);
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(Path d, IOException
exc) {
+ depth--;
+ if (!tryDeleteOnce(d, force, depth)) {
+ failures.add(d);
+ }
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult visitFileFailed(Path file, IOException
exc) {
+ failures.add(file);
+ return FileVisitResult.CONTINUE;
+ }
+ });
} catch (IOException e) {
errorOccurred(e);
+ return;
+ }
+ if (!failures.isEmpty() && retryOnError) {
+ try {
+ Thread.sleep(BATCH_RETRY_DELAY_MS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ // Report collected failures before returning.
+ errorOccurred(buildFailureException(failures));
+ return;
+ }
+ List<Path> remaining = new ArrayList<>();
+ for (Path path : failures) {
+ if (!tryDeleteOnce(path, force, 0)) {
+ remaining.add(path);
+ }
+ }
+ if (!remaining.isEmpty()) {
+ errorOccurred(buildFailureException(remaining));
+ }
+ } else if (!failures.isEmpty()) {
+ errorOccurred(buildFailureException(failures));
+ }
+ }
+
+ /**
+ * Builds an {@link IOException} that reports the failing paths (capped at
10) and total count.
+ *
+ * @param failures the list of paths that could not be deleted
+ * @return an exception describing the failures
+ */
+ private static IOException buildFailureException(List<Path> failures) {
+ StringBuilder sb = new StringBuilder("Failed to delete ")
+ .append(failures.size())
+ .append(" path(s) during background clean");
+ int limit = Math.min(failures.size(), 10);
+ for (int i = 0; i < limit; i++) {
+ sb.append("\n ").append(failures.get(i));
+ }
+ if (failures.size() > limit) {
+ sb.append("\n ... and ").append(failures.size() - limit).append("
more");
+ }
+ return new IOException(sb.toString());
+ }
+
+ /**
+ * Tries to delete a single file or directory once, without retry delays
or {@code System.gc()}.
+ * If {@code force} is enabled and deletion fails with {@link
AccessDeniedException},
+ * the file (or its parent directory) is made writable and deletion is
retried immediately (once).
+ *
+ * @param file the file or directory to delete
+ * @param force whether to make read-only files writable before retrying
+ * @param currentDepth the depth of the file relative to the staged root,
used by
+ * {@link Cleaner#setWritable} to walk up to the
parent directory
+ * @return {@code true} if the file was deleted or did not exist
+ */
+ private static boolean tryDeleteOnce(Path file, boolean force, int
currentDepth) {
+ try {
+ Files.deleteIfExists(file);
+ return true;
+ } catch (AccessDeniedException e) {
+ if (force) {
+ try {
+ Cleaner.setWritable(file, currentDepth);
Review Comment:
Reopening for the one point from this thread that is *not* covered by
`fca73f3`: `failOnError` does not apply to the background path.
The `setWritable` loop is fixed — verified, and both the new unit test and
the `read-only-fast` IT fail if I revert it, so that part is properly guarded.
Thanks.
But `failOnError=true` (the default) is still ignored once deletion moves to
the background thread. Same project, same plugin configuration, only `fast`
differs, against `fca73f3` with `force=false`, `retryOnError=false`,
`failOnError=true` and a `target/read-only-dir` at `dr-xr-xr-x` holding a file
at `r--r--r--`:
**`fast=false`** — exit code 1:
```
[ERROR] Failed to execute goal ...:clean (default-clean) on project probe:
Failed to clean project:
.../target/read-only-dir/read-only.properties
```
**`fast=true`** — exit code 0:
```
[WARNING] Errors during background file deletion.
java.io.IOException: Failed to delete 3 path(s) during background clean
.../.fastdir/probe-…/read-only-dir/read-only.properties
.../.fastdir/probe-…/read-only-dir
.../.fastdir/probe-…
[INFO] BUILD SUCCESS
```
with those three paths still on disk afterwards. So turning on `fast`
silently downgrades a configured build failure to a warning, and the leftovers
stay in the staging directory until some later build's leftover scan happens to
clear them.
This is not a regression from this PR — the background path never honoured
`failOnError` — so it is a reasonable thing to leave out of scope. But it is
now the sharpest remaining difference between the two paths, and `failOnError`
is the knob users reach for precisely because they want the build to stop.
Options, in increasing order of effort:
1. Document it: note in the `fast` / `failOnError` parameter Javadoc and on
the plugin site that `failOnError` has no effect in fast mode.
2. Honour it: `BackgroundCleaner` already collects the errors and `onEvent`
already waits for the executor before `run()`, so the accumulated `IOException`
could be thrown (or reported as a build failure) from there when the
originating configuration had `failOnError=true` — which would mean capturing
`failOnError` per submitted directory alongside `force` and `retryOnError` in
`DeferredDeletion`.
Happy with either, including just option 1, or with a follow-up issue.
Flagging it so the decision is explicit rather than implied.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]