查看的源码为spark2.3

调用ShuffleMapTask的runTask方法

org.apache.spark.scheduler.ShuffleMapTask#runTask

ShuffleMapTask继承了org.apache.spark.scheduler.Task,重写了Task的runTask方法,在该方法中关于shuffle部分主要是获取shuffleManager,然后得到sortShuffleManager,然后再通过manager获取writer,得到sortShuffleWriter,然后调用writer方法

  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 //定义writer对象
var writer: ShuffleWriter[Any, Any] = null
try {
//获取shuffleManager
val manager = SparkEnv.get.shuffleManager
//通过shuffleManager获取Writer对象,这里的partitionId传入的其实是mapId,每个map有个mapId
writer = manager.getWriter[Any, Any](dep.shuffleHandle, partitionId, context)
//调用write方法。write方法如下
writer.write(rdd.iterator(partition, context).asInstanceOf[Iterator[_ <: Product2[Any, Any]]])
writer.stop(success = true).get
} catch {
case e: Exception =>
try {
if (writer != null) {
writer.stop(success = false)
}
} catch {
case e: Exception =>
log.debug("Could not stop writer", e)
}
throw e
}
}

调用SortShuffleWriter的write方法

org.apache.spark.shuffle.sort.SortShuffleWriter#write

SortShuffleWriter继承了org.apache.spark.shuffle.ShuffleWriter并重写了其write方法

  /** Write a bunch of records to this task's output */
override def write(records: Iterator[Product2[K, V]]): Unit = {
//根据是否存在map端聚合获取ExternalSorter对象(sorter)
sorter = if (dep.mapSideCombine) {
require(dep.aggregator.isDefined, "Map-side combine without Aggregator specified!")
new ExternalSorter[K, V, C](
context, dep.aggregator, Some(dep.partitioner), dep.keyOrdering, dep.serializer)
} else {
// In this case we pass neither an aggregator nor an ordering to the sorter, because we don't
// care whether the keys get sorted in each partition; that will be done on the reduce side
// if the operation being run is sortByKey.如果没有map-side聚合,那么创建sorter对象时候,aggregator和ordering将不传入对应的值
new ExternalSorter[K, V, V](
context, aggregator = None, Some(dep.partitioner), ordering = None, dep.serializer)
}
//通过insertAll方法先写数据到buffer
sorter.insertAll(records) // Don't bother including the time to open the merged output file in the shuffle write time,
// because it just opens a single file, so is typically too fast to measure accurately
// (see SPARK-3570). //通过blockManager获取对应mapId.shuffleId的文件输出路径
val output = shuffleBlockResolver.getDataFile(dep.shuffleId, mapId)
//返回与“path”位于同一目录中的临时文件的路径。
val tmp = Utils.tempFileWith(output)
try {
val blockId = ShuffleBlockId(dep.shuffleId, mapId, IndexShuffleBlockResolver.NOOP_REDUCE_ID)
//将所有的数据合并到一个文件中
val partitionLengths = sorter.writePartitionedFile(blockId, tmp)
//生成index文件,也就是每个reduce通过该index文件得知它哪些是属于它的数据
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类

创建ExternalSorter对象时,各参数对应的意思。

class ExternalSorter[K, V, C](
context: TaskContext,
aggregator: Option[Aggregator[K, V, C]] = None,
partitioner: Option[Partitioner] = None,
ordering: Option[Ordering[K]] = None,
serializer: Serializer = SparkEnv.get.serializer) aggregator:在RDD shuffle时,map/reduce-side使用的aggregator
partitioner:对shuffle的输出,使用哪种partitioner对数据做分区,比如hashPartitioner或者rangePartitioner
ordering:根据哪个key做排序
serializer:使用哪种序列化,如果没有显示指定,默认使用spark.serializer参数值

从一个high level的角度看ExternalSorter到底做了什么?
第一:反复的将数据填充到内存buffer中(如果需要通过key做map-side聚合,则使用PartitionedAppendOnlyMap;如果不需要,则使用PartitionedPairBuffer),如下

// Data structures to store in-memory objects before we spill. Depending on whether we have an
// Aggregator set, we either put objects into an AppendOnlyMap where we combine them, or we
// store them in an array buffer.
@volatile private var map = new PartitionedAppendOnlyMap[K, C]
@volatile private var buffer = new PartitionedPairBuffer[K, C]

第二:在buffer中,通过key计算partition ID,通过partition ID对数据进行排序(partition ID可以理解为reduce ID,意思就是数据被分给了哪个reduce),为了避免对key调用多次partitioner,spark会将partition ID跟每一条数据一起存储。

第三:当buffer达到内存限制时(buffer默认大小32k,由spark.shuffle.file.buffer参数决定),会将buffer中的数据spill到文件中(每次spill都会生成一个文件),如果我们需要做map-side聚合,该文件生成时会通过partition ID先做排序,然后通过key或者key的hashcode值做二次排序。
第四:将spill形成的多个文件合并包括还在内存中的数据,文件合并时候将会排序,排序方式跟上面一样,生成数据文件dataFile以及索引文件indexFile
第五:最后调用stop方法,删除所有中间文件

结合下图更好理解

mapTask通过externalSorter生成多个文件,也就是fileSegment,最后每个map任务的所有filesegment将会合并成一个file

上图数据插入的是appendOnlyMap,也就是使用了map-side聚合,所以有merger value,appendOnlyMap在满了以后(默认32k)将spill成文件,多次spill生成多个文件,最后merge所有文件包括还在内存buffer中的数据。

调用ExternalSorter的insertAll方法

这一步主要是往buffer写数据,对数据分partition ID,buffer满了spill数据到磁盘且对数据排序

def insertAll(records: Iterator[Product2[K, V]]): Unit = {
// TODO: stop combining if we find that the reduction factor isn't high如果合并比例不高的话,就不会继续合并了
// 通过创建ExternalSorter对象时传入的aggregator获取是否存在合并
val shouldCombine = aggregator.isDefined if (shouldCombine) {
// Combine values in-memory first using our AppendOnlyMap
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就是该类中定义的PartitionedAppendOnlyMap,getPartition方法通过key获取所属Partition ID(hashPartitioner)
map.changeValue((getPartition(kv._1), kv._1), update)
// buffer满的话将内存中的数据spill成文件
maybeSpillCollection(usingMap = true)
}
} else {
// Stick values into our buffer
while (records.hasNext) {
addElementsRead()
val kv = records.next()
//这个buffer就是该类中定义的PartitionedPairBuffer
buffer.insert(getPartition(kv._1), kv._1, kv._2.asInstanceOf[C])
maybeSpillCollection(usingMap = false)
}
}
}

insertAll方法中调用maybeSpillCollection方法

  /**
* Spill the current in-memory collection to disk if needed.
*
* @param usingMap whether we're using a map or buffer as our current in-memory collection
* 不同的数据结构(也就是buffer)调用不同的方法
*/
private def maybeSpillCollection(usingMap: Boolean): Unit = {
var estimatedSize = 0L
if (usingMap) {
estimatedSize = map.estimateSize()
//maybeSpill方法会尝试申请buffer内存,如果申请到内存,则spill且返回false。否则true
if (maybeSpill(map, estimatedSize)) {
//appendOnlyMap的数据spill以后,创建一个新的appendOnlyMap
map = new PartitionedAppendOnlyMap[K, C]
}
} else {
estimatedSize = buffer.estimateSize()
if (maybeSpill(buffer, estimatedSize)) {
buffer = new PartitionedPairBuffer[K, C]
}
} if (estimatedSize > _peakMemoryUsedBytes) {
_peakMemoryUsedBytes = estimatedSize
}
}

maybeSpillCollection方法中调用maybeSpill方法,判断是否应该执行spill

  /**
* Spills the current in-memory collection to disk if needed. Attempts to acquire more
* memory before spilling.
* 在spill之前会尝试申请内存,最后才判断是否真正执行spill
* @param collection collection to spill to disk
* @param currentMemory estimated size of the collection in bytes
* @return true if `collection` was spilled to disk; false otherwise
*/
protected def maybeSpill(collection: C, currentMemory: Long): Boolean = {
var shouldSpill = false
if (elementsRead % 32 == 0 && currentMemory >= myMemoryThreshold) {
// Claim up to double our current memory from the shuffle memory pool;从上次spill以后,每读取32个元素判断一次,声明申请额外内存
val amountToRequest = 2 * currentMemory - myMemoryThreshold
val granted = acquireMemory(amountToRequest)
myMemoryThreshold += granted
// If we were granted too little memory to grow further (either tryToAcquire returned 0,
// or we already had more memory than myMemoryThreshold), spill the current collection
shouldSpill = currentMemory >= myMemoryThreshold
}
shouldSpill = shouldSpill || _elementsRead > numElementsForceSpillThreshold
// Actually spill
if (shouldSpill) {
_spillCount += 1
logSpillage(currentMemory)
spill(collection)
_elementsRead = 0
_memoryBytesSpilled += currentMemory
releaseMemory()
}
shouldSpill
}

1

spark sortShuffleWriter源码学习的更多相关文章

  1. Spark源码学习1.1——DAGScheduler.scala

    本文以Spark1.1.0版本为基础. 经过前一段时间的学习,基本上能够对Spark的工作流程有一个了解,但是具体的细节还是需要阅读源码,而且后续的科研过程中也肯定要修改源码的,所以最近开始Spark ...

  2. 【Spark2.0源码学习】-1.概述

          Spark作为当前主流的分布式计算框架,其高效性.通用性.易用性使其得到广泛的关注,本系列博客不会介绍其原理.安装与使用相关知识,将会从源码角度进行深度分析,理解其背后的设计精髓,以便后续 ...

  3. 使用 IntelliJ IDEA 导入 Spark 最新源码及编译 Spark 源代码(博主强烈推荐)

    前言   其实啊,无论你是初学者还是具备了有一定spark编程经验,都需要对spark源码足够重视起来. 本人,肺腑之己见,想要成为大数据的大牛和顶尖专家,多结合源码和操练编程. 准备工作 1.sca ...

  4. 【Spark SQL 源码分析系列文章】

    从决定写Spark SQL源码分析的文章,到现在一个月的时间里,陆陆续续差不多快完成了,这里也做一个整合和索引,方便大家阅读,这里给出阅读顺序 :) 第一篇 Spark SQL源码分析之核心流程 第二 ...

  5. Spark SQL源码解析(二)Antlr4解析Sql并生成树

    Spark SQL原理解析前言: Spark SQL源码剖析(一)SQL解析框架Catalyst流程概述 这一次要开始真正介绍Spark解析SQL的流程,首先是从Sql Parse阶段开始,简单点说, ...

  6. Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结

    2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...

  7. jQuery源码学习感想

    还记得去年(2015)九月份的时候,作为一个大四的学生去参加美团霸面,结果被美团技术总监教育了一番,那次问了我很多jQuery源码的知识点,以前虽然喜欢研究框架,但水平还不足够来研究jQuery源码, ...

  8. MVC系列——MVC源码学习:打造自己的MVC框架(四:了解神奇的视图引擎)

    前言:通过之前的三篇介绍,我们基本上完成了从请求发出到路由匹配.再到控制器的激活,再到Action的执行这些个过程.今天还是趁热打铁,将我们的View也来完善下,也让整个系列相对完整,博主不希望烂尾. ...

  9. MVC系列——MVC源码学习:打造自己的MVC框架(三:自定义路由规则)

    前言:上篇介绍了下自己的MVC框架前两个版本,经过两天的整理,版本三基本已经完成,今天还是发出来供大家参考和学习.虽然微软的Routing功能已经非常强大,完全没有必要再“重复造轮子”了,但博主还是觉 ...

随机推荐

  1. DVWA靶机的命令执行漏洞

    之前在打攻防世界的时候出现过类似的题目,这里再重温一下 (靶机一共低中高三个安全等级,这里只演示低中等级) (1)Security:low 根据提示让我们输入地址ping一下,之后返回以下内容,可以判 ...

  2. 用IDEA创建项目时没有Spring类型的项目模板

    使用的版本:2019.2.2 Community 解决方法:File=>Setting=>Plugins=>搜索Spring,安装Spring Assistant=>重启IDE ...

  3. 【PAT甲级】1033 To Fill or Not to Fill (25 分)(贪心,思维可以做出简单解)

    题意: 输入四个正数C,DIS,D,N(C<=100,DIS<=50000,D<=20,N<=500),分别代表油箱容积,杭州到目标城市的距离,每升汽油可以行驶的路程,加油站数 ...

  4. JS 一次性事件问题

    项目的需求就是不能重复提交 是通过click点击事件提交数据,到这里的时候想了很多办法,比如说销毁这个点击事件, 但是这个实现起来是相对比较麻烦的,后面想到了一个相对比较简单的办法 通过推荐判断 JS ...

  5. WebService介绍及C/C++访问

    一.什么是WebService? Web 服务是一个软件接口,它描述了一组可以在网络上通过标准化的 XML 消息传递访问的操作.它使用基于 XML 语言的协议来描述要执行的操作或者要与另一个 Web ...

  6. 创建私有yum仓库

    创建私有yum仓库

  7. 谁才是天朝最厉害的演员?让Python来为你揭晓!

    一.项目背景 上个月笔者的一个同学开了间影视投资公司,出于对创业人员的仰慕和影视投资行业的好奇,我就跟他寒暄了几句,聊天当中他提及到国庆节有部<攀登者>即将上映,预计票房会大好,因为吴京是 ...

  8. 01 MATLAB基本概念

    基本概念 整数类型 相同整数类型相乘还是整数 整数与浮点数相乘是这种整数类型 不同整数类型不能相乘,除非强制类型转换 整数与整数相乘: >> x = uint32(120); >&g ...

  9. python 中的富文本编译器

    第一种方式: 1,pip install django-tinymce 2,在INSTALL_APPS里面添加tinymce        在站点中使用: 配置setting.py TINYMCE_D ...

  10. Python作业篇 day03

    ###一.有变量name = 'aleX leNb',完成如下的操作 name = 'aleX leNb' name1 = ' aleX leNb ' #1.移除name1 变量对应的值两边的空格 , ...