标签:
各位看官,上一篇《Spark源码分析之Stage划分》详细讲述了Spark中Stage的划分,下面,我们进入第三个阶段--Stage提交。
Stage提交阶段的主要目的就一个,就是将每个Stage生成一组Task,即TaskSet,其处理流程如下图所示:
与Stage划分阶段一样,我们还是从handleJobSubmitted()方法入手,在Stage划分阶段,包括最好的ResultStage和前面的若干ShuffleMapStage均已生成,那么顺理成章的下一步便是Stage的提交。在handleJobSubmitted()方法的最后两行代码,便是Stage提交的处理。代码如下:
- submitStage(finalStage)
-
-
- submitWaitingStages()
从代码我们可以看出,Stage提交的逻辑顺序,是由后往前,即先提交最后一个finalStage,即ResultStage,然后再提交其parent stages,但是实际物理顺序是否如此呢?我们首先看下finalStage的提交,方法submitStage()代码如下:
-
- private def submitStage(stage: Stage) {
-
-
- val jobId = activeJobForStage(stage)
-
- if (jobId.isDefined) {
-
-
- logDebug("submitStage(" + stage + ")")
-
-
-
-
-
-
- if (!waitingStages(stage) && !runningStages(stage) && !failedStages(stage)) {
-
-
- val missing = getMissingParentStages(stage).sortBy(_.id)
-
- logDebug("missing: " + missing)
- if (missing.isEmpty) {
-
-
- logInfo("Submitting " + stage + " (" + stage.rdd + "), which has no missing parents")
- submitMissingTasks(stage, jobId.get)
- } else {
-
- for (parent <- missing) {
- submitStage(parent)
- }
-
-
- waitingStages += stage
- }
- }
- } else {
-
- abortStage(stage, "No active job for stage " + stage.id, None)
- }
- }
代码逻辑比较简单。根据stage获取到jobId,如果jobId未定义,说明该stage不属于明确的Job,则调用abortStage()方法放弃该stage。如果jobId已定义的话,则需要判断该stage属于waitingStages、runningStages、failedStages中任意一个,则该stage忽略,不被处理。顾名思义,waitingStages为等待处理的stages,spark采取由后往前的顺序处理stage提交,即先处理child stage,然后再处理parent stage,所以位于waitingStages中的stage,由于其child stage尚未处理,所以必须等待,runningStages为正在运行的stages,正在运行意味着已经提交了,所以无需再提交,而最后的failedStages就是失败的stages,既然已经失败了,再提交也还是会失败,徒劳无益啊~
此时,如果stage不位于上述三个数据结构中,则可以继续执行提交流程。接下来该怎么做呢?
首先调用getMissingParentStages()方法,获取stage还没有提交的parent,即missing;如果missing为空,说明该stage要么没有parent stage,要么其parent stages都已被提交,此时该stage就可以被提交,用于提交的方法submitMissingTasks()我们稍后分析。
如果missing不为空,则说明该stage还存在尚未被提交的parent stages,那么,我们就需要遍历missing,循环提交每个stage,并将该stage添加到waitingStages中,等待其parent stages都被提交后再被提交。
我们先看下这个missing是如何获取的。进入getMissingParentStages()方法,代码如下:
- private def getMissingParentStages(stage: Stage): List[Stage] = {
-
-
- val missing = new HashSet[Stage]
-
-
- val visited = new HashSet[RDD[_]]
-
-
-
-
- val waitingForVisit = new Stack[RDD[_]]
-
-
- def visit(rdd: RDD[_]) {
-
-
- if (!visited(rdd)) {
-
- visited += rdd
-
- val rddHasUncachedPartitions = getCacheLocs(rdd).contains(Nil)
- if (rddHasUncachedPartitions) {
-
- for (dep <- rdd.dependencies) {
- dep match {
-
- case shufDep: ShuffleDependency[_, _, _] =>
-
- val mapStage = getShuffleMapStage(shufDep, stage.firstJobId)
- if (!mapStage.isAvailable) {
- missing += mapStage
- }
-
- case narrowDep: NarrowDependency[_] =>
- waitingForVisit.push(narrowDep.rdd)
- }
- }
- }
- }
- }
-
-
- waitingForVisit.push(stage.rdd)
-
- while (waitingForVisit.nonEmpty) {
- visit(waitingForVisit.pop())
- }
-
-
- missing.toList
- }
有没有些似曾相识的感觉呢?对了,和《Spark源码分析之Stage划分》一文中getParentStages()方法、getAncestorShuffleDependencies()方法结构类似,也是定义了三个数据结构和一个visit()方法。三个数据结构分别是:
1、missing:HashSet[Stage]类型,存储尚未提交的parent stages,用于最后结果的返回;
2、visited:HashSet[RDD[_]]类型,已被处理的RDD集合,位于其中的RDD不会被重复处理;
3、waitingForVisit:Stack[RDD[_]]类型,等待被处理的RDD栈,后入先出。
visit()方法的处理逻辑也比较简单,大致如下:
通过RDD是否在visited中判断RDD是否已处理,若未被处理,添加到visited中,然后循环rdd的dependencies,如果是宽依赖ShuffleDependency,调用getShuffleMapStage(),获取ShuffleMapStage(此次调用则是直接取出已生成的stage,因为划分阶段已将stage全部生成,拿来主义即可),判断该stage的isAvailable标志位,若为false,则说明该stage未被提交过,加入到missing集合,如果是窄依赖NarrowDependency,直接将RDD压入waitingForVisit栈,等待后续处理,因为窄依赖的RDD同属于同一个stage,加入waitingForVisit只是为了后续继续沿着DAG图继续往上处理。
那么,整个missing的获取就一目了然,将final stage即ResultStage的RDD压入到waitingForVisit顶部,循环处理即可得到missing。
至此,各位可能有个疑问,这个ShuffleMapStage的isAvailable为什么能决定该stage是否已被提交呢?卖个关子,后续再分析。
submitStage()方法已分析完毕,go on,我们再回归到handleJobSubmitted()方法,在调用submitStage()方法提交finalStage之后,实际上只是将最原始的parent stage提交,其它child stage均存储在了waitingStages中,那么,接下来,我们就要调用submitWaitingStages()方法提交其中的stage。代码如下:
- private def submitWaitingStages() {
-
-
- logTrace("Checking for newly runnable parent stages")
- logTrace("running: " + runningStages)
- logTrace("waiting: " + waitingStages)
- logTrace("failed: " + failedStages)
-
-
- val waitingStagesCopy = waitingStages.toArray
-
-
- waitingStages.clear()
-
-
- for (stage <- waitingStagesCopy.sortBy(_.firstJobId)) {
- submitStage(stage)
- }
- }
很简单,既然stages的顺序已经梳理正确,将waitingStages转换为数组waitingStagesCopy,针对每个stage挨个调用submitStage()方法进行提交即可。
还记得我卖的那个关子吗?ShuffleMapStage的isAvailable为什么能决定该stage是否已被提交呢?现在来解开这个谜团。首先,看下ShuffleMapStage的isAvailable是如何定义的,在ShuffleMapStage中,代码如下:
- def isAvailable: Boolean = _numAvailableOutputs == numPartitions
它是通过判断_numAvailableOutputs和numPartitions是否相等来确定stage是否已被提交(或者说准备就绪可以提交is ready)的,而numPartitions很好理解,就是stage中的全部分区数目,那么_numAvailableOutputs是什么呢?
- private[this] var _numAvailableOutputs: Int = 0
-
- def numAvailableOutputs: Int = _numAvailableOutputs
可以看出,_numAvailableOutputs就是拥有shuffle outputs的分区数量,当这个numAvailableOutputs达到numPartitions时,这个map stage也就准备好了。
那么这个_numAvailableOutputs开始时默认为0,它是在何时被赋值的呢?通篇看完ShuffleMapStage的源码,只有两个方法对_numAvailableOutputs的值做修改,代码如下:
- def addOutputLoc(partition: Int, status: MapStatus): Unit = {
- val prevList = outputLocs(partition)
- outputLocs(partition) = status :: prevList
- if (prevList == Nil) {
- _numAvailableOutputs += 1
- }
- }
-
- def removeOutputLoc(partition: Int, bmAddress: BlockManagerId): Unit = {
- val prevList = outputLocs(partition)
- val newList = prevList.filterNot(_.location == bmAddress)
- outputLocs(partition) = newList
- if (prevList != Nil && newList == Nil) {
- _numAvailableOutputs -= 1
- }
- }
什么时候调用的这个addOutputLoc()方法呢?答案就在DAGScheduler的newOrUsedShuffleStage()方法中。方法主要逻辑如下:
- if (mapOutputTracker.containsShuffle(shuffleDep.shuffleId)) {
-
-
-
- val serLocs = mapOutputTracker.getSerializedMapOutputStatuses(shuffleDep.shuffleId)
-
-
- val locs = MapOutputTracker.deserializeMapStatuses(serLocs)
-
-
- (0 until locs.length).foreach { i =>
- if (locs(i) ne null) {
-
-
- stage.addOutputLoc(i, locs(i))
- }
- }
- } else {
-
-
-
-
- logInfo("Registering RDD " + rdd.id + " (" + rdd.getCreationSite + ")")
-
-
-
- mapOutputTracker.registerShuffle(shuffleDep.shuffleId, rdd.partitions.length)
- }
这个方法在stage划分过程中,第一轮被调用,此时mapOutputTracker中并没有注册shuffle相关信息,所以走的是else分支,调用mapOutputTracker的registerShuffle()方法注册shuffle,而在stage提交过程中,第二轮被调用,此时shuffle已在mapOutputTracker中注册,则会根据shuffleId从mapOutputTracker中获取序列化的多个MapOutputStatus对象,反序列化并循环调用stage的addOutputLoc()方法,更新stage的outputLocs,并累加_numAvailableOutputs,至此,关子卖完,再有疑问,后续再慢慢分析吧。
到了这里,就不得不分析下真正提交stage的方法submitMissingTasks()了。莫慌,慢慢看,代码如下:
- private def submitMissingTasks(stage: Stage, jobId: Int) {
- logDebug("submitMissingTasks(" + stage + ")")
-
-
-
- stage.pendingPartitions.clear()
-
-
-
- val partitionsToCompute: Seq[Int] = stage.findMissingPartitions()
-
-
-
-
- if (stage.internalAccumulators.isEmpty || stage.numPartitions == partitionsToCompute.size) {
- stage.resetInternalAccumulators()
- }
-
-
-
- val properties = jobIdToActiveJob(jobId).properties
-
-
- runningStages += stage
-
-
-
-
-
-
- stage match {
-
- case s: ShuffleMapStage =>
- outputCommitCoordinator.stageStart(stage = s.id, maxPartitionId = s.numPartitions - 1)
-
- case s: ResultStage =>
- outputCommitCoordinator.stageStart(
- stage = s.id, maxPartitionId = s.rdd.partitions.length - 1)
- }
-
-
-
- val taskIdToLocations: Map[Int, Seq[TaskLocation]] = try {
- stage match {
-
- case s: ShuffleMapStage =>
- partitionsToCompute.map { id => (id, getPreferredLocs(stage.rdd, id))}.toMap
-
- case s: ResultStage =>
- val job = s.activeJob.get
- partitionsToCompute.map { id =>
- val p = s.partitions(id)
- (id, getPreferredLocs(stage.rdd, p))
- }.toMap
- }
- } catch {
- case NonFatal(e) =>
- stage.makeNewStageAttempt(partitionsToCompute.size)
- listenerBus.post(SparkListenerStageSubmitted(stage.latestInfo, properties))
- abortStage(stage, s"Task creation failed: $e\n${e.getStackTraceString}", Some(e))
- runningStages -= stage
- return
- }
-
-
- stage.makeNewStageAttempt(partitionsToCompute.size, taskIdToLocations.values.toSeq)
-
- listenerBus.post(SparkListenerStageSubmitted(stage.latestInfo, properties))
-
-
-
-
-
-
-
-
- var taskBinary: Broadcast[Array[Byte]] = null
- try {
-
-
-
-
- val taskBinaryBytes: Array[Byte] = stage match {
- case stage: ShuffleMapStage =>
-
- closureSerializer.serialize((stage.rdd, stage.shuffleDep): AnyRef).array()
- case stage: ResultStage =>
-
- closureSerializer.serialize((stage.rdd, stage.func): AnyRef).array()
- }
-
-
- taskBinary = sc.broadcast(taskBinaryBytes)
-
- } catch {
-
- case e: NotSerializableException =>
- abortStage(stage, "Task not serializable: " + e.toString, Some(e))
- runningStages -= stage
-
-
- return
- case NonFatal(e) =>
- abortStage(stage, s"Task serialization failed: $e\n${e.getStackTraceString}", Some(e))
- runningStages -= stage
- return
- }
-
-
- val tasks: Seq[Task[_]] = try {
- stage match {
-
- case stage: ShuffleMapStage =>
- partitionsToCompute.map { id =>
-
- val locs = taskIdToLocations(id)
- val part = stage.rdd.partitions(id)
-
- new ShuffleMapTask(stage.id, stage.latestInfo.attemptId,
- taskBinary, part, locs, stage.internalAccumulators)
- }
-
- case stage: ResultStage =>
- val job = stage.activeJob.get
- partitionsToCompute.map { id =>
- val p: Int = stage.partitions(id)
- val part = stage.rdd.partitions(p)
- val locs = taskIdToLocations(id)
-
- new ResultTask(stage.id, stage.latestInfo.attemptId,
- taskBinary, part, locs, id, stage.internalAccumulators)
- }
- }
- } catch {
- case NonFatal(e) =>
- abortStage(stage, s"Task creation failed: $e\n${e.getStackTraceString}", Some(e))
- runningStages -= stage
- return
- }
-
-
- if (tasks.size > 0) {
- logInfo("Submitting " + tasks.size + " missing tasks from " + stage + " (" + stage.rdd + ")")
-
-
- stage.pendingPartitions ++= tasks.map(_.partitionId)
-
- logDebug("New pending partitions: " + stage.pendingPartitions)
-
-
- taskScheduler.submitTasks(new TaskSet(
- tasks.toArray, stage.id, stage.latestInfo.attemptId, jobId, properties))
-
- stage.latestInfo.submissionTime = Some(clock.getTimeMillis())
- } else {
-
-
-
- markStageAsFinished(stage, None)
-
- val debugString = stage match {
- case stage: ShuffleMapStage =>
- s"Stage ${stage} is actually done; " +
- s"(available: ${stage.isAvailable}," +
- s"available outputs: ${stage.numAvailableOutputs}," +
- s"partitions: ${stage.numPartitions})"
- case stage : ResultStage =>
- s"Stage ${stage} is actually done; (partitions: ${stage.numPartitions})"
- }
- logDebug(debugString)
- }
- }
submitMissingTasks()方法,最主要的就是针对每个stage生成一组Tasks,即TaskSet,并调用TaskScheduler的submitTasks()方法提交tasks。它主要做了以下几件事情:
1、清空stage的pendingPartitions;
2、首先确定该stage需要计算的分区ID索引,保存至partitionsToCompute;
3、将stage加入到runningStages中,标记stage正在运行,与上面的阐述对应;
4、开启一个stage时,需要调用outputCommitCoordinator的stageStart()方法;
5、创建一个Map:taskIdToLocations,存储的是id->Seq[TaskLocation]的映射关系,并对stage中指定RDD的每个分区获取位置信息,映射成id->Seq[TaskLocation]的关系;
6、标记新的stage attempt,并发送一个SparkListenerStageSubmitted事件;
7、对stage进行序列化并广播,如果是ShuffleMapStage,序列化rdd和shuffleDep,如果是ResultStage,序列化rdd和func;
8、最重要的,针对stage的每个分区构造task,形成tasks:ShuffleMapStage生成ShuffleMapTasks,ResultStage生成ResultTasks;
9、如果存在tasks,则利用taskScheduler.submitTasks()提交task,否则标记stage已完成。
至此,stage提交的主体流程已全部分析完毕,后续的Task调度与执行留待以后分析,而stage提交部分细节或者遗漏之处,特别是task生成时的部分细节,也留待以后再细细琢磨吧~
晚安!
博客原地址:http://blog.csdn.net/lipeng_bigdata/article/details/50679842
Spark源码分析之四:Stage提交
标签:
原文地址:http://www.cnblogs.com/jirimutu01/p/5274457.html