8. spark源码分析(基于yarn cluster模式)- Task执行,Map端写入实现,ShuffleMapTask,SortShuffleWriter,ResultStage,ResultT

VHDL按键消抖(状态机版本) 检测下降沿:设置一个和,分别代表之前的之前和之前的信号状态,若两个信号key_in_d2=1,key_in_d1=0,他俩的not key_in_d2 and key_in_d1为1,则说明下降沿产生,把它设置为标志位key_flag。延时计数:50MHz的板子每次计数需要20ns,而抖动时间大约为5-10ms。所以取7ms,作为延时时间。可以看见当检测到下降沿时,开始计数计数计满再次检测,若为低电平则为按下按键,否则为抖动。通过检测下降沿来临,延时计数再次检测,如果为低电平则为按键按下。 阅读详情

本系列基于spark-2.4.6
通过上一节分析,我们知道,task提交之后通过launchTasks来具体执行任务,这一章节我们看下其具体实现.

private def launchTasks(tasks: Seq[Seq[TaskDescription]]) {
      for (task <- tasks.flatten) {
        val serializedTask = TaskDescription.encode(task)
        if (serializedTask.limit() >= maxRpcMessageSize) {
          Option(scheduler.taskIdToTaskSetManager.get(task.taskId)).foreach { taskSetMgr =>
            try {
              var msg = "Serialized task %s:%d was %d bytes, which exceeds max allowed: " +
                "spark.rpc.message.maxSize (%d bytes). Consider increasing " +
                "spark.rpc.message.maxSize or using broadcast variables for large values."
              msg = msg.format(task.taskId, task.index, serializedTask.limit(), maxRpcMessageSize)
              taskSetMgr.abort(msg)
            } catch {
              case e: Exception => logError("Exception in error callback", e)
            }
          }
        }
        else {
          val executorData = executorDataMap(task.executorId)
          executorData.freeCores -= scheduler.CPUS_PER_TASK

          logDebug(s"Launching task ${task.taskId} on executor id: ${task.executorId} hostname: " +
            s"${executorData.executorHost}.")

          executorData.executorEndpoint.send(LaunchTask(new SerializableBuffer(serializedTask)))
        }
      }
    }

第一步判断序列化后的task是否大于maxRpcMessageSize,如果大于,直接报任务失败异常,退出执行当前任务,如果没有的话,则会发送LaunchTask指令给Executor去执行。接下来就要看Executor中是怎么执行的了。


通过前面的分析,我们知道,executor中消息到来会在org.apache.spark.rpc.netty.Inbox中进行处理:

 def process(dispatcher: Dispatcher): Unit = {
    var message: InboxMessage = null
    inbox.synchronized {
      if (!enableConcurrent && numActiveThreads != 0) {
        return
      }
      message = messages.poll()
      if (message != null) {
        numActiveThreads += 1
      } else {
        return
      }
    }
    while (true) {
      safelyCall(endpoint) {
        message match {
          case RpcMessage(_sender, content, context) =>
            try {
              endpoint.receiveAndReply(context).applyOrElse[Any, Unit](content, { msg =>
                throw new SparkException(s"Unsupported message $message from ${_sender}")
              })
            } catch {
              case e: Throwable =>
                context.sendFailure(e)
                throw e
            }

          case OneWayMessage(_sender, content) =>
            endpoint.receive.applyOrElse[Any, Unit](content, { msg =>
              throw new SparkException(s"Unsupported message $message from ${_sender}")
            })

          case OnStart =>
            endpoint.onStart()
            if (!endpoint.isInstanceOf[ThreadSafeRpcEndpoint]) {
              inbox.synchronized {
                if (!stopped) {
                  enableConcurrent = true
                }
              }
            }

          case OnStop =>
            val activeThreads = inbox.synchronized { inbox.numActiveThreads }
            dispatcher.removeRpcEndpointRef(endpoint)
            endpoint.onStop()
          case RemoteProcessConnected(remoteAddress) =>
            endpoint.onConnected(remoteAddress)

          case RemoteProcessDisconnected(remoteAddress) =>
            endpoint.onDisconnected(remoteAddress)

          case RemoteProcessConnectionError(cause, remoteAddress) =>
            endpoint.onNetworkError(cause, remoteAddress)
        }
      }

      inbox.synchronized {
        if (!enableConcurrent && numActiveThreads != 1) {
          numActiveThreads -= 1
          return
        }
        message = messages.poll()
        if (message == null) {
          numActiveThreads -= 1
          return
        }
      }
    }
  }

实际在CoarseGrainedExecutorBackend进行处理:

case LaunchTask(data) =>
      if (executor == null) {
        exitExecutor(1, "Received LaunchTask command but executor was null")
      } else {
        val taskDesc = TaskDescription.decode(data.value)
        logInfo("Got assigned task " + taskDesc.taskId)
        executor.launchTask(this, taskDesc)
      }
  def launchTask(context: ExecutorBackend, taskDescription: TaskDescription): Unit = {
    val tr = new TaskRunner(context, taskDescription)
    runningTasks.put(taskDescription.taskId, tr)
    threadPool.execute(tr)
  }

将接收到的task封装成一个TaskRunner然后提交到线程池中执行:

override def run(): Unit = {
      threadId = Thread.currentThread.getId
      Thread.currentThread.setName(threadName)
      val threadMXBean = ManagementFactory.getThreadMXBean
      val taskMemoryManager = new TaskMemoryManager(env.memoryManager, taskId)
      val deserializeStartTime = System.currentTimeMillis()
      val deserializeStartCpuTime = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
        threadMXBean.getCurrentThreadCpuTime
      } else 0L
      Thread.currentThread.setContextClassLoader(replClassLoader)
      val ser = env.closureSerializer.newInstance()
      logInfo(s"Running $taskName (TID $taskId)")
      execBackend.statusUpdate(taskId, TaskState.RUNNING, EMPTY_BYTE_BUFFER)
      var taskStartTime: Long = 0
      var taskStartCpu: Long = 0
      startGCTime = computeTotalGcTime()

      try {
        Executor.taskDeserializationProps.set(taskDescription.properties)

        updateDependencies(taskDescription.addedFiles, taskDescription.addedJars)
        task = ser.deserialize[Task[Any]](
          taskDescription.serializedTask, Thread.currentThread.getContextClassLoader)
        task.localProperties = taskDescription.properties
        task.setTaskMemoryManager(taskMemoryManager)
        val killReason = reasonIfKilled
        if (killReason.isDefined) {
          throw new TaskKilledException(killReason.get)
        }
        if (!isLocal) {
          logDebug("Task " + taskId + "'s epoch is " + task.epoch)
          env.mapOutputTracker.asInstanceOf[MapOutputTrackerWorker].updateEpoch(task.epoch)
        }

        // Run the actual task and measure its runtime.
        taskStartTime = System.currentTimeMillis()
        taskStartCpu = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
          threadMXBean.getCurrentThreadCpuTime
        } else 0L
        var threwException = true
        val value = Utils.tryWithSafeFinally {
          val res = task.run(
            taskAttemptId = taskId,
            attemptNumber = taskDescription.attemptNumber,
            metricsSystem = env.metricsSystem)
          threwException = false
          res
        } {
          val releasedLocks = env.blockManager.releaseAllLocksForTask(taskId)
          val freedMemory = taskMemoryManager.cleanUpAllAllocatedMemory()

          if (freedMemory > 0 && !threwException) {
            val errMsg = s"Managed memory leak detected; size = $freedMemory bytes, TID = $taskId"
            if (conf.getBoolean("spark.unsafe.exceptionOnMemoryLeak", false)) {
              throw new SparkException(errMsg)
            } else {
              logWarning(errMsg)
            }
          }

          if (releasedLocks.nonEmpty && !threwException) {
            if (conf.getBoolean("spark.storage.exceptionOnPinLeak", false)) {
              throw new SparkException(errMsg)
            } else {
              logInfo(errMsg)
            }
          }
        }
        task.context.fetchFailed.foreach { fetchFailure =>      
        }
        val taskFinish = System.currentTimeMillis()
        val taskFinishCpu = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
          threadMXBean.getCurrentThreadCpuTime
        } else 0L
        task.context.killTaskIfInterrupted()
        val resultSer = env.serializer.newInstance()
        val beforeSerialization = System.currentTimeMillis()
        val valueBytes = resultSer.serialize(value)
        val afterSerialization = System.currentTimeMillis()
        task.metrics.setExecutorDeserializeTime(
          (taskStartTime - deserializeStartTime) + task.executorDeserializeTime)
        task.metrics.setExecutorDeserializeCpuTime(
          (taskStartCpu - deserializeStartCpuTime) + task.executorDeserializeCpuTime)
        task.metrics.setExecutorRunTime((taskFinish - taskStartTime) - task.executorDeserializeTime)
        task.metrics.setExecutorCpuTime(
          (taskFinishCpu - taskStartCpu) - task.executorDeserializeCpuTime)
        task.metrics.setJvmGCTime(computeTotalGcTime() - startGCTime)
        task.metrics.setResultSerializationTime(afterSerialization - beforeSerialization)
       executorSource.METRIC_CPU_TIME.inc(task.metrics.executorCpuTime)
        executorSource.METRIC_RUN_TIME.inc(task.metrics.executorRunTime)
        executorSource.METRIC_JVM_GC_TIME.inc(task.metrics.jvmGCTime)
        executorSource.METRIC_DESERIALIZE_TIME.inc(task.metrics.executorDeserializeTime)
        executorSource.METRIC_DESERIALIZE_CPU_TIME.inc(task.metrics.executorDeserializeCpuTime)
        executorSource.METRIC_RESULT_SERIALIZE_TIME.inc(task.metrics.resultSerializationTime)
        executorSource.METRIC_SHUFFLE_FETCH_WAIT_TIME
          .inc(task.metrics.shuffleReadMetrics.fetchWaitTime)
        executorSource.METRIC_SHUFFLE_WRITE_TIME.inc(task.metrics.shuffleWriteMetrics.writeTime)
        executorSource.METRIC_SHUFFLE_TOTAL_BYTES_READ
          .inc(task.metrics.shuffleReadMetrics.totalBytesRead)
        executorSource.METRIC_SHUFFLE_REMOTE_BYTES_READ
          .inc(task.metrics.shuffleReadMetrics.remoteBytesRead)
        executorSource.METRIC_SHUFFLE_REMOTE_BYTES_READ_TO_DISK
          .inc(task.metrics.shuffleReadMetrics.remoteBytesReadToDisk)
        executorSource.METRIC_SHUFFLE_LOCAL_BYTES_READ
          .inc(task.metrics.shuffleReadMetrics.localBytesRead)
        executorSource.METRIC_SHUFFLE_RECORDS_READ
          .inc(task.metrics.shuffleReadMetrics.recordsRead)
        executorSource.METRIC_SHUFFLE_REMOTE_BLOCKS_FETCHED
          .inc(task.metrics.shuffleReadMetrics.remoteBlocksFetched)
        executorSource.METRIC_SHUFFLE_LOCAL_BLOCKS_FETCHED
          .inc(task.metrics.shuffleReadMetrics.localBlocksFetched)
        executorSource.METRIC_SHUFFLE_BYTES_WRITTEN
          .inc(task.metrics.shuffleWriteMetrics.bytesWritten)
        executorSource.METRIC_SHUFFLE_RECORDS_WRITTEN
          .inc(task.metrics.shuffleWriteMetrics.recordsWritten)
        executorSource.METRIC_INPUT_BYTES_READ
          .inc(task.metrics.inputMetrics.bytesRead)
        executorSource.METRIC_INPUT_RECORDS_READ
          .inc(task.metrics.inputMetrics.recordsRead)
        executorSource.METRIC_OUTPUT_BYTES_WRITTEN
          .inc(task.metrics.outputMetrics.bytesWritten)
        executorSource.METRIC_OUTPUT_RECORDS_WRITTEN
          .inc(task.metrics.outputMetrics.recordsWritten)
        executorSource.METRIC_RESULT_SIZE.inc(task.metrics.resultSize)
        executorSource.METRIC_DISK_BYTES_SPILLED.inc(task.metrics.diskBytesSpilled)
        executorSource.METRIC_MEMORY_BYTES_SPILLED.inc(task.metrics.memoryBytesSpilled)
        val accumUpdates = task.collectAccumulatorUpdates()
        val directResult = new DirectTaskResult(valueBytes, accumUpdates)
        val serializedDirectResult = ser.serialize(directResult)
        val resultSize = serializedDirectResult.limit()
        val serializedResult: ByteBuffer = {
          if (maxResultSize > 0 && resultSize > maxResultSize) {ze)}), " +
              s"dropping it.")
            ser.serialize(new IndirectTaskResult[Any](TaskResultBlockId(taskId), resultSize))
          } else if (resultSize > maxDirectResultSize) {
            val blockId = TaskResultBlockId(taskId)
            env.blockManager.putBytes(
              blockId,
              new ChunkedByteBuffer(serializedDirectResult.duplicate()),
              StorageLevel.MEMORY_AND_DISK_SER)
            ser.serialize(new IndirectTaskResult[Any](blockId, resultSize))
          } else {
            logInfo(s"Finished $taskName (TID $taskId). $resultSize bytes result sent to driver")
            serializedDirectResult
          }
        }
        setTaskFinishedAndClearInterruptStatus()
        execBackend.statusUpdate(taskId, TaskState.FINISHED, serializedResult)

      } catch {.......
      } finally {
        runningTasks.remove(taskId)
      }
    }

这里前面很大一部分在准备task执行的相关环境,然后调用task.run来执行,最后通过Task.runTask来实际执行任务,这是一个接口,我们以ShuffleMapTask为例进行说明:

// ShuffleMapTask
override def runTask(context: TaskContext): MapStatus = {
    // Deserialize the RDD using the broadcast variable.
    val threadMXBean = ManagementFactory.getThreadMXBean
    val deserializeStartTime = System.currentTimeMillis()
    val deserializeStartCpuTime = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
      threadMXBean.getCurrentThreadCpuTime
    } else 0L
    val ser = SparkEnv.get.closureSerializer.newInstance()
    val (rdd, dep) = ser.deserialize[(RDD[_], ShuffleDependency[_, _, _])](
      ByteBuffer.wrap(taskBinary.value), Thread.currentThread.getContextClassLoader)
    _executorDeserializeTime = System.currentTimeMillis() - deserializeStartTime
    _executorDeserializeCpuTime = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
      threadMXBean.getCurrentThreadCpuTime - deserializeStartCpuTime
    } else 0L

    var writer: ShuffleWriter[Any, Any] = null
    try {
      val manager = SparkEnv.get.shuffleManager
      writer = manager.getWriter[Any, Any](dep.shuffleHandle, partitionId, context)
      writer.write(rdd.iterator(partition, context).asInstanceOf[Iterator[_ <: Product2[Any, Any]]])
      writer.stop(success = true).get
    } catch {
     ....
    }
  }

这里会调用Writer进行处理:

writer.write(rdd.iterator(partition, context).asInstanceOf[Iterator[_ <: Product2[Any, Any]]])

spark中的ShuffleWriter有如下几种实现:
在这里插入图片描述

我们看下默认的SortShuffleWriter实现:

override def write(records: Iterator[Product2[K, V]]): Unit = {
    sorter = if (dep.mapSideCombine) {
      new ExternalSorter[K, V, C](
        context, dep.aggregator, Some(dep.partitioner), dep.keyOrdering, dep.serializer)
    } else {
      new ExternalSorter[K, V, V](
        context, aggregator = None, Some(dep.partitioner), ordering = None, dep.serializer)
    }
    sorter.insertAll(records)
    val output = shuffleBlockResolver.getDataFile(dep.shuffleId, mapId)
    val tmp = Utils.tempFileWith(output)
    try {
      val blockId = ShuffleBlockId(dep.shuffleId, mapId, IndexShuffleBlockResolver.NOOP_REDUCE_ID)
      val partitionLengths = sorter.writePartitionedFile(blockId, tmp)
      shuffleBlockResolver.writeIndexFileAndCommit(dep.shuffleId, mapId, partitionLengths, tmp)
      mapStatus = MapStatus(blockManager.shuffleServerId, partitionLengths)
    } finally {
      if (tmp.exists() && !tmp.delete()) {
        logError(s"Error while deleting temp file ${tmp.getAbsolutePath}")
      }
    }
  }

这里可以看到,里面用ExternalSorter,执行sorter.insertAll(records):

def insertAll(records: Iterator[Product2[K, V]]): Unit = {
    val shouldCombine = aggregator.isDefined
    if (shouldCombine) {
      val mergeValue = aggregator.get.mergeValue
      val createCombiner = aggregator.get.createCombiner
      var kv: Product2[K, V] = null
      val update = (hadValue: Boolean, oldValue: C) => {
        if (hadValue) mergeValue(oldValue, kv._2) else createCombiner(kv._2)
      }
      while (records.hasNext) {
        addElementsRead()
        kv = records.next()
        map.changeValue((getPartition(kv._1), kv._1), update)
        maybeSpillCollection(usingMap = true)
      }
    } else {
      while (records.hasNext) {
        addElementsRead()
        val kv = records.next()
        buffer.insert(getPartition(kv._1), kv._1, kv._2.asInstanceOf[C])
        maybeSpillCollection(usingMap = false)
      }
    }
  }

可以看到,这里如果需要在map端进行合并,则写入到了一个map中,否则写入到了一个数组中.map的实现为PartitionedAppendOnlyMap,数组缓存实现为PartitionedPairBuffer。 这里是写入到了一个缓存A中,缓存的实现为PartitionedPairBuffer,调用其insert`实现

  def insert(partition: Int, key: K, value: V): Unit = {
    if (curSize == capacity) {
      growArray()
    }
    data(2 * curSize) = (partition, key.asInstanceOf[AnyRef])
    data(2 * curSize + 1) = value.asInstanceOf[AnyRef]
    curSize += 1
    afterUpdate()
  }

最底层的datas还是一个数组来实现,一般内容为:

  • index保存分区号和key
  • index+1保存value

在ExternalSorter每次插入完之后会调用maybeSpillCollection来进行是否需要溢写到磁盘上,需要注意的是这里所谓的溢写磁盘是先将上面缓存中的数据先排好序,然后在写入到一个缓存B中,满足一定的阈值在写入到文件中,这里开启maybeSpillCollection这个步骤的条件是写入缓存A的大小大于阈值spark.shuffle.spill.initialMemoryThreshold,默认是5*1024*1024 5MB,然后执行maybeSpillCollection,这里面会对缓存A的数据先进行排序,然后在写入缓存B中,满足条件在flush到磁盘中,条件是已经写到缓存B中的数据条数等于spark.shuffle.spill.batchSize,默认是10000条:

private def maybeSpillCollection(usingMap: Boolean): Unit = {
    var estimatedSize = 0L
    if (usingMap) {
      estimatedSize = map.estimateSize()
      if (maybeSpill(map, estimatedSize)) {
        map = new PartitionedAppendOnlyMap[K, C]
      }
    } else {
      estimatedSize = buffer.estimateSize()
      if (maybeSpill(buffer, estimatedSize)) {
        buffer = new PartitionedPairBuffer[K, C]
      }
    }
    if (estimatedSize > _peakMemoryUsedBytes) {
      _peakMemoryUsedBytes = estimatedSize
    }
  }

在 Spillable去执行maybeSpill这里面如果需要溢写的话,会执行实际的溢写磁盘处理

  override protected[this] def spill(collection: WritablePartitionedPairCollection[K, C]): Unit = {
    val inMemoryIterator = collection.destructiveSortedWritablePartitionedIterator(comparator)
    val spillFile = spillMemoryIteratorToDisk(inMemoryIterator)
    spills += spillFile
  }

最终还是在ExternalSorter处理:

private[this] def spillMemoryIteratorToDisk(inMemoryIterator: WritablePartitionedIterator)
      : SpilledFile = {
    val (blockId, file) = diskBlockManager.createTempShuffleBlock()
    var objectsWritten: Long = 0
    val spillMetrics: ShuffleWriteMetrics = new ShuffleWriteMetrics
    val writer: DiskBlockObjectWriter =
      blockManager.getDiskWriter(blockId, file, serInstance, fileBufferSize, spillMetrics)
    val batchSizes = new ArrayBuffer[Long]
    val elementsPerPartition = new Array[Long](numPartitions)
    def flush(): Unit = {
      val segment = writer.commitAndGet()
      batchSizes += segment.length
      _diskBytesSpilled += segment.length
      objectsWritten = 0
    }
    var success = false
    try {
      while (inMemoryIterator.hasNext) {
        val partitionId = inMemoryIterator.nextPartition()
        inMemoryIterator.writeNext(writer)
        elementsPerPartition(partitionId) += 1
        objectsWritten += 1

        if (objectsWritten == serializerBatchSize) {
          flush()
        }
      }
      if (objectsWritten > 0) {
        flush()
      } else {
        writer.revertPartialWritesAndClose()
      }
      success = true
    } finally {
      if (success) {
        writer.close()
      } else {
        writer.revertPartialWritesAndClose()
        if (file.exists()) {
        }
      }
    }
    SpilledFile(file, blockId, batchSizes.toArray, elementsPerPartition)
  }

这里在写入的时候首先会通过diskBlockManager.createTempShuffleBlock()来获取一个临时的文件名和对应的路径,这个文件名就是通过UUID.randomUUID

 def createTempShuffleBlock(): (TempShuffleBlockId, File) = {
    var blockId = new TempShuffleBlockId(UUID.randomUUID())
    while (getFile(blockId).exists()) {
      blockId = new TempShuffleBlockId(UUID.randomUUID())
    }
    (blockId, getFile(blockId))
  }

当写入缓存的数据条数等于10000的时候会执行刷盘,写入创建的文件中。
写入前会对要写入的缓存数据进行排序,按照paritionId+Key的方式进行排序,先比较paritionId,同一个partitionId在比较Key。这样写入到文件中的数据就是已经排好序的文件,写入文件,每个partition对应的数据都是紧密排在一起、相邻的。

当任务都写完之后,这时候实际上是多个小文件,然后会进行小文件的合并,将多个文件合并成一个文件并生成一个对应的索引文件:

 val blockId = ShuffleBlockId(dep.shuffleId, mapId, IndexShuffleBlockResolver.NOOP_REDUCE_ID)
      val partitionLengths = sorter.writePartitionedFile(blockId, tmp)
      shuffleBlockResolver.writeIndexFileAndCommit(dep.shuffleId, mapId, partitionLengths, tmp)
      mapStatus = MapStatus(blockManager.shuffleServerId, partitionLengths)

这里通过sorter.writePartitionedFile(blockId, tmp)将所有溢写的小文件按照分区划分,相同分区数据写在一个文件中,通过shuffleBlockResolver.writeIndexFileAndCommit(dep.shuffleId, mapId, partitionLengths, tmp)生成索引文件。

def writePartitionedFile(
      blockId: BlockId,
    val lengths = new Array[Long](numPartitions)
    val writer = blockManager.getDiskWriter(blockId, outputFile, serInstance, fileBufferSize,
      context.taskMetrics().shuffleWriteMetrics)
    if (spills.isEmpty) {
      val collection = if (aggregator.isDefined) map else buffer
      val it = collection.destructiveSortedWritablePartitionedIterator(comparator)
      while (it.hasNext) {
        val partitionId = it.nextPartition()
        while (it.hasNext && it.nextPartition() == partitionId) {
          it.writeNext(writer)
        }
        val segment = writer.commitAndGet()
        lengths(partitionId) = segment.length
      }
    } else {
      for ((id, elements) <- this.partitionedIterator) {
        if (elements.hasNext) {
          for (elem <- elements) {
            writer.write(elem._1, elem._2)
        }
          val segment = writer.commitAndGet()
          lengths(id) = segment.length
        }
      }
    }
....
  }

这里的spills就是上面我们提到的溢写的小文件的集合,这里我们以已经有溢写小文件来看看是怎么处理的,主要逻辑在this.partitionedIterator返回的迭代器:

def partitionedIterator: Iterator[(Int, Iterator[Product2[K, C]])] = {
    val usingMap = aggregator.isDefined
    val collection: WritablePartitionedPairCollection[K, C] = if (usingMap) map else buffer
    if (spills.isEmpty) {
      if (!ordering.isDefined) {  groupByPartition(destructiveIterator(collection.partitionedDestructiveSortedIterator(None)))
      } else {
        // We do need to sort by both partition ID and key
        groupByPartition(destructiveIterator(
          collection.partitionedDestructiveSortedIterator(Some(keyComparator))))
      }
    } else {
      merge(spills, destructiveIterator(
        collection.partitionedDestructiveSortedIterator(comparator)))
    }
  }

private def merge(spills: Seq[SpilledFile], inMemory: Iterator[((Int, K), C)])
      : Iterator[(Int, Iterator[Product2[K, C]])] = {
    val readers = spills.map(new SpillReader(_))
    val inMemBuffered = inMemory.buffered
    (0 until numPartitions).iterator.map { p =>
      val inMemIterator = new IteratorForPartition(p, inMemBuffered)
      val iterators = readers.map(_.readNextPartition()) ++ Seq(inMemIterator)
      if (aggregator.isDefined) {
        // Perform partial aggregation across partitions
        (p, mergeWithAggregation(
          iterators, aggregator.get.mergeCombiners, keyComparator, ordering.isDefined))
      } else if (ordering.isDefined) {
        // No aggregator given, but we have an ordering (e.g. used by reduce tasks in sortByKey);
        // sort the elements without trying to merge them
        (p, mergeSort(iterators, ordering.get))
      } else {
        (p, iterators.iterator.flatten)
      }
    }
  }

可以看到,这里返回的是一个迭代器的集合,主要是用来迭代已经写入数据的小文件和还在缓存中的数据。小文件的迭代器实现为SpillReader,其是按照分区来读取文件中的内容,另外缓存数据的迭代器还是和上面写小文件用的迭代器一样。

 for ((id, elements) <- this.partitionedIterator) {
        if (elements.hasNext) {
          for (elem <- elements) {
            writer.write(elem._1, elem._2)
        }
          val segment = writer.commitAndGet()
          lengths(id) = segment.length
        }
      }
    }

这里每次都是一个分区的数据迭代器的集合,这样一次迭代完就把一个分区的数据都读取完并写入到文件中,另外这里在每个分区写入完成之后,会记录每个分区在写入文件中的数据的大小。这里Sort模式每个Task最终生成两个文件,一个数据文件,一个索引文件
然后生成索引文件,索引文件根据上面每个分区写入数据的大小,按照分区依次写入对应数据文件大小。到这里,map端的数据完成了。

这里总结下整个Map端的写入流程

  1. Executor收到Drvier端发送的LaunchTask命令后,将接收到的Task信息封装到TaskRunner中,然后通过线程池执行TaskRunner.run方法,执行任务
  2. TaskRunner.run最终会调用Task.runTask方法,在ShuffleMapTask中,交由ShuffleWriter去进行写入
  3. 默认的SortShuffleWriter会将数据写入一个map或者数组中(看是否需要在Map端进行聚合)
  4. SortShuffleWriter调用ExternalSorter进行插入数据到缓存中,每次插入完一条数据之后判断缓存是否需要一些磁盘,判断条件是缓存数据大小是否大于spark.shuffle.spill.initialMemoryThreshold,默认是5MB
  5. 如果需要进行溢写磁盘,先进行排好序后会将已经排好序的数据在写到一个临时缓存中,写入前会对要写入的缓存数据进行排序,按照paritionId+Key的方式进行排序,先比较paritionId,同一个partitionId在比较Key。这样写入到文件中的数据就是已经排好序的文件,写入文件,每个partition对应的数据都是紧密排在一起、相邻的。然后这个临时缓存如果数据条数大于spark.shuffle.spill.initialMemoryThreshold(默认10000条),则会把数据flush到本地磁盘中,(这里每次大于spark.shuffle.spill.initialMemoryThreshold写磁盘都是生成一个新的磁盘文件,大于spark.shuffle.spill.initialMemoryThreshold只是flush到磁盘,并不会生成一个新文件)
  6. 当任务执行完成之后,实际上生成的是多个小文件,最后会把这多个小文件的数据都写到一个文件中,同时生成一个对应的索引文件,写入数据到文件的时候是按照分区来进行写入的,会按照分区逐个遍历所有的小文件,然后读取该分区的数据并写入到最终的数据文件中,这样最终的数据文件中每个分区的数据都是紧密排列在一起的同时部分有序,这样索引文件就能够根据文件位置找到对应的分区的数据

上面说的都是ShuffleMapTask的处理,如果是 ResultStage生成的则是ResultTask,唯一的区别则是ResultTask不会进行类似ShuffleMapTask的本地临时文件写入(执行writer.write方法),而是根据用户传入的执行算子,执行方法:

  override def runTask(context: TaskContext): U = {
    val threadMXBean = ManagementFactory.getThreadMXBean
    val deserializeStartTime = System.currentTimeMillis()
    val deserializeStartCpuTime = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
      threadMXBean.getCurrentThreadCpuTime
    } else 0L
    val ser = SparkEnv.get.closureSerializer.newInstance()
    val (rdd, func) = ser.deserialize[(RDD[T], (TaskContext, Iterator[T]) => U)](
      ByteBuffer.wrap(taskBinary.value), Thread.currentThread.getContextClassLoader)
    _executorDeserializeTime = System.currentTimeMillis() - deserializeStartTime
    _executorDeserializeCpuTime = if (threadMXBean.isCurrentThreadCpuTimeSupported) {
      threadMXBean.getCurrentThreadCpuTime - deserializeStartCpuTime
    } else 0L

    func(context, rdd.iterator(partition, context))
  }

可以看到这里ResultTask获取到自己需要处理的分区数据后直接执行用户的方法。

openclaw-cn : 无法将“openclaw-cn”项识别为 cmdlet、函数、脚本文件或可运行程序的名称 解决方案 本文主要介绍了openclaw-cn : 无法将“openclaw-cn”项识别为 cmdlet、函数、脚本文件或可运行程序的名称解决方案,希望能对使用openclaw-cn的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案 阅读详情

相关推荐

C#程序突然崩溃怎么办?5分钟学会分析Dump文件(Visual Studio 2022实战)

本文详细介绍了在C#程序崩溃或无响应时,如何捕获并分析Dump文件以快速定位问题。通过Visual Studio 2022实战演示,重点讲解了配置符号服务器、解读调用堆栈与内存状态,以及针对CPU飙高、内存泄漏等典型场景的分析方法,帮助开发者高效进行故障诊断。

docker8compose的博客 479

解决Consider increasing spark.rpc.message.maxSize

apache.spark.SparkException: Job aborted due to stage failure: Serialized task 32:5 was 204136673 bytes, which exceeds max allowed: spark.rpc.message.maxSize (134217728 bytes).Consider increasing spark

quitozang的博客 6700

PCA9698嵌入式C++驱动库:高性能I²C GPIO扩展方案

GPIO扩展是嵌入式系统中解决MCU引脚资源不足的关键技术,其核心原理在于通过串行总线(如I²C)桥接主控与外设寄存器,实现逻辑引脚到物理IO的映射与状态同步。技术价值体现在低开销、高确定性与多设备可扩展性,广泛应用于工业控制、传感器节点和LED矩阵驱动等实时场景。本文聚焦PCA9698——一款支持24通道双向IO、中断输出与可编程驱动模式的I²C GPIO扩展芯片,结合其C++驱动库的影子寄存器机制、端口级原子操作及非阻塞同步设计,提供面向资源受限平台(如ATmega2560)的工程就绪方案。

weixin_35756637的博客 633

小米/红米刷机过程-以红米3S为例

文章目录小米/红米刷机过程-以红米3S为例卡刷1. 解锁设备2. 通过 fastboot 安装 Recovery3. 通过 Recovery 安装第三方ROM线刷 小米/红米刷机过程-以红米3S为例 对于小米/红米手机来说,刷机的方法可以分为线刷和卡刷。 注意事项: 线刷工具为MiFlash,卡刷推荐刷入第三方Recovery如twrp进行刷机。 线刷文件后缀名为.tgz。卡刷使用文件后缀名.z...

坐于屋顶望月球 8789

LangGraph实战:用Python异步构建智能客服多轮对话系统(附完整代码)

本文详细介绍了如何使用LangGraph框架和Python异步编程构建一个高性能的智能客服多轮对话系统。通过将对话流程建模为有向图,结合thread_id实现多用户对话隔离,并利用异步节点提升系统并发处理能力,有效解决了传统客服系统上下文遗忘与高并发瓶颈问题。文章提供了从环境搭建、状态管理、异步优化到复杂业务逻辑与部署的完整实战代码。

weixin_29055137的博客 156

RTX 4060笔记本也能跑!保姆级教程:用Ollama在Windows上部署DeepSeek-R1-8B模型

本文详细介绍了如何在RTX 4060笔记本上通过Ollama本地部署DeepSeek-R1-8B模型,提供从环境配置到性能调优的全流程优化指南。针对笔记本用户的显存、散热等问题,给出了量化模型选择、启动参数优化及散热解决方案,帮助用户在消费级硬件上高效运行大语言模型。

weixin_28745067的博客 531

Spark在StandAlone模式下提交任务,spark.rpc.message.maxSize太小而出错

1.错误信息org.apache.spark.SparkException: Job aborted due to stage failure:Serialized task 32:5 was 1728746673 bytes, which exceeds max allowed: spark.rpc.message.maxSize (134217728 bytes). Consi...

weixin_30828379的博客 1818

SAP 系统间信任关系配置全攻略:从 SM59 到 SMT1 的实践与风险控制

本文介绍了在SAP系统间配置信任关系的详细流程与最佳实践。文章以SAP Gateway与后端系统架构为场景,从SM59创建RFC目的地开始,到SMT1建立信任关系,再到授权对象S_RFCACL的配置,提供了完整的操作指南。重点包括:使用标准命名规范创建专用RFC连接、通过向导完成系统间信任登记、严格控制S_RFCACL授权范围等。文中还分享了真实项目案例、可复用的检查清单以及常见问题的排查思路,帮助用户实现稳定可靠的跨系统无密码调用,同时确保安全性。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 328

小米4c刷LineageOS

小米4c刷LineageOS 注意,本文仅限于小米4c,其他手机仅可参考步骤。如下rom,su,gapps包的下载都是小米4c的,深刷miflash也仅适用于小米手机。准备工作:请自行备份好手机内的个人资料。 电脑环境,usb驱动等...(后续补充),可参考如下,https://wiki.lineageos.org/devices/libra/installhtt...

feiyu5323的专栏 5131

智能温室:温室环境监测_(7).土壤监测技术包括pH值和电导率

土壤的pH值是指土壤溶液的酸碱度,它对植物的营养吸收和生长发育有着重要的影响。在智能温室中,土壤监测是非常重要的一个环节,因为土壤的pH值和电导率直接影响植物的生长和健康。本节将详细介绍如何利用传感器和数据处理技术来监测土壤的pH值和电导率,并提供具体的代码示例。在智能温室中,监测到的土壤pH值和电导率数据需要传输到中央控制系统进行进一步的处理和分析。通过以上步骤,您可以构建一个完整的智能温室土壤监测系统,实时监控土壤的pH值和电导率,确保植物在最佳的生长环境中。校准通常包括在已知电导率的标准溶液中进行。

zhubeibei168的博客 1411

【大模型】AI 辅助编程操作实战使用详解

AI 编程实战使用详解

congge 8474

功夫不负有心人,小米 Note 3 进 EDL (9008) 模式方法。可修复传感器、相机启动贼慢问题

翻阅 XDA 和海外 MIUI 论坛许久,国内 MIUI 论坛也看了个遍,没找到可靠的解决办法,于是自己瞎 J8 折腾,还真弄出来了 先说一下,我在看 XDA 论坛时,RedMi Note 3(红米3)板块有网友提到 fastboot erase psersist 和 fastboot flash persist persist.img 的修复方法。 还有进入 EDL 模式,然后修改 ...

Right! I'm Max Sky. 3万+

利用 SAP Joule 提升 ABAP 开发效率的前提条件与限制全解析

综上,想要在 ABAP Development Tools 中顺利使用 SAP Joule,既要准备好 BTP、IAS、ABAP 系统与 ADT 的版本与信任链,也要理解许可证、配额、语法范围等限制。只有在这些前提全部满足后,Joule 才能真正发挥生成式 AI 的价值,帮助 ABAP 开发者从繁琐模板中解放出来,把注意力投入在业务创新与 Clean Core 改造之上。未来 SAP 还将扩展中文语境、自动修复建议以及跨系统智能代理等功能,值得持续关注。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 672

nexus5 线刷5.01

我当初是用这种方式: http://www.igao7.com/news/201406/nexus-root-ota.html https://goo.im/devs/WugFresh/NexusRootToolkit/ 来root的5.0,结果ota不行, 据说只能线刷5.01. ======== 备份 ======= 刷机精灵,想刷个cm的4.4,结果rom 脚本错误,

突围 2557

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

spring boot 报错

D:\svn\n54_内部系统2021\后端>java.lang.reflect.InvocationTargetExceptionjava.lang.reflect.InvocationTargetException。下面这个报错是在cmd中运行的 各位大佬能帮忙分析下啥子原因不eclipse下所有项目都这样 我下载了3个版本的eclipse,19到23的都有都一样结果,jdk是1.8的。D:\svn\n54_内部系统2021\后端>mvn spring-boot:run。

weixin_53175943的博客 437

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Android11 刷机教程

目录0x0 背景0x1 下载刷机包0x2 安装0x20 刷机包文件解析0x21 进入fasterboot模式0x22 刷机 0x0 背景 需要使用Piexl 3a手机刷Android 11系统。 0x1 下载刷机包 先访问Google的官方刷机包下载地址:https://developer.android.google.cn/preview/download 选择对应机型的刷机包: 0x2 安装 0x20 刷机包文件解析 解压刷机包,得到如下的文件: 核心文件: bootloader-sargo-b4

stoneWang_L的博客 1万+

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Galaxy Nexus IMM76K 手动升级 4.1.1

手上Galaxy Nexus是 IMM76K,一直等不到OTA升级。查了一下,这是三×来管理的OTA的机器,Google不管。是后娘养的。只好自己动手回到Google箮理之下。 前提升级需要在Linux 下,我的电脑装的Arch 升级过程非常简单。 英文的升级说明: Instructions You will find these files useful i...

移动开发记录 266

Spark任务两个小问题笔记

今天在用spark处理数据的时候,遇到两个小问题,特此笔记一下。 两个问题都与网络交互有关,大致处理场景是,在driver端会提前获取组装一批数据,然后把这些数据发送executor端进行后续处理。 问题一:序列化异常 driver有一个case class类需要封装一些数据发送到executor上,原来都是scala的类,直接发送到executor上执行没问...

三劫散仙 270

Spark ERROR netty.Inbox: Ignoring error org.apache.spark.SparkException: Couldnot find CoarseGrained

问题 ERROR org.apache.spark.rpc.netty.Inbox: Ignoring error org.apache.spark.SparkException: Could not find CoarseGrainedScheduler 提到如下解决思路: 我没设置 上面的参数默认已经为false了 还有方案说 增加num-executors ,已经设置成了100,感觉是设置太多了 解决 经过一般调试,发现原来是因为spark任务生成task任务过少,而任...

每天进步一点点儿 2136

大数据:Spark Core(二)Driver上的Task的生成、分配、调度

1. 什么是Task? 在前面的章节里描述过几个角色,Driver(Client),Master,Worker(Executor),Driver会提交Application到Master进行Worker上的Executor上的调度,显然这些都不是Task. Spark上的几个关系可以这样理解: Application: Application是Driver在构建SparkContent的上下文的时候创建的,就像申报员,现在要构建一个能完成任务的集群,需要申报的是这次需要多少个Executor(可以简单理解

沧海一粟 1万+

Spark源码阅读——任务提交过程

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33831196的博客 191

spark源码学习

从启动SparkContext开始1、createTaskScheduler: 创建scheduler 、backendcase SPARK_REGEX(sparkUrl) => val scheduler = new TaskSchedulerImpl(sc) val masterUrls = sparkUrl.split(",").map("spark://"

prometheus的博客 1789

Spark2.2 TaskScheduler原理剖析与源码分析

TaskScheduler的作用TaskScheduler的主要作用是把TaskSet中的每一个task提交到executor上去执行; 其中最主要的就是task的分配算法。TaskScheduler源码分析 TaskScheduler 提交tasks的入口 submitTasks 为每一个taskSet创建一个taskSetManager 调用CoarseGrainedSchedulerBa

行走的树 2863

android L nexus5 刷机

前置条件:1 android nexue 5 手机一部2 android L最新rom包android L rom下载地址https://developers.google.com/fit/preview#flash_your_nexus_5_or_nexus_7过程:下载完成后解压缩,这个包需要使用 fastboot工具,不是原来的zip卡刷包,好在里面的脚本文件都已经写好...

weixin_34418883的博客 200

Weex Android SDK源码分析之界面渲染(上)

首先感谢阿里巴巴团队对移动端跨三端与动态化做出的杰出贡献,阿里在6月初,彻底开放了weex android与ios端内测,最近已使用一周有余,效果果然达到了learn once,write everywhere!而且运行效果可以与原声媲美,并且virtual dom的加入更加优化了性能问题,切对native扩展等提供了很好的预留,目前可以采用组件形式与全页形式进行集成,接下来我给大家介绍下weex在android端的工作原理及代码分析。

王永迪的专栏 2万+
上一篇: 7. spark源码分析(基于yarn cluster模式)- Task划分、资源分配、提交
下一篇: 9. spark源代码分析(基于yarn cluster模式)- Task执行,Reduce端读取shuffle数据文件
Leo Han
博客等级 码龄9年 1171粉丝 253原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值