Skip to content

Add --processes to list running Maven builds. - #11102

Open
arturobernalg wants to merge 1 commit into
apache:masterfrom
arturobernalg:10627
Open

arturobernalg wants to merge 1 commit into
apache:masterfrom
arturobernalg:10627

Conversation

@arturobernalg

@arturobernalg arturobernalg commented Sep 5, 2025 •

Copy link
Copy Markdown
Member

Implements a per-user registry under ~/.m2/.maven/runs (create on start, remove on exit). Pure Java 17 using ProcessHandle; no jps or vendor tools.

Following this checklist to help us incorporate your
contribution quickly and easily:

  • [ X] Your pull request should address just one issue, without pulling in other changes.
  • [ X] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • [ X] Each commit in the pull request should have a meaningful subject line and body.
    Note that commits might be squashed by a maintainer on merge.
  • [ X] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied.
    This may not always be possible but is a best-practice.
  • [ X] Run mvn verify to make sure basic checks pass.
    A more thorough check will be performed on your pull request automatically.
  • You have run the Core IT successfully.

If your pull request is about ~20 lines of code you don't need to sign an
Individual Contributor License Agreement if you are unsure
please ask on the developers list.

To make clear that you license your contribution under
the Apache License Version 2.0, January 2004
you have to acknowledge this by using the following check-box.

Fixes #10627

}
}

private static String ell(final String s, final int max) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ell -> truncateEnd

@gnodet

gnodet commented Sep 8, 2025

Copy link
Copy Markdown
Contributor

I think we're missing a mvnsh integration. This can be done by adding a command to the builtin command registry:

@arturobernalg

Copy link
Copy Markdown
Member Author

I think we're missing a mvnsh integration. This can be done by adding a command to the builtin command registry:

please do another passs

@gnodet gnodet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution, Arturo. The feature idea is useful, but there are several issues that need to be addressed before this can be merged.

Critical: Duplicate option registration will cause a runtime error

In CommonsCliOptions.CLIManager.prepareOptions(), two Option instances are added with the same longOpt("processes"). Commons CLI does not allow duplicate long option names -- this will silently overwrite the first option, or throw depending on the version. You should register a single option, either with or without a short form.

Critical: Short option -p conflict

The comment says "No short form: -ps already used" but then the code defines PROCESSES_SHORT = "p" and registers Option.builder(PROCESSES_SHORT).longOpt(PROCESSES). The -ps option is used for ALTERNATE_PROJECT_SETTINGS. Using -p as a short option for processes is risky because it is a prefix of -ps and -pl, which could cause ambiguity depending on how commons-cli handles partial matching. I would recommend dropping the short form entirely -- --processes is clear enough for an infrequent diagnostic flag.

Output should use determineWriter(context) instead of System.out.print

The existing pattern for early-exit commands (help, version) uses determineWriter(context) to route output through the proper writer infrastructure. The --processes handler should follow the same pattern rather than writing directly to System.out.

Placement: should be in helpOrVersionAndMayExit not preCommands

The --processes flag is semantically similar to --help and --version: it prints some information and exits. It would be more consistent to handle it in helpOrVersionAndMayExit() or in the Options-level early exit path, rather than in preCommands() which also installs the process registry (mixing the two concerns).

Shell ps command logs exit code 0 as an error

In BuiltinShellCommandRegistryFactory, the ps() method catches ExitException and logs it as an error (shellContext.logger.error("ps command exited with exit code " + ...)). But ExitException(0) represents a successful exit -- the --processes handler throws it to signal normal termination. This will print a confusing error message for a successful operation. I note the same anti-pattern exists in the mvn() handler, but for ps this is the only execution path, so it will always print an error.

ProcessHandle.isAlive() does not verify the process is actually Maven

The listAlive() method checks whether the PID is alive via ProcessHandle.of(pid).map(ProcessHandle::isAlive), but after a system reboot (or PID recycling by the OS), a stale file could match a completely unrelated process. This is a correctness concern: the listing could show non-Maven processes as if they were Maven builds. Consider also checking ProcessHandle.info().command() or the process start time against the recorded started timestamp to validate the process identity.

Run class is private but returned from public methods

The inner class Run is declared private static final class but is returned from the public method listAlive(). While this compiles (the caller is in the same class), it means external callers can only treat the returned list as opaque -- they can iterate over it but cannot access any fields. If the intent is that callers only pass the list to format(), consider making listAlive() package-private, or combining it with format() into a single public method.

Test modifies global System.setProperty("user.home")

The test listsCurrentPidFromRegistry sets System.setProperty("user.home", ...) which is global JVM state. This can cause flakiness when tests run in parallel. Consider injecting the runs directory path instead of relying on System.getProperty("user.home").

Review by Claude Code on behalf of @gnodet

.longOpt(PROCESSES)
.desc("List running Maven processes for the current user")
.build());
options.addOption(Option.builder(PROCESSES_SHORT)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two options are registered with the same longOpt(PROCESSES) (the long-only one on line 363 and the short+long one here). Commons CLI does not support duplicate long option names -- the second addOption call will silently overwrite the first, making the long-only version dead code. You should register a single option.

Moreover, the comment on line 327 says "No short form: -ps already used" but then PROCESSES_SHORT = "p" is defined and used. I would suggest dropping the short option entirely and keeping only the --processes long form:

Suggested change
options.addOption(Option.builder(PROCESSES_SHORT)
options.addOption(Option.builder()
.longOpt(PROCESSES)
.desc("List running Maven processes for the current user and exit")
.build());


if (context.options().processes().orElse(false)) {
final String out = ProcessRuns.format(ProcessRuns.listAlive());
System.out.print(out);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using System.out.print bypasses the Maven output infrastructure. The established pattern in LookupInvoker.helpOrVersionAndMayExit() is to use determineWriter(context) for early-exit output. This should follow the same approach.

Additionally, the --processes check is conceptually an early-exit flag like --help and --version. It would be more appropriate to handle it in helpOrVersionAndMayExit() rather than preCommands(), keeping the process registration separate.

p.getProperty(KEY_VERSION, "-"),
p.getProperty(KEY_WORKDIR, "?"),
p.getProperty(KEY_EXECROOT, "?"),
p.getProperty(KEY_STARTED, "?")));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ProcessHandle.isAlive() only checks whether the PID exists on the system -- after a reboot or PID recycling, a stale descriptor file could match a completely different process. Consider comparing the recorded started timestamp against ProcessHandle.info().startInstant() to verify that the process identity matches, not just the PID.

new String[] {"--processes"}, shellContext.invokerRequest.messageBuilderFactory())
.cwd(shellContext.cwd.get())
.build()));
} catch (InvokerException.ExitException e) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The --processes handler throws ExitException(0) on success, so this catch block will always log an error message for a successful ps command. For exit code 0, this should not be logged as an error. Consider:

} catch (InvokerException.ExitException e) {
    if (e.getExitCode() != 0) {
        shellContext.logger.error("ps command exited with exit code " + e.getExitCode());
    }
}

return runsDir().resolve(FILE_PREFIX + pid + FILE_SUFFIX);
}

public static void install(final long pid, final String version, final Path workDir, final Path execRoot) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The runs directory is derived from System.getProperty("user.home") which couples this class to global JVM state and makes testing harder (the test has to mutate user.home). Consider accepting the base directory as a parameter to install/uninstall/listAlive, or at minimum a package-private overload for testability.

return Optional.empty();
}

public Optional<Boolean> processes() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check commandLine.hasOption(CLIManager.PROCESSES) || commandLine.hasOption(CLIManager.PROCESSES_SHORT) is redundant when both options share the same longOpt. hasOption with the long name will match regardless of whether the user specified the short or long form. If you keep only the long form (as suggested), this simplifies to just commandLine.hasOption(CLIManager.PROCESSES).

@gnodet gnodet added mvn4 enhancement New feature or request labels Jun 22, 2026
gnodet added a commit to gnodet/maven that referenced this pull request Jul 10, 2026
67 open non-draft PRs exist but --limit 30 made 37 invisible to both
the precondition script and the review loop. Raised to 100 in both
check-pr-work.sh and SKILL.md. Also synced 2 newly-visible PRs
(apache#11410, apache#11102) that already have AI reviews from prior sessions.

35 previously-invisible PRs are now actionable and will be picked up
by the loop at 3 per iteration.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@gnodet gnodet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The feature idea — listing running Maven builds via --processes — is useful for diagnostic workflows. However, the implementation has several bugs and design issues that should be addressed:

1. Duplicate option registration (high)
Two Option.builder calls both use .longOpt("processes"). Commons CLI's Options.addOption() stores options in a longOpts map via Map.put(), so the second call silently overwrites the first, making the long-only registration dead code.

2. Contradictory comment and short-option concern (high)
The comment says "No short form: -ps already used" but then defines PROCESSES_SHORT = "p" and registers it. While commons-cli doesn't do partial matching for short options, the comment-code contradiction is a clear code quality issue.

3. Long option ambiguity with --projects (high)
The new --processes long option is dangerously similar to the existing --projects option. Maven's DefaultParser has partial matching enabled by default, so --pro would match both options and throw AmbiguousOptionException. This could break workflows of users who currently abbreviate --projects as --pro. Consider a more distinct name such as --list-processes or --running.

4. System.out bypasses output infrastructure (medium)
System.out.print(out) bypasses Maven's output infrastructure. The existing early-exit handlers (--help, --version) use determineWriter(context) which respects --log-file redirection. This should follow the same pattern.

5. Wrong method placement (medium)
The --processes flag is semantically an early-exit flag like --help and --version (print info, then exit). The listing logic should be handled in helpOrVersionAndMayExit() rather than preCommands(), which currently mixes the listing concern with the process registration concern.

6. Error logging on success (medium)
In BuiltinShellCommandRegistryFactory, the ps command handler throws ExitException(0) for a successful listing, but the catch block unconditionally logs it as shellContext.logger.error(...). Every successful ps invocation produces a misleading error log line.

7. PID recycling vulnerability (medium)
ProcessHandle.isAlive() only checks whether a PID exists. After a reboot or PID recycling, a stale descriptor file could match an unrelated process. The started timestamp is already recorded — comparing it against ProcessHandle.info().startInstant() would verify process identity.

8. Redundant hasOption check (medium)
The hasOption(PROCESSES) || hasOption(PROCESSES_SHORT) check is redundant — a direct consequence of the duplicate option registration issue (#1).

Lower severity: The ProcessRuns directory is derived from System.getProperty("user.home") which couples the class to global JVM state and makes testing harder (the test mutates user.home). Consider accepting the base directory as a parameter.

This review was generated by an AI agent and may contain inaccuracies. Please verify all suggestions before applying.

Claude Code on behalf of gnodet

@slachiewicz

Copy link
Copy Markdown
Member

The last CI run on this branch was 2025-09-25, and GitHub has deleted the logs since, so there's no way to tell whether the change still builds against master.

A rebase triggers a fresh run and makes the state readable again. If you'd rather not carry it forward, closing is equally useful — the PR isn't being ignored, it's unreadable.

The branch also conflicts with master now, so that needs resolving before CI can say anything. Say the word if you'd like a hand with it.

This comment was created with AI assistance.

@slachiewicz slachiewicz added the waiting-for-feedback Waiting for 90 days until issues or pull request will be closed label Aug 24, 2026
@arturobernalg

Copy link
Copy Markdown
Member Author

Reworked per the review: a single long-only option, now --list-processes (no short form), handled in helpOrVersionAndMayExit through determineWriter. ps in mvnsh no longer logs an error on exit 0. A descriptor is dropped if its pid was taken by another process, by comparing the recorded start time, and the runs directory is injectable so tests no longer touch user.home. One clarification: --pro was already ambiguous on master (project-settings vs projects), so --processes did not add a new ambiguity; I renamed it anyway for clarity.

@github-actions github-actions Bot removed the waiting-for-feedback Waiting for 90 days until issues or pull request will be closed label Oct 12, 2026

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All 7 prior findings are addressed in this rework — clean separation between the public API and testable package-private methods, proper best-effort semantics throughout, and solid process liveness check logic. Two low-severity observations below, neither blocking.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

KEY_EXECROOT,
execRoot == null ? "?" : execRoot.toAbsolutePath().toString());
properties.setProperty(KEY_STARTED, started.toString());
try (Writer writer = Files.newBufferedWriter(descriptor(runsDir, pid), StandardCharsets.UTF_8)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Observation (non-blocking): install() writes directly to the final descriptor path via Files.newBufferedWriter(). A concurrent listAlive() could theoretically read a partially-written file. A write-to-temp-then-atomic-move pattern would eliminate the race entirely:

Suggested change
try (Writer writer = Files.newBufferedWriter(descriptor(runsDir, pid), StandardCharsets.UTF_8)) {
Path target = descriptor(runsDir, pid);
Path tmp = runsDir.resolve(FILE_PREFIX + pid + ".tmp");
try (Writer writer = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8)) {
properties.store(writer, "mvn run");
}
Files.move(tmp, target, java.nio.file.StandardCopyOption.ATOMIC_MOVE);

That said, since the whole registry is best-effort and read() already handles parse failures gracefully (catch (IOException | RuntimeException e) → Optional.empty()), the current approach is arguably acceptable.

return "No running Maven processes.";
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("%-10s %-12s %-24s %-48s %-48s", "PID", "VERSION", "STARTED", "WORKDIR", "EXEC_ROOT"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Observation (non-blocking): Column widths are hardcoded to %-48s for WORKDIR and EXEC_ROOT. On narrow terminals (or with long paths that get truncated to 48 chars by truncateStart()), the output will wrap. Consider computing the column width dynamically from the actual max values in the run list, or at least capping the output to the terminal width. The truncateStart() helper already handles the path side — the column width itself could follow suit.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both prior observations addressed in this push. One new (non-blocking) observation on the atomic-write path.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@arturobernalg
arturobernalg force-pushed the 10627 branch 2 times, most recently from 69ce397 to da0830a Compare October 13, 2026 12:43

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Temp-file cleanup on exception addressed — finally { Files.deleteIfExists(temp); } guarantees the .tmp file is removed even when properties.store() or Files.move() throws. The non-blocking column-widths observation (hardcoded %-48s) remains open from the previous review.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

@arturobernalg

Copy link
Copy Markdown
Member Author

Pushed an update: the table no longer uses fixed column widths. Every column but the last is as wide as its widest value and nothing is cut off, and a test covers it. The earlier points (no short option, output through the context writer, atomic descriptor write, start-time check, injectable runs directory) are in the previous commit. @gnodet could you take another look when you have time?

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two observations on new code:

This review was generated by an AI agent, Hermès on behalf of @gnodet.

final Path execRoot = context.invokerRequest.rootDirectory().orElse(context.invokerRequest.topDirectory());
ProcessRuns.install(version, workDir, execRoot);
context.closeables.add(() -> ProcessRuns.uninstall(pid));
} catch (final Throwable ignored) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ catch (Throwable) is too broad here. This silently swallows JVM-fatal errors like OutOfMemoryError and StackOverflowError, making catastrophic failures invisible. Since ProcessRuns.install() already handles IOException | RuntimeException internally, and the remaining calls (ProcessHandle.current().pid(), getClass().getPackage().getImplementationVersion(), context accessors) only throw RuntimeException subclasses — narrowing to catch (Exception) preserves the best-effort semantics without muffling fatal errors.

Suggested change
} catch (final Throwable ignored) {
} catch (final Exception ignored) {

* @since 4.1.0
*/
@Nonnull
default Optional<Boolean> listProcesses() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Naming convention: All existing Options accessors use noun/adjective style — help(), offline(), quiet(), verbose(), projects(), goals(), threads(), userProperties(), etc. listProcesses() is the only imperative verb-command accessor in the interface. Per the accessor-style convention applied consistently across Options and MavenOptions, consider renaming to processes().

Suggested change
default Optional<Boolean> listProcesses() {
default Optional<Boolean> processes() {

Each Maven build registers itself in a per-user registry, one descriptor file in
~/.m2/.maven/runs which is removed when the build ends. --list-processes prints
the builds which are still running and exits, like --help and --version do, and
mvnsh has a matching ps command.

A descriptor is ignored and removed when its process is gone, or when its pid was
taken by another process since: the start time recorded has to be the one of the
process.

@gnodet-bot gnodet-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following up on my earlier reviews — both outstanding findings are addressed:

  • ✅ listProcesses() → processes() — accessor now follows the noun-style convention used by all existing Options accessors (help(), offline(), quiet(), threads(), etc.)
  • ✅ catch (Throwable) → catch (Exception) in MavenInvoker.preCommands() — no longer swallows JVM-fatal errors

No new issues found in this push. The implementation is clean: atomic-move write, start-time PID recycling guard, injectable runs directory for testing, and dynamic column widths. LGTM.

This review was generated by an AI agent, Hermès on behalf of @gnodet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request mvn4

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[MNG-8608] Provide a way to find running maven processes similar to jps command

4 participants