上篇已经说到有向任务图已经构建完毕,接下来就是对任务进行执行了
// DefaultGradleLauncher.java
private void runWork() {
if (stage != Stage.TaskGraph) {
throw new IllegalStateException("Cannot execute tasks: current stage = " + stage);
}
List<Throwable> taskFailures = new ArrayList<>();
buildExecuter.execute(gradle, taskFailures);
if (!taskFailures.isEmpty()) {
throw new MultipleBuildFailures(taskFailures);
}
stage = Stage.RunTasks;
}
buildExecuter对象来源于下图的方法调用,调用层级是由外到内,层层递进关系
BuildOperationFiringBuildWorkerExecutor、DeprecateUndefinedBuildWorkExecutor、IncludedBuildLifecycleBuildWorkExecutor基本都是转发,无决定意义,直接跳过,直接到DefaultBuildWorkExecutor
最终还是依次执行executionActions容器对象,上面可以看到构造器传入了二个action,只要分析它就好了
执行taskGraph中的task前会执行二个action
针对dry-run特殊处理,主要就是一些打印输出
/**
* A {@link org.gradle.execution.BuildExecutionAction} that disables all selected tasks before they are executed.
*/
public class DryRunBuildExecutionAction implements BuildExecutionAction {
private final StyledTextOutputFactory textOutputFactory;
public DryRunBuildExecutionAction(StyledTextOutputFactory textOutputFactory) {
this.textOutputFactory = textOutputFactory;
}
@Override
public void execute(BuildExecutionContext context, Collection<? super Throwable> taskFailures) {
GradleInternal gradle = context.getGradle();
if (gradle.getStartParameter().isDryRun()) {
for (Task task : gradle.getTaskGraph().getAllTasks()) {
textOutputFactory.create(DryRunBuildExecutionAction.class)
.append(((TaskInternal) task).getIdentityPath().getPath())
.append(" ")
.style(StyledTextOutput.Style.ProgressStatus)
.append("SKIPPED")
.println();
}
} else {
context.proceed();
}
}
}
主要是绑定规则,具体不太清楚干什么用的
public class SelectedTaskExecutionAction implements BuildExecutionAction {
@Override
public void execute(BuildExecutionContext context, Collection<? super Throwable> taskFailures) {
GradleInternal gradle = context.getGradle();
TaskExecutionGraphInternal taskGraph = gradle.getTaskGraph();
// 设置当任务执行失败是,是否继续下去
if (gradle.getStartParameter().isContinueOnFailure()) {
taskGraph.setContinueOnFailure(true);
}
bindAllReferencesOfProject(taskGraph);
// 执行任务(DefaultTaskExecutionGraph)
taskGraph.execute(taskFailures);
}
private void bindAllReferencesOfProject(TaskExecutionGraph graph) {
Set<Project> seen = Sets.newHashSet();
for (Task task : graph.getAllTasks()) {
if (seen.add(task.getProject())) {
ProjectInternal projectInternal = (ProjectInternal) task.getProject();
//绑定规则?
projectInternal.bindAllModelRules();
}
}
}
}
DefaultTaskExecutionGraph
@Override
public void execute(Collection<? super Throwable> failures) {
if (!hasFiredWhenReady) {
throw new IllegalStateException("Task graph should be populated before execution starts.");
}
try (ProjectExecutionServiceRegistry projectExecutionServices = new ProjectExecutionServiceRegistry(globalServices)) {
executeWithServices(projectExecutionServices, failures);
}
}
private void executeWithServices(ProjectExecutionServiceRegistry projectExecutionServices, Collection<? super Throwable> failures) {
Timer clock = Time.startTimer();
try {
// DefaultPlanExecutor
planExecutor.process(
executionPlan,
failures,
new BuildOperationAwareExecutionAction(
buildOperationExecutor.getCurrentOperation(),
new InvokeNodeExecutorsAction(nodeExecutors, projectExecutionServices)
)
);
LOGGER.debug("Timing: Executing the DAG took " + clock.getElapsed());
} finally {
coordinationService.withStateLock(resourceLockState -> {
executionPlan.clear();
return ResourceLockState.Disposition.FINISHED;
});
}
}
后面的调用层级非常深,最终会经过多个任务执行器()执行
EventFiringTaskExecuter:事项通知发送包括beforeExecute、afterExecute
CatchExceptionTaskExecuter:异常处理
SkipOnlyIfTaskExecuter: 针对onlyif特殊谓词的task直接skip onlyif官方说明
SkipTaskWithNoActionsExecuter:无action的task不会执行
ResolveTaskExecutionModeExecuter:设置任务执行模式(5种),执行会有差异
FinalizePropertiesTaskExecuter:任务预处理,结束事件调用
CleanupStaleOutputsExecuter:Clean stale outputs
ExecuteActionsTaskExecuter:任务执行
private void finishBuild(String action, @Nullable Throwable stageFailure) {
if (stage == Stage.Finished) {
return;
}
RuntimeException reportableFailure = stageFailure == null ? null : exceptionAnalyser.transform(stageFailure);
BuildResult buildResult = new BuildResult(action, gradle, reportableFailure);
List<Throwable> failures = new ArrayList<>();
// 任务执行器对应的线程回收
includedBuildControllers.finishBuild(failures);
// 相关回调调用
try {
buildListener.buildFinished(buildResult);
buildFinishedListener.buildFinished((GradleInternal) buildResult.getGradle());
} catch (Throwable t) {
failures.add(t);
}
stage = Stage.Finished;
if (failures.isEmpty() && reportableFailure != null) {
throw reportableFailure;
}
if (!failures.isEmpty()) {
if (stageFailure instanceof MultipleBuildFailures) {
failures.addAll(0, ((MultipleBuildFailures) stageFailure).getCauses());
} else if (stageFailure != null) {
failures.add(0, stageFailure);
}
throw exceptionAnalyser.transform(new MultipleBuildFailures(failures));
}
}
任务执行结束阶段
之此gradle系列篇已初探完毕,我们对gradle整个生命周期的内部实现,应该比之前有更深入的理解😄