Spark Streaming 數(shù)據(jù)準備階段分析(Receiver方式)

—————?—————?—————?—————?—————?—————
Spark Streaming概述
Spark Streaming 初始化過程
Spark Streaming Receiver啟動過程分析
Spark Streaming 數(shù)據(jù)準備階段分析(Receiver方式)
Spark Streaming 數(shù)據(jù)計算階段分析
SparkStreaming Backpressure分析
Spark Streaming Executor DynamicAllocation 機制分析

—————?—————?—————?—————?—————?—————

1仰禀、Spark Streaming數(shù)據(jù)準備流程

SparkStreaming的全過程分為兩個階段:數(shù)據(jù)準備階段和數(shù)據(jù)計算階段典勇。兩個階段在功能上相互獨立馁启,僅通過數(shù)據(jù)聯(lián)系在一起。本文重點從源碼角度分析Spark Streaming數(shù)據(jù)準備階段的具體流程励翼。

Spark Streaming數(shù)據(jù)準備階段包含對流入數(shù)據(jù)的接收、分片(按照時間片劃分為數(shù)據(jù)集)以及分片數(shù)據(jù)的分發(fā)工作技矮。其轉(zhuǎn)數(shù)據(jù)的接收轉(zhuǎn)化過程主要有以下幾個關(guān)鍵步驟:

  1. Receiver接收外部數(shù)據(jù)流泳炉,其將接收的數(shù)據(jù)流交由BlockGenerator存儲在ArrayBuffer中,在存儲之前會先獲取許可(由“spark.streaming.receiver.maxRate”指定任洞,spark 1.5之后由backpressure進行自動計算蓄喇,代表可以存取的最大速率,每存儲一條數(shù)據(jù)獲取一個許可交掏,若未獲取到許可接收將阻塞)妆偏。
  2. BlockGenerater中定義一Timer,其依據(jù)設置的Interval定時將ArrayBuffer中的數(shù)據(jù)取出,包裝成Block,并將Block存放入blocksForPushing中(阻塞隊列ArrayBlockingQueue)盅弛,并將ArrayBuffer清空
  3. BlockGenerater中的blockPushingThread線程從阻塞隊列中取出取出block信息钱骂,并以onPushBlock的方式將消息通過監(jiān)聽器(listener)發(fā)送給ReceiverSupervisor.
  4. ReceiverSupervisor收到消息后叔锐,將對消息中攜帶數(shù)據(jù)進行處理,其會通過調(diào)用BlockManager對數(shù)據(jù)進行存儲见秽,并將存儲結(jié)果信息向ReceiverTracker匯報
  5. ReceiverTracker收到消息后愉烙,將信息存儲在未分配Block隊列(streamidToUnallocatedBlock)中,等待JobGenerator生成Job時將其指定給RDD

1過程持續(xù)進行解取,2-5 以BlockInterval為周期重復執(zhí)行.

2步责、源碼分析

以WordCount應用為例,程序見Spark Streaming概述

2.1 數(shù)據(jù)接收

在Receiver啟動之后肮蛹,其將開始接收外部數(shù)據(jù)源的數(shù)據(jù)(WordCount程序中使用的SocketReceiver是以主動接收的方式獲取數(shù)據(jù))勺择,并對數(shù)據(jù)進行存儲。SocketReceiver實現(xiàn)代碼如下:

 def receive() {
    try {
      val iterator = bytesToObjects(socket.getInputStream())
      while(!isStopped && iterator.hasNext) {
        store(iterator.next())
      }
  ......
  }

  /**
   * Store a single item of received data to Spark's memory.
   * These single items will be aggregated together into data blocks before
   * being pushed into Spark's memory.
   */
  def store(dataItem: T) {
    supervisor.pushSingle(dataItem)
  }

其中 supervisor的pushSingle()實現(xiàn)如下:

 /** Push a single record of received data into block generator. */
  def pushSingle(data: Any) {
    defaultBlockGenerator.addData(data)
  }

其調(diào)用defaultBlockGenerator的addData將數(shù)據(jù)添加進currentBuffer伦忠,其中defaultBlockGenerator 即為BlockGenerator,其addData方法如下:

 /**
   * Push a single data item into the buffer.
   */
  def addData(data: Any): Unit = {
    if (state == Active) {
      waitToPush()
      synchronized {
        if (state == Active) {
          currentBuffer += data
        } else {
          throw new SparkException(
            "Cannot add data as BlockGenerator has not been started or has been stopped")
        }
      }
    } else {
      throw new SparkException(
        "Cannot add data as BlockGenerator has not been started or has been stopped")
    }
  }

分析上述代碼省核,其中waitToPush()方法,是用來控制接收速率的昆码,與BackPressure機制相關(guān),"SparkStreaming Backpressure分析"一章會進行詳細分析气忠。當獲取到許可之后,數(shù)據(jù)將會存入currentBuffer中赋咽,并等待進行后續(xù)處理旧噪。
Receiver會不斷重復上述過程,接收數(shù)據(jù)脓匿,存入currentBuffer.

2.2 數(shù)據(jù)切片

"Spark Streaming Receiver啟動過程分析"提到淘钟,在啟動Receiver進會創(chuàng)建ReceiverSupervisorImpl, ReceiverSupervisorImpl又會創(chuàng)建并啟動BlockGenerator陪毡,用于對Receiver接收的數(shù)據(jù)流進行切片操作米母。其切片是以定時器的方式進行的。其時間周期由“spark.streaming.blockInterval”進行設置毡琉,默認為200ms.

BlockGenerator的start方法實現(xiàn)如下:

 /** Start block generating and pushing threads. */
  def start(): Unit = synchronized {
    if (state == Initialized) {
      state = Active
      blockIntervalTimer.start()
      blockPushingThread.start()
      logInfo("Started BlockGenerator")
    } else {
      throw new SparkException(
        s"Cannot start BlockGenerator as its not in the Initialized state [state = $state]")
    }
  }

其中

  • blockIntervalTimer為定時器任務铁瞒,其會周期性的執(zhí)行計劃任務
  private val blockIntervalMs = conf.getTimeAsMs("spark.streaming.blockInterval", "200ms")
  require(blockIntervalMs > 0, s"'spark.streaming.blockInterval' should be a positive value")

  private val blockIntervalTimer =
    new RecurringTimer(clock, blockIntervalMs, updateCurrentBuffer, "BlockGenerator")
  • blockPushingThread為新線程,負載不斷的從阻塞隊列中取出打包的數(shù)據(jù)
private val blockPushingThread = new Thread() { override def run() { keepPushingBlocks() } }

2.2.1 數(shù)據(jù)流切分

RecurringTimer為定時器桅滋,其每隔blockIntervalMs時間慧耍,執(zhí)行一次updateCurrentBuffer方法,將currentBuffer中的數(shù)據(jù)進行打包丐谋,并添加到阻塞隊列blocksForPushing中芍碧。

 /** Change the buffer to which single records are added to. */
  private def updateCurrentBuffer(time: Long): Unit = {
    try {
      var newBlock: Block = null
      synchronized {
        if (currentBuffer.nonEmpty) {   //如果buffer空,則不生成block.
          val newBlockBuffer = currentBuffer
          currentBuffer = new ArrayBuffer[Any]
          val blockId = StreamBlockId(receiverId, time - blockIntervalMs)
          listener.onGenerateBlock(blockId)
          newBlock = new Block(blockId, newBlockBuffer)
        }
      }

      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)
    }
  }

2.2.2 數(shù)據(jù)傳輸

blockPushingThread 線程啟動會号俐,將執(zhí)行keepPushingBlocks()方法师枣,從阻塞隊列中取出切片后的數(shù)據(jù),并通過defaultBlockGeneratorListener轉(zhuǎn)發(fā),并等待下一步存儲萧落、分發(fā)操作践美。(defaultBlockGeneratorListener在ReceiverSupervisorImpl中定義)。

/** 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)
    }
  }

其中pushBlock方法實現(xiàn)如下:

 private def pushBlock(block: Block) {
    listener.onPushBlock(block.id, block.buffer)
    logInfo("Pushed block " + block.id)
  }

2.3 Block 存儲與匯報

BlockGeneratorListener 監(jiān)控到onPushBlock事件后找岖,會對傳輸?shù)臄?shù)據(jù)分片進行存儲操作陨倡,并向ReceiverTracker匯報。

2.3.1 Block存儲

BlockGeneratorListener 監(jiān)控到onPushBlock事件后许布,經(jīng)過一系列調(diào)整兴革,最后將調(diào)用 pushAndReportBlock對數(shù)據(jù)分片進行存儲,pushAndReportBlock的實現(xiàn)如下:

/** Store block and report it to driver */
  def pushAndReportBlock(
      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")
  }

其中蜜唾,數(shù)據(jù)通過receivedBlockHandler存儲為Block, ReceivedBlockHandler有兩種實現(xiàn)

  • WriteAheadLogBasedBlockHandler 杂曲, 開啟WAL時會使用此實現(xiàn)
  • BlockManagerBasedBlockHandler,默認情況下會使用此實現(xiàn) 袁余。

BlockManagerBasedBlockHandler通過BlockManager的接口對數(shù)據(jù)在Receiver所在節(jié)點進行保存擎勘,并依據(jù)StorageLevel 設置的副本數(shù),在其它Executor中保存副本颖榜。保存副本的方法如下所示:

  /**
   * Replicate block to another node. Note that this is a blocking call that returns after
   * the block has been replicated.
   */
  private def replicate(
      blockId: BlockId,
      data: ChunkedByteBuffer,
      level: StorageLevel,
      classTag: ClassTag[_]): Unit = {
    ......
    var peersForReplication = blockReplicationPolicy.prioritize(
      blockManagerId,
      getPeers(false),
      mutable.HashSet.empty,
      blockId,
      numPeersToReplicateTo)
   ......
}

其中副本策略采用棚饵,隨機取樣的方式進行,


  /**
   * Method to prioritize a bunch of candidate peers of a block. This is a basic implementation,
   * that just makes sure we put blocks on different hosts, if possible
   *
   * @param blockManagerId Id of the current BlockManager for self identification
   * @param peers A list of peers of a BlockManager
   * @param peersReplicatedTo Set of peers already replicated to
   * @param blockId BlockId of the block being replicated. This can be used as a source of
   *                randomness if needed.
   * @return A prioritized list of peers. Lower the index of a peer, higher its priority
   */
  override def prioritize(
      blockManagerId: BlockManagerId,
      peers: Seq[BlockManagerId],
      peersReplicatedTo: mutable.HashSet[BlockManagerId],
      blockId: BlockId,
      numReplicas: Int): List[BlockManagerId] = {
    val random = new Random(blockId.hashCode)
    logDebug(s"Input peers : ${peers.mkString(", ")}")
    val prioritizedPeers = if (peers.size > numReplicas) {
      getSampleIds(peers.size, numReplicas, random).map(peers(_))
    } else {
      if (peers.size < numReplicas) {
        logWarning(s"Expecting ${numReplicas} replicas with only ${peers.size} peer/s.")
      }
      random.shuffle(peers).toList
    }
    logDebug(s"Prioritized peers : ${prioritizedPeers.mkString(", ")}")
    prioritizedPeers
  }

2.3.2 Block 匯報

當Block保存完成,并且副本制作完成后掩完,將通過trackerEndpoint向ReceiverTrack進行匯報噪漾。

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

ReceiverTrackEndpoint收到“AddBlock”信息后,將receivedBlockTracker將block信息保存入隊列streamIdToUnallocatedBlockQueues中且蓬,以用于生成Job欣硼。

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))
        }


  /** Add new blocks for the given stream */
  private def addBlock(receivedBlockInfo: ReceivedBlockInfo): Boolean = {
    receivedBlockTracker.addBlock(receivedBlockInfo)
  }

其中receivedBlockTracker的addBlock實現(xiàn)如下:


  /** Add received block. This event will get written to the write ahead log (if enabled). */
  def addBlock(receivedBlockInfo: ReceivedBlockInfo): Boolean = {
    try {
      val writeResult = writeToLog(BlockAdditionEvent(receivedBlockInfo))
      if (writeResult) {
        synchronized {
          getReceivedBlockQueue(receivedBlockInfo.streamId) += receivedBlockInfo
        }
        logDebug(s"Stream ${receivedBlockInfo.streamId} received " +
          s"block ${receivedBlockInfo.blockStoreResult.blockId}")
      } else {
        logDebug(s"Failed to acknowledge stream ${receivedBlockInfo.streamId} receiving " +
          s"block ${receivedBlockInfo.blockStoreResult.blockId} in the Write Ahead Log.")
      }
      writeResult
    } catch {
      case NonFatal(e) =>
        logError(s"Error adding block $receivedBlockInfo", e)
        false
    }
  }

  /** Get the queue of received blocks belonging to a particular stream */
  private def getReceivedBlockQueue(streamId: Int): ReceivedBlockQueue = {
    streamIdToUnallocatedBlockQueues.getOrElseUpdate(streamId, new ReceivedBlockQueue)
  }

至此數(shù)據(jù)準備階段完成,保存在streamIdToUnallocatedBlockQueues中的數(shù)據(jù)信息恶阴,在下一個批次生成Job時會被取出用于封裝成RDD诈胜,且注冊數(shù)據(jù)信息會轉(zhuǎn)移至timeToAllocatedBlocks中。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末存淫,一起剝皮案震驚了整個濱河市耘斩,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌桅咆,老刑警劉巖括授,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異岩饼,居然都是意外死亡荚虚,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門籍茧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來版述,“玉大人,你說我怎么就攤上這事寞冯】饰觯” “怎么了晚伙?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長俭茧。 經(jīng)常有香客問我咆疗,道長,這世上最難降的妖魔是什么母债? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任午磁,我火速辦了婚禮,結(jié)果婚禮上毡们,老公的妹妹穿的比我還像新娘迅皇。我一直安慰自己,他們只是感情好衙熔,可當我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布登颓。 她就那樣靜靜地躺著,像睡著了一般青责。 火紅的嫁衣襯著肌膚如雪挺据。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天脖隶,我揣著相機與錄音扁耐,去河邊找鬼。 笑死产阱,一個胖子當著我的面吹牛婉称,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播构蹬,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼王暗,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了庄敛?” 一聲冷哼從身側(cè)響起俗壹,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎藻烤,沒想到半個月后绷雏,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡怖亭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年涎显,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片兴猩。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡期吓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出倾芝,到底是詐尸還是另有隱情讨勤,我是刑警寧澤箭跳,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站悬襟,受9級特大地震影響衅码,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜脊岳,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望垛玻。 院中可真熱鬧割捅,春花似錦、人聲如沸帚桩。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽账嚎。三九已至莫瞬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間郭蕉,已是汗流浹背疼邀。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留召锈,地道東北人旁振。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像涨岁,于是被迫代替她去往敵國和親拐袜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容