Spark Streaming源码解读之流数据不断接收全生命周期彻底研究和思考

Spark Streaming应用程序有以下特点:

1. 不断持续接收数据

2.  Receiver和Driver不在同一节点中

       Spark Streaming应用程序接收数据、存储数据、汇报数据的metedata给Driver。数据接收的模式类似于MVC,其中Driver是Model,Receiver是View,ReceiverSupervisorImpl是Controller。Receiver的启动由ReceiverSupervisorImpl来控制,Receiver接收到数据交给ReceiverSupervisorImpl来存储。RDD中的元素必须要实现序列化,才能将RDD序列化给Executor端。Receiver就实现了Serializable接口。


ReceiverTracker的代码片段:

// Create the RDD using the scheduledLocations to run the receiver in a Spark job

val receiverRDD: RDD[Receiver[_]] =

if (scheduledLocations.isEmpty) {

ssc.sc.makeRDD(Seq(receiver), 1)

} else {

val preferredLocations = scheduledLocations.map(_.toString).distinct

ssc.sc.makeRDD(Seq(receiver -> preferredLocations))

}

Receiver的代码片段:

@DeveloperApi

abstract class Receiver[T](val storageLevel: StorageLevel) extends Serializable {

处理Receiver接收到的数据,存储数据并汇报给Driver,Receiver是一条一条的接收数据的。

/**

* Concrete implementation of [[org.apache.spark.streaming.receiver.ReceiverSupervisor]]

* which provides all the necessary functionality for handling the data received by

* the receiver. Specifically, it creates a [[org.apache.spark.streaming.receiver.BlockGenerator]]

* object that is used to divide the received data stream into blocks of data.

*/

private[streaming] class ReceiverSupervisorImpl(

receiver: Receiver[_],

env: SparkEnv,

hadoopConf: Configuration,

checkpointDirOption: Option[String]

) extends ReceiverSupervisor(receiver, env.conf) with Logging {

通过限定数据存储速度来实现限流接收数据,合并成buffer,放入block队列在ReceiverSupervisorImpl启动会调用BlockGenerator对象的start方法。

override protected def onStart() {

registeredBlockGenerators.foreach { _.start() }

...

private val registeredBlockGenerators = new mutable.ArrayBuffer[BlockGenerator]

with mutable.SynchronizedBuffer[BlockGenerator]

      源码注释说明了BlockGenerator把一个Receiver接收到的数据合并到一个Block然后写入到BlockManager中。该类内部有两个线程,一个是周期性把数据生成一批对象,然后把先前的一批数据封装成Block。另一个线程时把Block写入到BlockManager中。

private val defaultBlockGenerator = createBlockGenerator(defaultBlockGeneratorListener)

BlockGenerator类继承自RateLimiter类,说明我们不能限定接收数据的速度,但是可以限定存储数据的速度,转过来就限定流动的速度。

BlockGenerator类有一个定时器(默认每200ms将接收到的数据合并成block)和一个线程(把block写入到BlockManager),200ms会产生一个Block,即1秒钟生成5个Partition。太小则生成的数据片中数据太小,导致一个Task处理的数据少,性能差。实际经验得到不要低于50ms。

BlockGenerator代码片段:

private val blockIntervalTimer =

new RecurringTimer(clock, blockIntervalMs, updateCurrentBuffer, "BlockGenerator")

...

private val blockPushingThread = new Thread() { override def run() { keepPushingBlocks() } }

那BlockGenerator是怎么被创建的?

private val defaultBlockGenerator = createBlockGenerator(defaultBlockGeneratorListener)

...

override def createBlockGenerator(

blockGeneratorListener: BlockGeneratorListener): BlockGenerator = {

// Cleanup BlockGenerators that have already been stopped

registeredBlockGenerators --= registeredBlockGenerators.filter{ _.isStopped() }

val newBlockGenerator = new BlockGenerator(blockGeneratorListener, streamId, env.conf)

registeredBlockGenerators += newBlockGenerator

newBlockGenerator

}

BlockGenerator类中的定时器会回调updateCurrentBuffer方法。

Receiver不断的接收数据,BlockGenerator类通过一个定时器,把Receiver接收到的数据,把多条合并成Block,再放入到Block队列中。

/** Change the buffer to which single records are added to. */

private def updateCurrentBuffer(time: Long): Unit = {

try {

var newBlock: Block = null

// 不同线程都会访问currentBuffer,故需加锁

synchronized {

// 如果缓冲器不为空,则生成StreamBlockId对象,

// 调用listener的onGenerateBlock来通知Block已生成,

// 再实例化block对象。

if (currentBuffer.nonEmpty) {

val newBlockBuffer = currentBuffer

currentBuffer = new ArrayBuffer[Any]

val blockId = StreamBlockId(receiverId, time - blockIntervalMs)

listener.onGenerateBlock(blockId)

newBlock = new Block(blockId, newBlockBuffer)

}

}

// 最后,把Block对象放入

if (newBlock != null) {

blocksForPushing.put(newBlock)  // put is blocking when queue is full

}

} catch {

case ie: InterruptedException =>

logInfo("Block updating timer thread was interrupted")

case e: Exception =>

reportError("Error in block updating thread", e)

}

}

该函数200ms回调一次,可以设置,但不能小于50ms。

运行在Executor端的ReceiverSupervisorImpl需要与Driver端的ReceiverTracker进行通信,传递元数据信息metedata,其中ReceiverSupervisorImpl通过RPC的名称获取到ReceiverTrcker的远程调用。

ReceiverSupervisorImpl代码片段:

/** Remote RpcEndpointRef for the ReceiverTracker */

private val trackerEndpoint = RpcUtils.makeDriverRef("ReceiverTracker", env.conf, env.rpcEnv)

在ReceiverTracker调用start方法启动的时候,会以ReceiverTracker的名称创建RPC通信体。ReceiverSupervisorImpl就是和这个RPC通信体进行消息交互的。

/** Start the endpoint and receiver execution thread. */

def start(): Unit = synchronized {

if (isTrackerStarted) {

throw new SparkException("ReceiverTracker already started")

}

if (!receiverInputStreams.isEmpty) {

endpoint = ssc.env.rpcEnv.setupEndpoint(

"ReceiverTracker", newReceiverTrackerEndpoint(ssc.env.rpcEnv))

if (!skipReceiverLaunch) launchReceivers()

logInfo("ReceiverTracker started")

trackerState = Started

}

}

在ReceiverTrackerEndpoint接收到ReceiverSupervisorImpl发送的注册消息,把其RpcEndpoint保存起来。

override def receiveAndReply(context: RpcCallContext): PartialFunction[Any, Unit] = {

// Remote messages

caseRegisterReceiver(streamId, typ, host, executorId,receiverEndpoint) =>

val successful =

registerReceiver(streamId, typ, host, executorId, receiverEndpoint, context.senderAddress)

context.reply(successful)

case AddBlock(receivedBlockInfo) =>

if (WriteAheadLogUtils.isBatchingEnabled(ssc.conf, isDriver = true)) {

walBatchingThreadPool.execute(new Runnable {

override def run(): Unit = Utils.tryLogNonFatalError {

if (active) {

context.reply(addBlock(receivedBlockInfo))

} else {

throw new IllegalStateException("ReceiverTracker RpcEndpoint shut down.")

}

}

})

} else {

context.reply(addBlock(receivedBlockInfo))

}

case DeregisterReceiver(streamId, message, error) =>

deregisterReceiver(streamId, message, error)

context.reply(true)

// Local messages

case AllReceiverIds =>

context.reply(receiverTrackingInfos.filter(_._2.state != ReceiverState.INACTIVE).keys.toSeq)

case StopAllReceivers =>

assert(isTrackerStopping || isTrackerStopped)

stopReceivers()

context.reply(true)

}

对应的Executor端的ReceiverSupervisorImpl也会创建Rpc消息通信体,来接收来自Driver端ReceiverTacker的消息。

/** RpcEndpointRef for receiving messages from the ReceiverTracker in the driver */

private val endpoint = env.rpcEnv.setupEndpoint(

"Receiver-" + streamId + "-" + System.currentTimeMillis(), new ThreadSafeRpcEndpoint {

override val rpcEnv: RpcEnv = env.rpcEnv

override def receive: PartialFunction[Any, Unit] = {

case StopReceiver =>

logInfo("Received stop signal")

ReceiverSupervisorImpl.this.stop("Stopped by driver", None)

case CleanupOldBlocks(threshTime) =>

logDebug("Received delete old batch signal")

cleanupOldBlocks(threshTime)

case UpdateRateLimit(eps) =>

logInfo(s"Received a new rate limit: $eps.")

registeredBlockGenerators.foreach { bg =>

bg.updateRate(eps)

}

}

})

BlockGenerator类中的线程每隔10ms从队列中获取Block,写入到BlockManager中。

/** Keep pushing blocks to the BlockManager. */

private def keepPushingBlocks() {

logInfo("Started block pushing thread")

def areBlocksBeingGenerated: Boolean = synchronized {

state != StoppedGeneratingBlocks

}

try {

// While blocks are being generated, keep polling for to-be-pushed blocks and push them.

while (areBlocksBeingGenerated) {

Option(blocksForPushing.poll(10, TimeUnit.MILLISECONDS)) match {

case Some(block) =>pushBlock(block)

case None =>

}

}

// At this point, state is StoppedGeneratingBlock. So drain the queue of to-be-pushed blocks.

logInfo("Pushing out the last " + blocksForPushing.size() + " blocks")

while (!blocksForPushing.isEmpty) {

val block = blocksForPushing.take()

logDebug(s"Pushing block $block")

pushBlock(block)

logInfo("Blocks left to push " + blocksForPushing.size())

}

logInfo("Stopped block pushing thread")

} catch {

case ie: InterruptedException =>

logInfo("Block pushing thread was interrupted")

case e: Exception =>

reportError("Error in block pushing thread", e)

}

}

ReceiverSupervisorImpl代码片段:

/** Divides received data records into data blocks for pushing in BlockManager. */

private val defaultBlockGeneratorListener = new BlockGeneratorListener {

def onAddData(data: Any, metadata: Any): Unit = { }

def onGenerateBlock(blockId: StreamBlockId): Unit = { }

def onError(message: String, throwable: Throwable) {

reportError(message, throwable)

}

defonPushBlock(blockId: StreamBlockId, arrayBuffer: ArrayBuffer[_]) {

pushArrayBuffer(arrayBuffer, None, Some(blockId))

}

}

...

/** Store block and report it to driver */

defpushAndReportBlock(

receivedBlock: ReceivedBlock,

metadataOption: Option[Any],

blockIdOption: Option[StreamBlockId]

) {

val blockId = blockIdOption.getOrElse(nextBlockId)

val time = System.currentTimeMillis

val blockStoreResult = receivedBlockHandler.storeBlock(blockId, receivedBlock)

logDebug(s"Pushed block $blockId in ${(System.currentTimeMillis - time)} ms")

val numRecords = blockStoreResult.numRecords

val blockInfo = ReceivedBlockInfo(streamId, numRecords, metadataOption, blockStoreResult)

trackerEndpoint.askWithRetry[Boolean](AddBlock(blockInfo))

logDebug(s"Reported block $blockId")

}

将数据存储在BlockManager中,并将源数据信息告诉Driver端的ReceiverTracker。

defstoreBlock(blockId: StreamBlockId, block: ReceivedBlock): ReceivedBlockStoreResult = {

var numRecords = None: Option[Long]

val putResult: Seq[(BlockId, BlockStatus)] = block match {

case ArrayBufferBlock(arrayBuffer) =>

numRecords = Some(arrayBuffer.size.toLong)

blockManager.putIterator(blockId, arrayBuffer.iterator, storageLevel,

tellMaster = true)

case IteratorBlock(iterator) =>

val countIterator = new CountingIterator(iterator)

// 把数据写入BlockManager

val putResult =blockManager.putIterator(blockId, countIterator, storageLevel,

tellMaster = true)

numRecords = countIterator.count

putResult

case ByteBufferBlock(byteBuffer) =>

blockManager.putBytes(blockId, byteBuffer, storageLevel, tellMaster = true)

case o =>

throw new SparkException(

s"Could not store $blockId to block manager, unexpected block type ${o.getClass.getName}")

}

if (!putResult.map { _._1 }.contains(blockId)) {

throw new SparkException(

s"Could not store $blockId to block manager with storage level $storageLevel")

}

BlockManagerBasedStoreResult(blockId, numRecords)

}


备注:

资料来源于:DT_大数据梦工厂(Spark发行版本定制)

更多私密内容,请关注微信公众号:DT_Spark

如果您对大数据Spark感兴趣,可以免费听由王家林老师每天晚上20:00开设的Spark永久免费公开课,地址YY房间号:68917580

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容