1. 程式人生 > >Spark Streaming原始碼解讀之資料清理內幕徹底解密

Spark Streaming原始碼解讀之資料清理內幕徹底解密

本篇部落格的主要目的是:
1. 理清楚Spark Streaming中資料清理的流程

組織思路如下:
a) 背景
b) 如何研究Spark Streaming資料清理?
c) 原始碼解析

一:背景
Spark Streaming資料清理的工作無論是在實際開發中,還是自己動手實踐中都是會面臨的,Spark Streaming中Batch Durations中會不斷的產生RDD,這樣會不斷的有記憶體物件生成,其中包含元資料和資料本身。由此Spark Streaming本身會有一套產生元資料以及資料的清理機制。

二:如何研究Spark Streaming資料清理?

  1. 操作DStream的時候會產生元資料,所以要解決RDD的資料清理工作就一定要從DStream入手。因為DStream是RDD的模板,DStream之間有依賴關係。
    DStream的操作產生了RDD,接收資料也靠DStream,資料的輸入,資料的計算,輸出整個生命週期都是由DStream構建的。由此,DStream負責RDD的整個生命週期。因此研究的入口的是DStream。
  2. 基於Kafka資料來源,通過Direct的方式訪問Kafka,DStream隨著時間的進行,會不斷的在自己的記憶體資料結構中維護一個HashMap,HashMap維護的就是時間視窗,以及時間視窗下的RDD.按照Batch Duration來儲存RDD以及刪除RDD.
  3. Spark Streaming本身是一直在執行的,在自己計算的時候會不斷的產生RDD,例如每秒Batch Duration都會產生RDD,除此之外可能還有累加器,廣播變數。由於不斷的產生這些物件,因此Spark Streaming有自己的一套物件,元資料以及資料的清理機制。
  4. Spark Streaming對RDD的管理就相當於JVM的GC.

三:原始碼解析
generatedRDDs:安照Batch Duration的方式來儲存RDD以及刪除RDD。

// RDDs generated, marked as private[streaming] so that testsuites can access it
@transient
private[streaming] var generatedRDDs = new HashMap[Time, RDD[T]] ()

我們在實際開發中,可能手動快取,即使不快取的話,它在記憶體generatorRDD中也有物件,如何釋放他們?不僅僅是RDD本身,也包括資料來源(資料來源)和元資料(metada),因此釋放RDD的時候這三方面都需要考慮。
釋放跟時鐘Click有關係,因為資料是週期性產生,所以肯定是週期性釋放。


因此下一步就需要找JobGenerator

  1. RecurringTimer: 訊息迴圈器將訊息不斷的傳送給EventLoop
private val timer = new RecurringTimer(clock, ssc.graph.batchDuration.milliseconds,
  longTime => eventLoop.post(GenerateJobs(new Time(longTime))), "JobGenerator")
2.  eventLoop:onReceive接收到訊息。
/** Start generation of jobs */
def start(): Unit = synchronized {
  if (eventLoop != null) return // generator has already been started

  // Call checkpointWriter here to initialize it before eventLoop uses it to avoid a deadlock.
  // See SPARK-10125
  checkpointWriter

  eventLoop = new EventLoop[JobGeneratorEvent]("JobGenerator") {
    override protected def onReceive(event: JobGeneratorEvent): Unit = processEvent(event)

    override protected def onError(e: Throwable): Unit = {
      jobScheduler.reportError("Error in job generator", e)
    }
  }
3.  processEvent:中就會接收到ClearMetadata和ClearCheckpointData。
/** Processes all events */
private def processEvent(event: JobGeneratorEvent) {
  logDebug("Got event " + event)
  event match {
    case GenerateJobs(time) => generateJobs(time)
    case ClearMetadata(time) => clearMetadata(time)
    case DoCheckpoint(time, clearCheckpointDataLater) =>
      doCheckpoint(time, clearCheckpointDataLater)
    case ClearCheckpointData(time) => clearCheckpointData(time)
  }
}
4.  clearMetadata:清楚元資料資訊。
/** Clear DStream metadata for the given `time`. */
private def clearMetadata(time: Time) {
  ssc.graph.clearMetadata(time)

  // If checkpointing is enabled, then checkpoint,
  // else mark batch to be fully processed
  if (shouldCheckpoint) {
    eventLoop.post(DoCheckpoint(time, clearCheckpointDataLater = true))
  } else {
    // If checkpointing is not enabled, then delete metadata information about
    // received blocks (block data not saved in any case). Otherwise, wait for
    // checkpointing of this batch to complete.
    val maxRememberDuration = graph.getMaxInputStreamRememberDuration()
    jobScheduler.receiverTracker.cleanupOldBlocksAndBatches(time - maxRememberDuration)
    jobScheduler.inputInfoTracker.cleanup(time - maxRememberDuration)
    markBatchFullyProcessed(time)
  }
}
5.  DStreamGraph:首先會清理outputDStream,其實就是forEachDStream
def clearMetadata(time: Time) {
  logDebug("Clearing metadata for time " + time)
  this.synchronized {
    outputStreams.foreach(_.clearMetadata(time))
  }
  logDebug("Cleared old metadata for time " + time)
}
6.  DStream.clearMetadata:除了清除RDD,也可以清除metadata元資料。如果想RDD跨Batch Duration的話可以設定rememberDuration時間. rememberDuration一般都是Batch Duration的倍數。
/**
 * Clear metadata that are older than `rememberDuration` of this DStream.
 * This is an internal method that should not be called directly. This default
 * implementation clears the old generated RDDs. Subclasses of DStream may override
 * this to clear their own metadata along with the generated RDDs.
 */
private[streaming] def clearMetadata(time: Time) {
  val unpersistData = ssc.conf.getBoolean("spark.streaming.unpersist", true)
// rememberDuration記憶週期 檢視下RDD是否是oldRDD
  val oldRDDs = generatedRDDs.filter(_._1 <= (time - rememberDuration))
  logDebug("Clearing references to old RDDs: [" +
    oldRDDs.map(x => s"${x._1} -> ${x._2.id}").mkString(", ") + "]")
//從generatedRDDs中將key清理掉。
  generatedRDDs --= oldRDDs.keys
  if (unpersistData) {
    logDebug("Unpersisting old RDDs: " + oldRDDs.values.map(_.id).mkString(", "))
    oldRDDs.values.foreach { rdd =>
      rdd.unpersist(false)
      // Explicitly remove blocks of BlockRDD
      rdd match {
        case b: BlockRDD[_] =>
          logInfo("Removing blocks of RDD " + b + " of time " + time)
          b.removeBlocks() //清理掉RDD的資料
        case _ =>
      }
    }
  }
  logDebug("Cleared " + oldRDDs.size + " RDDs that were older than " +
    (time - rememberDuration) + ": " + oldRDDs.keys.mkString(", "))
//依賴的DStream也需要清理掉。
  dependencies.foreach(_.clearMetadata(time))
}
7.  在BlockRDD中,BlockManagerMaster根據blockId將Block刪除。刪除Block的操作是不可逆的。
/**
 * Remove the data blocks that this BlockRDD is made from. NOTE: This is an
 * irreversible operation, as the data in the blocks cannot be recovered back
 * once removed. Use it with caution.
 */
private[spark] def removeBlocks() {
  blockIds.foreach { blockId =>
    sparkContext.env.blockManager.master.removeBlock(blockId)
  }
  _isValid = false
}

回到上面JobGenerator中的processEvent
1. clearCheckpoint:清除快取資料。

/** Clear DStream checkpoint data for the given `time`. */
private def clearCheckpointData(time: Time) {
  ssc.graph.clearCheckpointData(time)

  // All the checkpoint information about which batches have been processed, etc have
  // been saved to checkpoints, so its safe to delete block metadata and data WAL files
  val maxRememberDuration = graph.getMaxInputStreamRememberDuration()
  jobScheduler.receiverTracker.cleanupOldBlocksAndBatches(time - maxRememberDuration)
  jobScheduler.inputInfoTracker.cleanup(time - maxRememberDuration)
  markBatchFullyProcessed(time)
}
2.  clearCheckpointData:
def clearCheckpointData(time: Time) {
  logInfo("Clearing checkpoint data for time " + time)
  this.synchronized {
    outputStreams.foreach(_.clearCheckpointData(time))
  }
  logInfo("Cleared checkpoint data for time " + time)
}
3.  ClearCheckpointData: 和清除元資料資訊一樣,還是清除DStream依賴的快取資料。
private[streaming] def clearCheckpointData(time: Time) {
  logDebug("Clearing checkpoint data")
  checkpointData.cleanup(time)
  dependencies.foreach(_.clearCheckpointData(time))
  logDebug("Cleared checkpoint data")
}
4.  DStreamCheckpointData:清除快取的資料
/**
 * Cleanup old checkpoint data. This gets called after a checkpoint of `time` has been
 * written to the checkpoint directory.
 */
def cleanup(time: Time) {
  // Get the time of the oldest checkpointed RDD that was written as part of the
  // checkpoint of `time`
  timeToOldestCheckpointFileTime.remove(time) match {
    case Some(lastCheckpointFileTime) =>
      // Find all the checkpointed RDDs (i.e. files) that are older than `lastCheckpointFileTime`
      // This is because checkpointed RDDs older than this are not going to be needed
      // even after master fails, as the checkpoint data of `time` does not refer to those files
      val filesToDelete = timeToCheckpointFile.filter(_._1 < lastCheckpointFileTime)
      logDebug("Files to delete:\n" + filesToDelete.mkString(","))
      filesToDelete.foreach {
        case (time, file) =>
          try {
            val path = new Path(file)
            if (fileSystem == null) {
              fileSystem = path.getFileSystem(dstream.ssc.sparkContext.hadoopConfiguration)
            }
            fileSystem.delete(path, true)
            timeToCheckpointFile -= time
            logInfo("Deleted checkpoint file '" + file + "' for time " + time)
          } catch {
            case e: Exception =>
              logWarning("Error deleting old checkpoint file '" + file + "' for time " + time, e)
              fileSystem = null
          }
      }
    case None =>
      logDebug("Nothing to delete")
  }
}

至此我們也知道了清理的過程,全流程如下:
這裡寫圖片描述

但是清理是什麼時候被觸發的?
1. 在最終提交Job的時候,是交給JobHandler去執行的。

private class JobHandler(job: Job) extends Runnable with Logging {
    import JobScheduler._

    def run() {
      try {
        val formattedTime = UIUtils.formatBatchTime(
          job.time.milliseconds, ssc.graph.batchDuration.milliseconds, showYYYYMMSS = false)
        val batchUrl = s"/streaming/batch/?id=${job.time.milliseconds}"
        val batchLinkText = s"[output operation ${job.outputOpId}, batch time ${formattedTime}]"

        ssc.sc.setJobDescription(
          s"""Streaming job from <a href="$batchUrl">$batchLinkText</a>""")
        ssc.sc.setLocalProperty(BATCH_TIME_PROPERTY_KEY, job.time.milliseconds.toString)
        ssc.sc.setLocalProperty(OUTPUT_OP_ID_PROPERTY_KEY, job.outputOpId.toString)

        // We need to assign `eventLoop` to a temp variable. Otherwise, because
        // `JobScheduler.stop(false)` may set `eventLoop` to null when this method is running, then
        // it's possible that when `post` is called, `eventLoop` happens to null.
        var _eventLoop = eventLoop
        if (_eventLoop != null) {
          _eventLoop.post(JobStarted(job, clock.getTimeMillis()))
          // Disable checks for existing output directories in jobs launched by the streaming
          // scheduler, since we may need to write output to an existing directory during checkpoint
          // recovery; see SPARK-4835 for more details.
          PairRDDFunctions.disableOutputSpecValidation.withValue(true) {
            job.run()
          }
          _eventLoop = eventLoop
          if (_eventLoop != null) {
//當Job完成的時候,eventLoop會發訊息初始化onReceive
            _eventLoop.post(JobCompleted(job, clock.getTimeMillis()))
          }
        } else {
          // JobScheduler has been stopped.
        }
      } finally {
        ssc.sc.setLocalProperty(JobScheduler.BATCH_TIME_PROPERTY_KEY, null)
        ssc.sc.setLocalProperty(JobScheduler.OUTPUT_OP_ID_PROPERTY_KEY, null)
      }
    }
  }
}
2.  OnReceive初始化接收到訊息JobCompleted.
def start(): Unit = synchronized {
  if (eventLoop != null) return // scheduler has already been started

  logDebug("Starting JobScheduler")
  eventLoop = new EventLoop[JobSchedulerEvent]("JobScheduler") {
    override protected def onReceive(event: JobSchedulerEvent): Unit = processEvent(event)

    override protected def onError(e: Throwable): Unit = reportError("Error in job scheduler", e)
  }
  eventLoop.start()
3.  processEvent:
private def processEvent(event: JobSchedulerEvent) {
  try {
    event match {
      case JobStarted(job, startTime) => handleJobStart(job, startTime)
      case JobCompleted(job, completedTime) => handleJobCompletion(job, completedTime)
      case ErrorReported(m, e) => handleError(m, e)
    }
  } catch {
    case e: Throwable =>
      reportError("Error in job scheduler", e)
  }
}
4.  呼叫JobGenerator的onBatchCompletion方法清楚元資料。
private def handleJobCompletion(job: Job, completedTime: Long) {
  val jobSet = jobSets.get(job.time)
  jobSet.handleJobCompletion(job)
  job.setEndTime(completedTime)
  listenerBus.post(StreamingListenerOutputOperationCompleted(job.toOutputOperationInfo))
  logInfo("Finished job " + job.id + " from job set of time " + jobSet.time)
  if (jobSet.hasCompleted) {
    jobSets.remove(jobSet.time)
    jobGenerator.onBatchCompletion(jobSet.time)
    logInfo("Total delay: %.3f s for time %s (execution: %.3f s)".format(
      jobSet.totalDelay / 1000.0, jobSet.time.toString,
      jobSet.processingDelay / 1000.0
    ))
    listenerBus.post(StreamingListenerBatchCompleted(jobSet.toBatchInfo))
  }
  job.result match {
    case Failure(e) =>
      reportError("Error running job " + job, e)
    case _ =>
  }
}

觸發流程如下:
這裡寫圖片描述

相關推薦

Spark Streaming原始碼解讀資料清理內幕徹底解密

本篇部落格的主要目的是: 1. 理清楚Spark Streaming中資料清理的流程 組織思路如下: a) 背景 b) 如何研究Spark Streaming資料清理? c) 原始碼解析

Spark 定製版:010~Spark Streaming原始碼解讀資料不斷接收全生命週期徹底研究和思考

本講內容: a. 資料接收架構設計模式 b. 資料接收原始碼徹底研究 注:本講內容基於Spark 1.6.1版本(在2016年5月來說是Spark最新版本)講解。 上節回顧 上一講中,我們給大傢俱體分析了Receiver啟動的方式及其啟動設計帶來的多個

Spark——Streaming原始碼解析資料的產生與匯入

此文是從思維導圖中匯出稍作調整後生成的,思維腦圖對程式碼瀏覽支援不是很好,為了更好閱讀體驗,文中涉及到的原始碼都是刪除掉不必要的程式碼後的虛擬碼,如需獲取更好閱讀體驗可下載腦圖配合閱讀: 此博文共分為四個部分: DAG定義 Job動態生成 資料的產生與匯入 容錯 資料的產生與匯入主要分為以下五個部分

Spark Streaming原始碼解讀Receiver在Driver的精妙實現全生命週期徹底研究和思考

在Spark Streaming中對於ReceiverInputDStream來說,都是現實一個Receiver,用來接收資料。而Receiver可以有很多個,並且執行在不同的worker節點上。這些Receiver都是由ReceiverTracker來管理的。

Spark 定製版:015~Spark Streaming原始碼解讀No Receivers徹底思考

本講內容: a. Direct Acess b. Kafka 注:本講內容基於Spark 1.6.1版本(在2016年5月來說是Spark最新版本)講解。 上節回顧 上一講中,我們講Spark Streaming中一個非常重要的內容:State狀態管理

Spark 定製版:013~Spark Streaming原始碼解讀Driver容錯安全性

本講內容: a. ReceiverBlockTracker容錯安全性 b. DStreamGraph和JobGenerator容錯安全性 注:本講內容基於Spark 1.6.1版本(在2016年5月來說是Spark最新版本)講解。 上節回顧 上一講中,

第15課:Spark Streaming原始碼解讀No Receivers徹底思考

背景:      目前No Receivers在企業中使用的越來越多。No Receivers具有更強的控制度,語義一致性。No Receivers是我們操作資料來源自然方式,操作資料來源使用一個封裝器,且是RDD型別的。所以Spark Streaming就產生了自定義R

Spark Streaming原始碼解讀No Receivers詳解

背景: 目前No Receivers在企業中使用的越來越多。No Receivers具有更強的控制度,語義一致性。No Receivers是我們操作資料來源自然方式,操作資料來源使用一個封裝器,且是RDD型別的。所以Spark Streaming就產生了自定義

Spark Streaming原始碼解讀Driver中的ReceiverTracker詳解

本篇博文的目標是: Driver的ReceiverTracker接收到資料之後,下一步對資料是如何進行管理 一:ReceiverTracker的架構設計 1. Driver在Executor啟動Receiver方式,每個Receiver都封裝成一個Tas

Spark定製班第9課:Spark Streaming原始碼解讀Receiver在Driver的精妙實現全生命週期徹底研究和思考

本期內容: 1. Receiver啟動的方式設想 2. Receiver啟動原始碼徹底分析 1. Receiver啟動的方式設想   Spark Streaming是個執行在Spark Core上的應用程式。這個應用程式既要接收資料,還要處理資料,這些都是在分散式的

Spark Streaming原始碼解讀State管理updateStateByKey和mapWithState解密

源地址:http://blog.csdn.net/snail_gesture/article/details/5151058 背景:  整個Spark Streaming是按照Batch Duractions劃分Job的。但是很多時候我們需要算過去的一天甚

Spark——Streaming原始碼解析容錯

此文是從思維導圖中匯出稍作調整後生成的,思維腦圖對程式碼瀏覽支援不是很好,為了更好閱讀體驗,文中涉及到的原始碼都是刪除掉不必要的程式碼後的虛擬碼,如需獲取更好閱讀體驗可下載腦圖配合閱讀: 此博文共分為四個部分: DAG定義 Job動態生成 資料的產生與匯入 容錯 ​ 策略 優點 缺點 (1) 熱備

Spark——Streaming原始碼解析DAG定義

此文是從思維導圖中匯出稍作調整後生成的,思維腦圖對程式碼瀏覽支援不是很好,為了更好閱讀體驗,文中涉及到的原始碼都是刪除掉不必要的程式碼後的虛擬碼,如需獲取更好閱讀體驗可下載腦圖配合閱讀: 此博文共分為四個部分: DAG定義 Job動態生成 資料的產生與匯入 容錯 1. DStream 1.1. RD

Vue原始碼解讀資料繫結

原文地址:https://banggan.github.io/2019/01/08/Vue原始碼解讀之資料繫結/ 從最開始vue初始化到渲染的整個流程如下:new Vue----一系列的初始化----$mount做掛載—如果是帶編譯的版本就compile,沒有就跳過—render函式—生

Spark MLlib原始碼解讀樸素貝葉斯分類器,NaiveBayes

Spark MLlib 樸素貝葉斯NaiveBayes 原始碼分析 基本原理介紹 首先是基本的條件概率求解的公式。 P(A|B)=P(AB)P(B) 在現實生活中,我們經常會碰到已知一個條件概率,求得兩個時間交換後的概率的問題。也就是在已知P(A

Spark Streaming從Flume Poll資料案例實戰和內幕原始碼解密

本博文內容主要包括以下幾點內容: 1、Spark Streaming on Polling from Flume實戰 2、Spark Streaming on Polling from Flume原始碼 一、推模式(Flume push SparkStre

Spark原始碼解讀RDD構建和轉換過程

上一節講了Spark原始碼解讀之Context的初始化過程,發現其實一行簡單的new SparkContext(sparkConf)程式碼,spark內部會去做很多事情。這節主要講RDD的構建和轉換過

【1】pytorch torchvision原始碼解讀Alexnet

最近開始學習一個新的深度學習框架PyTorch。 框架中有一個非常重要且好用的包:torchvision,顧名思義這個包主要是關於計算機視覺cv的。這個包主要由3個子包組成,分別是:torchvision.datasets、torchvision.models、torchvision.trans

java原始碼解讀HashMap

1:首先下載openjdk(http://pan.baidu.com/s/1dFMZXg1),把原始碼匯入eclipse,以便看到jdk原始碼            Windows-Prefe

Detectron原始碼解讀-roidb資料結構

roidb資料結構 roidb的型別是list, 其中的每個元素的資料型別都是dict, roidb列表的長度為資料集的數量(即圖片的數量), roidb中每個元素的詳細情況如下表所示: for entry in roidb 資料型別