Skip to content

Commit c6d4df6

Browse files
[MNG-8678] Concurrent executor ignores java.lang.Error subclasses
Closes #10415 Widen catch blocks in ConcurrentLifecycleStarter from Exception to Throwable so that Error subclasses thrown during build steps are properly recorded in the build result instead of being silently swallowed.
1 parent 1991811 commit c6d4df6

3 files changed

Lines changed: 287 additions & 11 deletions

File tree

‎impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java‎

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -401,9 +401,9 @@ private void processStep(BuildStep step) {
401401
try {
402402
executeStep(step);
403403
executePlan();
404-
} catch (Exception e) {
404+
} catch (Throwable e) {
405405
step.status.compareAndSet(SKIPPED, FAILED);
406-
// Store the exception in the step for handling in the TEARDOWN phase
406+
// Store the failure in the step for handling in the TEARDOWN phase
407407
step.exception = e;
408408
logger.debug("Stored exception for step {} to be handled in TEARDOWN phase", step, e);
409409
// Let the scheduler handle after:* phases and TEARDOWN in the next cycle
@@ -438,10 +438,10 @@ private void processStep(BuildStep step) {
438438
}
439439
}
440440
executePlan();
441-
} catch (Exception e) {
441+
} catch (Throwable e) {
442442
step.status.compareAndSet(SCHEDULED, FAILED);
443443

444-
// Store the exception in the step for handling in the TEARDOWN phase
444+
// Store the failure in the step for handling in the TEARDOWN phase
445445
step.exception = e;
446446
logger.debug("Stored exception for step {} to be handled in TEARDOWN phase", step, e);
447447

@@ -525,7 +525,7 @@ private void executeStep(BuildStep step) throws IOException, LifecycleExecutionE
525525
List<Throwable> failures = null;
526526
boolean allWorkExecuted = true;
527527
for (BuildStep projectStep : plan.steps(step.project).toList()) {
528-
Exception exception = projectStep.exception;
528+
Throwable exception = projectStep.exception;
529529
if (exception != null) {
530530
if (failures == null) {
531531
failures = new ArrayList<>();
@@ -560,7 +560,7 @@ private void executeStep(BuildStep step) throws IOException, LifecycleExecutionE
560560
failure = new LifecycleExecutionException("Error building project");
561561
failures.forEach(failure::addSuppressed);
562562
}
563-
handleBuildError(reactorContext, session, step.project, failure);
563+
handleBuildError(reactorContext, session, step.project, failure, isFatal(failures));
564564
} else if (projectStarted && allWorkExecuted) {
565565
// If there were no failures, report success
566566
projectExecutionListener.afterProjectExecutionSuccess(
@@ -593,6 +593,18 @@ private void executeStep(BuildStep step) throws IOException, LifecycleExecutionE
593593
step.status.compareAndSet(SCHEDULED, EXECUTED);
594594
}
595595

596+
/**
597+
* Tells whether any of the failures collected for a project must halt the build. Several failures are
598+
* reported through a wrapper, and a wrapper is always a checked exception, so an {@link Error} among
599+
* them can only be seen by looking at the failures themselves.
600+
*
601+
* @param failures The failures collected for a single project
602+
* @return {@code true} if the build must be halted
603+
*/
604+
private static boolean isFatal(List<Throwable> failures) {
605+
return failures.stream().anyMatch(t -> t instanceof RuntimeException || !(t instanceof Exception));
606+
}
607+
596608
private void attachToThread(BuildStep step) {
597609
BuildPlanExecutor.attachToThread(step.project);
598610
session.setCurrentProject(step.project);
@@ -863,13 +875,16 @@ private String getResolvedPhase(String phase) {
863875
* @param buildContext The reactor context
864876
* @param session The Maven session
865877
* @param mavenProject The project that failed
866-
* @param t The exception that caused the failure
878+
* @param t The exception that caused the failure, possibly a wrapper around several failures
879+
* @param fatal Whether the failure must halt the build. This cannot be read off {@code t}, because a
880+
* wrapper around several failures hides what is inside it. See {@link #isFatal(List)}.
867881
*/
868882
protected void handleBuildError(
869883
final ReactorContext buildContext,
870884
final MavenSession session,
871885
final MavenProject mavenProject,
872-
Throwable t) {
886+
Throwable t,
887+
boolean fatal) {
873888
// record the error and mark the project as failed
874889
Clock clock = getClock(mavenProject);
875890
buildContext.getResult().addException(t);
@@ -878,12 +893,12 @@ protected void handleBuildError(
878893
.addBuildSummary(new BuildFailure(mavenProject, clock.execTime(), clock.wallTime(), t));
879894

880895
// notify listeners about "soft" project build failures only
881-
if (t instanceof Exception exception && !(t instanceof RuntimeException)) {
896+
if (!fatal && t instanceof Exception exception) {
882897
eventCatapult.fire(ExecutionEvent.Type.ProjectFailed, session, null, exception);
883898
}
884899

885900
// reactor failure modes
886-
if (t instanceof RuntimeException || !(t instanceof Exception)) {
901+
if (fatal) {
887902
// fail fast on RuntimeExceptions, Errors and "other" Throwables
888903
// assume these are system errors and further build is meaningless
889904
buildContext.getReactorBuildStatus().halt();

‎impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildStep.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public class BuildStep {
6161
final Collection<BuildStep> successors = new HashSet<>();
6262
final AtomicInteger status = new AtomicInteger();
6363
final AtomicBoolean skip = new AtomicBoolean();
64-
volatile Exception exception;
64+
volatile Throwable exception;
6565

6666
public BuildStep(String name, MavenProject project, Lifecycle.Phase phase) {
6767
this.name = Objects.requireNonNull(name, "name cannot be null");
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.maven.lifecycle.internal.concurrent;
20+
21+
import java.util.Collections;
22+
import java.util.List;
23+
import java.util.Map;
24+
import java.util.function.Consumer;
25+
26+
import org.apache.maven.api.Lifecycle;
27+
import org.apache.maven.execution.DefaultMavenExecutionRequest;
28+
import org.apache.maven.execution.DefaultMavenExecutionResult;
29+
import org.apache.maven.execution.MavenExecutionRequest;
30+
import org.apache.maven.execution.MavenSession;
31+
import org.apache.maven.execution.ProjectDependencyGraph;
32+
import org.apache.maven.execution.ProjectExecutionEvent;
33+
import org.apache.maven.execution.ProjectExecutionListener;
34+
import org.apache.maven.internal.impl.DefaultLifecycleRegistry;
35+
import org.apache.maven.internal.transformation.TransformerManager;
36+
import org.apache.maven.lifecycle.LifecycleExecutionException;
37+
import org.apache.maven.lifecycle.internal.LifecycleTask;
38+
import org.apache.maven.lifecycle.internal.ReactorBuildStatus;
39+
import org.apache.maven.lifecycle.internal.ReactorContext;
40+
import org.apache.maven.lifecycle.internal.TaskSegment;
41+
import org.apache.maven.lifecycle.internal.stub.ExecutionEventCatapultStub;
42+
import org.apache.maven.project.MavenProject;
43+
import org.eclipse.aether.DefaultRepositorySystemSession;
44+
import org.eclipse.aether.RepositorySystemSession;
45+
import org.eclipse.aether.deployment.DeployRequest;
46+
import org.eclipse.aether.installation.InstallRequest;
47+
import org.junit.jupiter.api.Test;
48+
49+
import static org.junit.jupiter.api.Assertions.assertEquals;
50+
import static org.junit.jupiter.api.Assertions.assertSame;
51+
import static org.junit.jupiter.api.Assertions.assertTrue;
52+
53+
class BuildPlanExecutorTest {
54+
55+
/**
56+
* A build step that throws an {@link Error} must be reported as a build failure, the same way the
57+
* single threaded builder reports it. Otherwise the build ends with no exception at all and Maven
58+
* prints BUILD SUCCESS while nothing was built.
59+
*/
60+
@Test
61+
void errorThrownByBuildStepIsRecordedAsBuildFailure() throws Exception {
62+
Error thrown = new NoClassDefFoundError("some/Class");
63+
MavenProject project = newProject();
64+
MavenSession session = newSession(project);
65+
66+
execute(session, project, event -> {
67+
throw thrown;
68+
});
69+
70+
List<Throwable> exceptions = session.getResult().getExceptions();
71+
assertEquals(1, exceptions.size(), "expected the error to be recorded, but got: " + exceptions);
72+
assertSame(thrown, exceptions.get(0));
73+
assertTrue(session.getResult().getBuildSummary(project) instanceof org.apache.maven.execution.BuildFailure);
74+
}
75+
76+
/**
77+
* The same for an exception, which already worked. This pins the existing behaviour so the widened
78+
* catch does not change it.
79+
*/
80+
@Test
81+
void exceptionThrownByBuildStepIsRecordedAsBuildFailure() throws Exception {
82+
RuntimeException thrown = new IllegalStateException("nope");
83+
MavenProject project = newProject();
84+
MavenSession session = newSession(project);
85+
86+
execute(session, project, event -> {
87+
throw thrown;
88+
});
89+
90+
List<Throwable> exceptions = session.getResult().getExceptions();
91+
assertEquals(1, exceptions.size(), "expected the exception to be recorded, but got: " + exceptions);
92+
assertSame(thrown, exceptions.get(0));
93+
assertTrue(session.getResult().getBuildSummary(project) instanceof org.apache.maven.execution.BuildFailure);
94+
}
95+
96+
/**
97+
* A project can end up with more than one failure: when a build step fails, the matching after:* step is
98+
* still run for cleanup and may fail on its own. Those failures are reported through a wrapper exception,
99+
* and the wrapper is a checked exception, so reading the severity off the wrapper hides the {@link Error}
100+
* that is inside it. A cleanup step failing after an Error must not downgrade the build from "halt" to a
101+
* plain per-project failure.
102+
*/
103+
@Test
104+
void errorIsStillFatalWhenASecondFailureJoinsIt() throws Exception {
105+
Error thrown = new NoClassDefFoundError("some/Class");
106+
MavenProject project = newProject();
107+
MavenSession session = newSession(project);
108+
// with fail-fast the build halts whatever happens, so the downgrade is only observable with fail-at-end
109+
session.getRequest().setReactorFailureBehavior(MavenExecutionRequest.REACTOR_FAIL_AT_END);
110+
111+
ReactorContext reactorContext = execute(
112+
session,
113+
project,
114+
event -> {
115+
throw thrown;
116+
},
117+
plan -> {
118+
BuildStep cleanup = plan.step(project, Lifecycle.AFTER + "validate")
119+
.orElseThrow(() -> new IllegalStateException("no after:validate step in the plan"));
120+
// stands in for the cleanup step failing after the Error, the way processStep records it
121+
cleanup.exception = new LifecycleExecutionException("cleanup failed");
122+
});
123+
124+
assertTrue(
125+
reactorContext.getReactorBuildStatus().isHalted(),
126+
"an Error must halt the reactor even when a second failure is recorded for the same project, but"
127+
+ " the build was not halted; recorded exceptions: "
128+
+ session.getResult().getExceptions());
129+
}
130+
131+
private ReactorContext execute(MavenSession session, MavenProject project, BeforeProjectExecution listener)
132+
throws Exception {
133+
ReactorContext reactorContext = newReactorContext(session);
134+
newExecutor(listener).execute(session, reactorContext, List.of(newTaskSegment()));
135+
return reactorContext;
136+
}
137+
138+
/**
139+
* Same, but the plan is handed to {@code planCustomizer} after it is created and before it is executed.
140+
* A step that runs no mojo cannot be made to fail from the outside, so this is the only way to put a
141+
* second failure on the project.
142+
*/
143+
private ReactorContext execute(
144+
MavenSession session,
145+
MavenProject project,
146+
BeforeProjectExecution listener,
147+
Consumer<BuildPlan> planCustomizer)
148+
throws Exception {
149+
ReactorContext reactorContext = newReactorContext(session);
150+
try (BuildPlanExecutor.BuildContext context =
151+
newExecutor(listener).new BuildContext(session, reactorContext, List.of(newTaskSegment()))) {
152+
planCustomizer.accept(context.plan);
153+
context.execute();
154+
}
155+
return reactorContext;
156+
}
157+
158+
private ReactorContext newReactorContext(MavenSession session) {
159+
return new ReactorContext(
160+
session.getResult(),
161+
Thread.currentThread().getContextClassLoader(),
162+
new ReactorBuildStatus(session.getProjectDependencyGraph()));
163+
}
164+
165+
private TaskSegment newTaskSegment() {
166+
TaskSegment taskSegment = new TaskSegment(false);
167+
taskSegment.getTasks().add(new LifecycleTask("validate"));
168+
return taskSegment;
169+
}
170+
171+
private BuildPlanExecutor newExecutor(ProjectExecutionListener listener) {
172+
return new BuildPlanExecutor(
173+
null,
174+
new ExecutionEventCatapultStub(),
175+
List.of(listener),
176+
new NoopTransformerManager(),
177+
new BuildPlanLogger(),
178+
Map.of(),
179+
null,
180+
null,
181+
new DefaultLifecycleRegistry(Collections.emptyList()));
182+
}
183+
184+
private MavenProject newProject() {
185+
MavenProject result = new MavenProject();
186+
result.setArtifactId("a");
187+
result.setCollectedProjects(List.of());
188+
return result;
189+
}
190+
191+
private MavenSession newSession(MavenProject project) {
192+
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
193+
request.setGoals(List.of("validate"));
194+
MavenSession result = new MavenSession(
195+
null, new DefaultRepositorySystemSession(h -> false), request, new DefaultMavenExecutionResult());
196+
result.setProjectDependencyGraph(new SingleProjectDependencyGraph(project));
197+
result.setProjects(List.of(project));
198+
return result;
199+
}
200+
201+
private static final class SingleProjectDependencyGraph implements ProjectDependencyGraph {
202+
203+
private final List<MavenProject> projects;
204+
205+
private SingleProjectDependencyGraph(MavenProject project) {
206+
this.projects = List.of(project);
207+
}
208+
209+
@Override
210+
public List<MavenProject> getAllProjects() {
211+
return projects;
212+
}
213+
214+
@Override
215+
public List<MavenProject> getSortedProjects() {
216+
return projects;
217+
}
218+
219+
@Override
220+
public List<MavenProject> getDownstreamProjects(MavenProject project, boolean transitive) {
221+
return List.of();
222+
}
223+
224+
@Override
225+
public List<MavenProject> getUpstreamProjects(MavenProject project, boolean transitive) {
226+
return List.of();
227+
}
228+
}
229+
230+
private static final class NoopTransformerManager implements TransformerManager {
231+
232+
@Override
233+
public InstallRequest remapInstallArtifacts(RepositorySystemSession session, InstallRequest request) {
234+
return request;
235+
}
236+
237+
@Override
238+
public DeployRequest remapDeployArtifacts(RepositorySystemSession session, DeployRequest request) {
239+
return request;
240+
}
241+
242+
@Override
243+
public void injectTransformedArtifacts(RepositorySystemSession repositorySession, MavenProject project) {}
244+
}
245+
246+
@FunctionalInterface
247+
private interface BeforeProjectExecution extends ProjectExecutionListener {
248+
249+
@Override
250+
void beforeProjectExecution(ProjectExecutionEvent event);
251+
252+
@Override
253+
default void beforeProjectLifecycleExecution(ProjectExecutionEvent event) {}
254+
255+
@Override
256+
default void afterProjectExecutionSuccess(ProjectExecutionEvent event) {}
257+
258+
@Override
259+
default void afterProjectExecutionFailure(ProjectExecutionEvent event) {}
260+
}
261+
}

0 commit comments

Comments
 (0)