-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
DefaultBuildLifecycleController.java
426 lines (374 loc) · 16.9 KB
/
DefaultBuildLifecycleController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/*
* Copyright 2021 the original author or authors.
*
* Licensed 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.gradle.internal.build;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import org.gradle.BuildListener;
import org.gradle.BuildResult;
import org.gradle.api.NonNullApi;
import org.gradle.api.Task;
import org.gradle.api.internal.GradleInternal;
import org.gradle.api.internal.SettingsInternal;
import org.gradle.api.internal.artifacts.DefaultBuildIdentifier;
import org.gradle.api.internal.project.HoldsProjectState;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.internal.project.ProjectState;
import org.gradle.api.problems.internal.Problem;
import org.gradle.api.specs.Spec;
import org.gradle.execution.BuildWorkExecutor;
import org.gradle.execution.EntryTaskSelector;
import org.gradle.execution.TaskSelection;
import org.gradle.execution.plan.BuildWorkPlan;
import org.gradle.execution.plan.ExecutionPlan;
import org.gradle.execution.plan.FinalizedExecutionPlan;
import org.gradle.execution.plan.LocalTaskNode;
import org.gradle.execution.plan.QueryableExecutionPlan;
import org.gradle.execution.plan.ScheduledWork;
import org.gradle.initialization.exception.ExceptionAnalyser;
import org.gradle.internal.Describables;
import org.gradle.internal.Pair;
import org.gradle.internal.model.StateTransitionController;
import org.gradle.internal.model.StateTransitionControllerFactory;
import org.gradle.util.Path;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.gradle.util.Path.path;
@SuppressWarnings("deprecation")
public class DefaultBuildLifecycleController implements BuildLifecycleController {
private enum State implements StateTransitionController.State {
// Configuring the build, can access build model
Configure,
// Scheduling tasks for execution
TaskSchedule,
ReadyToRun,
BuildFinishHooks,
ReadyToReset,
// build has finished and should do no further work
Finished
}
private static final ImmutableList<State> CONFIGURATION_STATES = ImmutableList.of(State.Configure, State.TaskSchedule, State.ReadyToRun);
private final ExceptionAnalyser exceptionAnalyser;
private final BuildListener buildListener;
private final BuildModelLifecycleListener buildModelLifecycleListener;
private final BuildWorkPreparer workPreparer;
private final BuildWorkExecutor workExecutor;
private final BuildToolingModelControllerFactory toolingModelControllerFactory;
private final BuildModelController modelController;
private final StateTransitionController<State> state;
private final Multimap<Throwable, Problem> problems;
private final GradleInternal gradle;
private boolean hasTasks;
private boolean hasFiredBeforeModelDiscarded;
public DefaultBuildLifecycleController(
GradleInternal gradle,
BuildModelController buildModelController,
ExceptionAnalyser exceptionAnalyser,
BuildListener buildListener,
BuildModelLifecycleListener buildModelLifecycleListener,
BuildWorkPreparer workPreparer,
BuildWorkExecutor workExecutor,
BuildToolingModelControllerFactory toolingModelControllerFactory,
StateTransitionControllerFactory controllerFactory,
Multimap<Throwable, Problem> problems
) {
this.gradle = gradle;
this.modelController = buildModelController;
this.exceptionAnalyser = exceptionAnalyser;
this.buildListener = buildListener;
this.workPreparer = workPreparer;
this.workExecutor = workExecutor;
this.buildModelLifecycleListener = buildModelLifecycleListener;
this.toolingModelControllerFactory = toolingModelControllerFactory;
this.state = controllerFactory.newController(Describables.of("state of", targetBuild().getDisplayName()), State.Configure);
this.problems = problems;
}
@Override
public GradleInternal getGradle() {
// Should not ignore other threads, however it is currently possible for this to be queried by tasks at execution time (that is, when another thread is
// transitioning the task graph state). Instead, it may be better to:
// - have the threads use some specific immutable view of the build model state instead of requiring direct access to the build model.
// - not have a thread blocked around task execution, so that other threads can use the build model.
// - maybe split the states into one for the build model and one for the task graph.
state.assertNotInState(State.Finished);
return gradle;
}
@Override
public void loadSettings() {
state.notInState(State.Finished, modelController::getLoadedSettings);
}
@Override
public <T> T withSettings(Function<? super SettingsInternal, T> action) {
return state.notInState(State.Finished, () -> action.apply(modelController.getLoadedSettings()));
}
@Override
public void configureProjects() {
state.notInState(State.Finished, modelController::getConfiguredModel);
}
@Override
public <T> T withProjectsConfigured(Function<? super GradleInternal, T> action) {
return state.notInState(State.Finished, () -> action.apply(modelController.getConfiguredModel()));
}
@Override
public void resetModel() {
state.restart(State.ReadyToReset, State.Configure, () -> {
gradle.resetState();
for (HoldsProjectState service : gradle.getServices().getAll(HoldsProjectState.class)) {
service.discardAll();
}
});
}
@Override
public ExecutionResult<Void> beforeModelReset() {
return state.transition(CONFIGURATION_STATES, State.ReadyToReset, failures -> fireBeforeModelDiscarded(false));
}
@Override
public ExecutionResult<Void> beforeModelDiscarded(boolean failed) {
return state.transition(State.BuildFinishHooks, State.Finished, failures -> fireBeforeModelDiscarded(failed));
}
private ExecutionResult<Void> fireBeforeModelDiscarded(boolean failed) {
if (hasFiredBeforeModelDiscarded) {
return ExecutionResult.succeeded();
} else {
hasFiredBeforeModelDiscarded = true;
return ExecutionResult.maybeFailing(() -> buildModelLifecycleListener.beforeModelDiscarded(gradle, failed));
}
}
@Override
public GradleInternal getConfiguredBuild() {
// Should not ignore other threads. See above.
return state.notInStateIgnoreOtherThreads(State.Finished, modelController::getConfiguredModel);
}
@Override
public void prepareToScheduleTasks() {
state.maybeTransition(State.Configure, State.TaskSchedule, () -> {
hasTasks = true;
modelController.prepareToScheduleTasks();
});
}
@Override
public BuildWorkPlan newWorkGraph() {
ExecutionPlan plan = workPreparer.newExecutionPlan();
return new DefaultBuildWorkPlan(this, plan);
}
@Override
public void populateWorkGraph(BuildWorkPlan plan, Consumer<? super WorkGraphBuilder> action) {
DefaultBuildWorkPlan workPlan = unpack(plan);
workPlan.empty = false;
state.inState(State.TaskSchedule, () -> workPreparer.populateWorkGraph(gradle, workPlan.plan, dest -> action.accept(new DefaultWorkGraphBuilder(dest))));
}
@Override
public void finalizeWorkGraph(BuildWorkPlan plan) {
DefaultBuildWorkPlan workPlan = unpack(plan);
if (workPlan.empty) {
return;
}
state.transition(State.TaskSchedule, State.ReadyToRun, () -> {
for (Consumer<LocalTaskNode> handler : workPlan.handlers) {
workPlan.plan.onComplete(handler);
}
workPlan.finalizedPlan = workPreparer.finalizeWorkGraph(gradle, workPlan.plan);
});
}
@NonNullApi
private class EntryTaskSelectorContext implements EntryTaskSelector.Context {
@Override
public TaskSelection getSelection(String taskPath) {
// We assume taskPath is valid since the selector has been used before
return selectionOf(path(taskPath));
}
private TaskSelection selectionOf(Path taskPath) {
Path taskProjectPath = taskPath.getParent();
assert taskProjectPath != null;
ProjectInternal taskProject = resolveProject(taskProjectPath);
if (taskProject != null) {
String taskName = taskPath.getName();
return new TaskSelection(
taskProject.getPath(),
taskName,
tasks -> tasks.add(taskProject.getTasks().getByName(taskName))
);
}
return new TaskSelection(null, null, tasks -> {});
}
@Override
public GradleInternal getGradle() {
return gradle;
}
@Nullable
private ProjectInternal resolveProject(Path path) {
assert path.isAbsolute();
// Try to resolve the path as "<included-build-path>:<project-path>"
Pair<Path, BuildState> includedBuildPrefix = resolveIncludedBuildPrefixOf(path);
if (includedBuildPrefix != null) {
Path includedBuildPath = includedBuildPrefix.left;
BuildState includedBuild = includedBuildPrefix.right;
Path projectPath = path.removeFirstSegments(includedBuildPath.segmentCount());
return findProjectOf(includedBuild, projectPath);
}
return findProjectOf(targetBuild(), path);
}
/**
* Finds the longest {@code path} prefix that identifies an included build and returns a pair
* with the matching {@code path} prefix and {@link BuildState included build reference}.
*
* @return {@code null} if no {@code path} prefix identifying an included build is found
*/
@Nullable
private Pair<Path, BuildState> resolveIncludedBuildPrefixOf(Path path) {
Path resolvedPath = null;
BuildState resolvedBuild = null;
int prefixLength = 1;
while (prefixLength <= path.segmentCount()) {
Path candidatePath = path.takeFirstSegments(prefixLength);
BuildState existingBuild = findBuild(candidatePath);
if (existingBuild == null) {
break;
}
resolvedPath = candidatePath;
resolvedBuild = existingBuild;
prefixLength++;
}
return resolvedPath != null
? Pair.of(resolvedPath, resolvedBuild)
: null;
}
@Nullable
private ProjectInternal findProjectOf(BuildState build, Path projectPath) {
ProjectState project = build.getProjects().findProject(projectPath);
return project != null
? project.getMutableModel()
: null;
}
@Nullable
private BuildState findBuild(Path buildPath) {
return getBuildStateRegistry().findBuild(new DefaultBuildIdentifier(buildPath));
}
private BuildStateRegistry getBuildStateRegistry() {
return gradle.getServices().get(BuildStateRegistry.class);
}
}
@Override
public ExecutionResult<Void> executeTasks(BuildWorkPlan plan) {
// Execute tasks and transition back to "configure", as this build may run more tasks;
DefaultBuildWorkPlan workPlan = unpack(plan);
if (workPlan.empty) {
return ExecutionResult.succeeded();
}
return state.tryTransition(State.ReadyToRun, State.Configure, () -> {
List<BiConsumer<EntryTaskSelector.Context, QueryableExecutionPlan>> finalizations = workPlan.finalizations;
if (!finalizations.isEmpty()) {
EntryTaskSelectorContext context = new EntryTaskSelectorContext();
for (BiConsumer<EntryTaskSelector.Context, QueryableExecutionPlan> finalization : finalizations) {
finalization.accept(context, workPlan.finalizedPlan.getContents());
}
workPlan.finalizations.clear();
}
return workExecutor.execute(gradle, workPlan.finalizedPlan);
});
}
private DefaultBuildWorkPlan unpack(BuildWorkPlan plan) {
DefaultBuildWorkPlan workPlan = (DefaultBuildWorkPlan) plan;
if (workPlan.owner != this) {
throw new IllegalArgumentException("Unexpected plan owner.");
}
return workPlan;
}
@Override
public <T> T withToolingModels(Function<? super BuildToolingModelController, T> action) {
return action.apply(toolingModelControllerFactory.createController(targetBuild(), this));
}
private BuildState targetBuild() {
return gradle.getOwner();
}
@Override
public ExecutionResult<Void> finishBuild(@Nullable Throwable failure) {
return state.transition(CONFIGURATION_STATES, State.BuildFinishHooks, stageFailures -> {
// Fire the build finished events even if nothing has happened to this build, because quite a lot of internal infrastructure
// adds listeners and expects to see a build finished event. Infrastructure should not be using the public listener types
// In addition, they almost all should be using a build tree scoped event instead of a build scoped event
Throwable reportableFailure = failure;
if (reportableFailure == null && !stageFailures.getFailures().isEmpty()) {
reportableFailure = exceptionAnalyser.transform(stageFailures.getFailures());
}
Collection<Problem> problemCollection = problems.get(failure);
BuildResult buildResult = new BuildResult(hasTasks ? "Build" : "Configure", gradle, reportableFailure, problemCollection);
return ExecutionResult.maybeFailing(() -> buildListener.buildFinished(buildResult));
});
}
/**
* <p>Adds a listener to this build instance. The listener is notified of events which occur during the execution of the build.
* See {@link org.gradle.api.invocation.Gradle#addListener(Object)} for supported listener types.</p>
*
* @param listener The listener to add. Has no effect if the listener has already been added.
*/
@Override
public void addListener(Object listener) {
getGradle().addListener(listener);
}
private static class DefaultBuildWorkPlan implements BuildWorkPlan {
private final DefaultBuildLifecycleController owner;
private final ExecutionPlan plan;
private final List<Consumer<LocalTaskNode>> handlers = new ArrayList<>();
private final List<BiConsumer<EntryTaskSelector.Context, QueryableExecutionPlan>> finalizations = new ArrayList<>();
private FinalizedExecutionPlan finalizedPlan;
private boolean empty = true;
public DefaultBuildWorkPlan(DefaultBuildLifecycleController owner, ExecutionPlan plan) {
this.owner = owner;
this.plan = plan;
}
@Override
public void stop() {
plan.close();
}
@Override
public void addFilter(Spec<Task> filter) {
plan.addFilter(filter);
}
@Override
public void addFinalization(BiConsumer<EntryTaskSelector.Context, QueryableExecutionPlan> finalization) {
finalizations.add(finalization);
}
@Override
public void onComplete(Consumer<LocalTaskNode> handler) {
handlers.add(handler);
}
}
private class DefaultWorkGraphBuilder implements WorkGraphBuilder {
private final ExecutionPlan plan;
public DefaultWorkGraphBuilder(ExecutionPlan plan) {
this.plan = plan;
}
@Override
public void addRequestedTasks(@Nullable EntryTaskSelector selector) {
modelController.scheduleRequestedTasks(selector, plan);
}
@Override
public void addEntryTasks(List<? extends Task> tasks) {
for (Task task : tasks) {
plan.addEntryTask(task);
}
}
@Override
public void setScheduledWork(ScheduledWork work) {
plan.setScheduledWork(work);
}
}
}