Spark源碼解析——Storage模塊

Background

前段時間瑣事頗多,一直沒有時間整理自己的博客,Spark源碼分析寫到一半也擱置了。之前介紹了deployscheduler兩大模塊,這次介紹Spark中的另一大模塊 - storage模塊。

在寫Spark程序的時候我們常常和RDD ( Resilient Distributed Dataset ) 打交道,通過RDD爲我們提供的各種transformation和action接口實現我們的應用,RDD的引入提高了抽象層次,在接口和實現上進行有效地隔離,使用戶無需關心底層的實現。但是RDD提供給我們的僅僅是一個“”, 我們所操作的數據究竟放在哪裏,如何存取?它的“”是怎麼樣的?這是由storage模塊來實現和管理的,接下來我們就要剖析一下storage模塊。

Storage模塊整體架構

Storage模塊主要分爲兩層:

  1. 通信層:storage模塊採用的是master-slave結構來實現通信層,master和slave之間傳輸控制信息、狀態信息,這些都是通過通信層來實現的。
  2. 存儲層:storage模塊需要把數據存儲到disk或是memory上面,有可能還需replicate到遠端,這都是由存儲層來實現和提供相應接口。

而其他模塊若要和storage模塊進行交互,storage模塊提供了統一的操作類BlockManager,外部類與storage模塊打交道都需要通過調用BlockManager相應接口來實現。

Storage模塊通信層

首先來看一下通信層的UML類圖:

communication layer class chart

其次我們來看看各個類在master和slave上所扮演的不同角色:

communication character class chart

對於master和slave,BlockManager的創建有所不同:

  • Master (client driver)

    BlockManagerMaster擁有BlockManagerMasterActoractor和所有BlockManagerSlaveActorref

  • Slave (executor)

    對於slave,BlockManagerMaster則擁有BlockManagerMasterActorref和自身BlockManagerSlaveActoractor

BlockManagerMasterActorrefactor之間進行通信;BlockManagerSlaveActorrefactor之間通信。

actorref:

actorrefAkka中的兩個不同的actor reference,分別由actorOfactorFor所創建。actor類似於網絡服務中的server端,它保存所有的狀態信息,接收client端的請求執行並返回給客戶端;ref類似於網絡服務中的client端,通過向server端發起請求獲取結果。

BlockManager wrap了BlockManagerMaster,通過BlockManagerMaster進行通信。Spark會在client driver和executor端創建各自的BlockManager,通過BlockManager對storage模塊進行操作。

BlockManager對象在SparkEnv中被創建,創建的過程如下所示:

  1. def registerOrLookup(name: String, newActor: => Actor): ActorRef = {
  2. if (isDriver) {
  3. logInfo("Registering " + name)
  4. actorSystem.actorOf(Props(newActor), name = name)
  5. } else {
  6. val driverHost: String = System.getProperty("spark.driver.host", "localhost")
  7. val driverPort: Int = System.getProperty("spark.driver.port", "7077").toInt
  8. Utils.checkHost(driverHost, "Expected hostname")
  9. val url = "akka://spark@%s:%s/user/%s".format(driverHost, driverPort, name)
  10. logInfo("Connecting to " + name + ": " + url)
  11. actorSystem.actorFor(url)
  12. }
  13. }
  14. val blockManagerMaster = new BlockManagerMaster(registerOrLookup(
  15. "BlockManagerMaster",
  16. new BlockManagerMasterActor(isLocal)))
  17. val blockManager = new BlockManager(executorId, actorSystem, blockManagerMaster, serializer)

可以看到對於client driver和executor,Spark分別創建了BlockManagerMasterActor actorref,並被wrap到BlockManager中。

通信層傳遞的消息

  • BlockManagerMasterActor

    • executor to client driver

      RegisterBlockManager (executor創建BlockManager以後向client driver發送請求註冊自身) HeartBeat UpdateBlockInfo (更新block信息) GetPeers (請求獲得其他BlockManager的id) GetLocations (獲取block所在的BlockManager的id) GetLocationsMultipleBlockIds (獲取一組block所在的BlockManager id)

    • client driver to client driver

      GetLocations (獲取block所在的BlockManager的id) GetLocationsMultipleBlockIds (獲取一組block所在的BlockManager id) RemoveExecutor (刪除所保存的已經死亡的executor上的BlockManager) StopBlockManagerMaster (停止client driver上的BlockManagerMasterActor)

有些消息例如GetLocations在executor端和client driver端都會向actor請求,而其他的消息比如RegisterBlockManager只會由executor端的ref向client driver端的actor發送,於此同時例如RemoveExecutor則只會由client driver端的ref向client driver端的actor發送。

具體消息是從哪裏發送,哪裏接收和處理請看代碼細節,在這裏就不再贅述了。

  • BlockManagerSlaveActor

    • client driver to executor

      RemoveBlock (刪除block) RemoveRdd (刪除RDD)

通信層中涉及許多控制消息和狀態消息的傳遞以及處理,這些細節可以直接查看源碼,這裏就不在一一羅列。下面就只簡單介紹一下exeuctor端的BlockManager是如何啓動以及向client driver發送註冊請求完成註冊。

Register BlockManager

前面已經介紹了BlockManager對象是如何被創建出來的,當BlockManager被創建出來以後需要向client driver註冊自己,下面我們來看一下這個流程:

首先BlockManager會調用initialize()初始化自己

  1. private def initialize() {
  2. master.registerBlockManager(blockManagerId, maxMemory, slaveActor)
  3. ...
  4. if (!BlockManager.getDisableHeartBeatsForTesting) {
  5. heartBeatTask = actorSystem.scheduler.schedule(0.seconds, heartBeatFrequency.milliseconds) {
  6. heartBeat()
  7. }
  8. }
  9. }

initialized()函數中首先調用BlockManagerMaster向client driver註冊自己,同時設置heartbeat定時器,定時發送heartbeat報文。可以看到在註冊自身的時候向client driver傳遞了自身的slaveActor,client driver收到slaveActor以後會將其與之對應的BlockManagerInfo存儲到hash map中,以便後續通過slaveActor向executor發送命令。

BlockManagerMaster會將註冊請求包裝成RegisterBlockManager報文發送給client driver的BlockManagerMasterActorBlockManagerMasterActor調用register()函數註冊BlockManager

  1. private def register(id: BlockManagerId, maxMemSize: Long, slaveActor: ActorRef) {
  2. if (id.executorId == "<driver>" && !isLocal) {
  3. // Got a register message from the master node; don't register it
  4. } else if (!blockManagerInfo.contains(id)) {
  5. blockManagerIdByExecutor.get(id.executorId) match {
  6. case Some(manager) =>
  7. // A block manager of the same executor already exists.
  8. // This should never happen. Let's just quit.
  9. logError("Got two different block manager registrations on " + id.executorId)
  10. System.exit(1)
  11. case None =>
  12. blockManagerIdByExecutor(id.executorId) = id
  13. }
  14. blockManagerInfo(id) = new BlockManagerMasterActor.BlockManagerInfo(
  15. id, System.currentTimeMillis(), maxMemSize, slaveActor)
  16. }
  17. }

需要注意的是在client driver端也會執行上述過程,只是在最後註冊的時候如果判斷是"<driver>"就不進行任何操作。可以看到對應的BlockManagerInfo對象被創建並保存在hash map中。

Storage模塊存儲層

在RDD層面上我們瞭解到RDD是由不同的partition組成的,我們所進行的transformation和action是在partition上面進行的;而在storage模塊內部,RDD又被視爲由不同的block組成,對於RDD的存取是以block爲單位進行的,本質上partition和block是等價的,只是看待的角度不同。在Spark storage模塊中中存取數據的最小單位是block,所有的操作都是以block爲單位進行的。

首先我們來看一下存儲層的UML類圖:

storage layer class chart

BlockManager對象被創建的時候會創建出MemoryStoreDiskStore對象用以存取block,同時在initialize()函數中創建BlockManagerWorker對象用以監聽遠程的block存取請求來進行相應處理。

  1. private[storage] val memoryStore: BlockStore = new MemoryStore(this, maxMemory)
  2. private[storage] val diskStore: DiskStore =
  3. new DiskStore(this, System.getProperty("spark.local.dir", System.getProperty("java.io.tmpdir")))
  4. private def initialize() {
  5. ...
  6. BlockManagerWorker.startBlockManagerWorker(this)
  7. ...
  8. }

下面就具體介紹一下對於DiskStoreMemoryStore,block的存取操作是怎樣進行的。

DiskStore如何存取block

DiskStore可以配置多個folder,Spark會在不同的folder下面創建Spark文件夾,文件夾的命名方式爲(spark-local-yyyyMMddHHmmss-xxxx, xxxx是一個隨機數),所有的block都會存儲在所創建的folder裏面。DiskStore會在對象被創建時調用createLocalDirs()來創建文件夾:

  1. private def createLocalDirs(): Array[File] = {
  2. logDebug("Creating local directories at root dirs '" + rootDirs + "'")
  3. val dateFormat = new SimpleDateFormat("yyyyMMddHHmmss")
  4. rootDirs.split(",").map { rootDir =>
  5. var foundLocalDir = false
  6. var localDir: File = null
  7. var localDirId: String = null
  8. var tries = 0
  9. val rand = new Random()
  10. while (!foundLocalDir && tries < MAX_DIR_CREATION_ATTEMPTS) {
  11. tries += 1
  12. try {
  13. localDirId = "%s-%04x".format(dateFormat.format(new Date), rand.nextInt(65536))
  14. localDir = new File(rootDir, "spark-local-" + localDirId)
  15. if (!localDir.exists) {
  16. foundLocalDir = localDir.mkdirs()
  17. }
  18. } catch {
  19. case e: Exception =>
  20. logWarning("Attempt " + tries + " to create local dir " + localDir + " failed", e)
  21. }
  22. }
  23. if (!foundLocalDir) {
  24. logError("Failed " + MAX_DIR_CREATION_ATTEMPTS +
  25. " attempts to create local dir in " + rootDir)
  26. System.exit(ExecutorExitCode.DISK_STORE_FAILED_TO_CREATE_DIR)
  27. }
  28. logInfo("Created local directory at " + localDir)
  29. localDir
  30. }
  31. }

DiskStore裏面,每一個block都被存儲爲一個file,通過計算block id的hash值將block映射到文件中,block id與文件路徑的映射關係如下所示:

  1. private def getFile(blockId: String): File = {
  2. logDebug("Getting file for block " + blockId)
  3. // Figure out which local directory it hashes to, and which subdirectory in that
  4. val hash = Utils.nonNegativeHash(blockId)
  5. val dirId = hash % localDirs.length
  6. val subDirId = (hash / localDirs.length) % subDirsPerLocalDir
  7. // Create the subdirectory if it doesn't already exist
  8. var subDir = subDirs(dirId)(subDirId)
  9. if (subDir == null) {
  10. subDir = subDirs(dirId).synchronized {
  11. val old = subDirs(dirId)(subDirId)
  12. if (old != null) {
  13. old
  14. } else {
  15. val newDir = new File(localDirs(dirId), "%02x".format(subDirId))
  16. newDir.mkdir()
  17. subDirs(dirId)(subDirId) = newDir
  18. newDir
  19. }
  20. }
  21. }
  22. new File(subDir, blockId)
  23. }

根據block id計算出hash值,將hash取模獲得dirIdsubDirId,在subDirs中找出相應的subDir,若沒有則新建一個subDir,最後以subDir爲路徑、block id爲文件名創建file handler,DiskStore使用此file handler將block寫入文件內,代碼如下所示:

  1. override def putBytes(blockId: String, _bytes: ByteBuffer, level: StorageLevel) {
  2. // So that we do not modify the input offsets !
  3. // duplicate does not copy buffer, so inexpensive
  4. val bytes = _bytes.duplicate()
  5. logDebug("Attempting to put block " + blockId)
  6. val startTime = System.currentTimeMillis
  7. val file = createFile(blockId)
  8. val channel = new RandomAccessFile(file, "rw").getChannel()
  9. while (bytes.remaining > 0) {
  10. channel.write(bytes)
  11. }
  12. channel.close()
  13. val finishTime = System.currentTimeMillis
  14. logDebug("Block %s stored as %s file on disk in %d ms".format(
  15. blockId, Utils.bytesToString(bytes.limit), (finishTime - startTime)))
  16. }

而獲取block則非常簡單,找到相應的文件並讀取出來即可:

  1. override def getBytes(blockId: String): Option[ByteBuffer] = {
  2. val file = getFile(blockId)
  3. val bytes = getFileBytes(file)
  4. Some(bytes)
  5. }

因此在DiskStore中存取block首先是要將block id映射成相應的文件路徑,接着存取文件就可以了。

MemoryStore如何存取block

相對於DiskStore需要根據block id hash計算出文件路徑並將block存放到對應的文件裏面,MemoryStore管理block就顯得非常簡單:MemoryStore內部維護了一個hash map來管理所有的block,以block id爲key將block存放到hash map中。

  1. case class Entry(value: Any, size: Long, deserialized: Boolean)
  2. private val entries = new LinkedHashMap[String, Entry](32, 0.75f, true)

MemoryStore中存放block必須確保內存足夠容納下該block,若內存不足則會將block寫到文件中,具體的代碼如下所示:

  1. override def putBytes(blockId: String, _bytes: ByteBuffer, level: StorageLevel) {
  2. // Work on a duplicate - since the original input might be used elsewhere.
  3. val bytes = _bytes.duplicate()
  4. bytes.rewind()
  5. if (level.deserialized) {
  6. val values = blockManager.dataDeserialize(blockId, bytes)
  7. val elements = new ArrayBuffer[Any]
  8. elements ++= values
  9. val sizeEstimate = SizeEstimator.estimate(elements.asInstanceOf[AnyRef])
  10. tryToPut(blockId, elements, sizeEstimate, true)
  11. } else {
  12. tryToPut(blockId, bytes, bytes.limit, false)
  13. }
  14. }

tryToPut()中,首先調用ensureFreeSpace()確保空閒內存是否足以容納block,若可以則將該block放入hash map中進行管理;若不足以容納則通過調用dropFromMemory()將block寫入文件。

  1. private def tryToPut(blockId: String, value: Any, size: Long, deserialized: Boolean): Boolean = {
  2. // TODO: Its possible to optimize the locking by locking entries only when selecting blocks
  3. // to be dropped. Once the to-be-dropped blocks have been selected, and lock on entries has been
  4. // released, it must be ensured that those to-be-dropped blocks are not double counted for
  5. // freeing up more space for another block that needs to be put. Only then the actually dropping
  6. // of blocks (and writing to disk if necessary) can proceed in parallel.
  7. putLock.synchronized {
  8. if (ensureFreeSpace(blockId, size)) {
  9. val entry = new Entry(value, size, deserialized)
  10. entries.synchronized {
  11. entries.put(blockId, entry)
  12. currentMemory += size
  13. }
  14. if (deserialized) {
  15. logInfo("Block %s stored as values to memory (estimated size %s, free %s)".format(
  16. blockId, Utils.bytesToString(size), Utils.bytesToString(freeMemory)))
  17. } else {
  18. logInfo("Block %s stored as bytes to memory (size %s, free %s)".format(
  19. blockId, Utils.bytesToString(size), Utils.bytesToString(freeMemory)))
  20. }
  21. true
  22. } else {
  23. // Tell the block manager that we couldn't put it in memory so that it can drop it to
  24. // disk if the block allows disk storage.
  25. val data = if (deserialized) {
  26. Left(value.asInstanceOf[ArrayBuffer[Any]])
  27. } else {
  28. Right(value.asInstanceOf[ByteBuffer].duplicate())
  29. }
  30. blockManager.dropFromMemory(blockId, data)
  31. false
  32. }
  33. }
  34. }

而從MemoryStore中取得block則非常簡單,只需從hash map中取出block id對應的value即可。

  1. override def getValues(blockId: String): Option[Iterator[Any]] = {
  2. val entry = entries.synchronized {
  3. entries.get(blockId)
  4. }
  5. if (entry == null) {
  6. None
  7. } else if (entry.deserialized) {
  8. Some(entry.value.asInstanceOf[ArrayBuffer[Any]].iterator)
  9. } else {
  10. val buffer = entry.value.asInstanceOf[ByteBuffer].duplicate() // Doesn't actually copy data
  11. Some(blockManager.dataDeserialize(blockId, buffer))
  12. }
  13. }

Put or Get block through BlockManager

上面介紹了DiskStoreMemoryStore對於block的存取操作,那麼我們是要直接與它們交互存取數據嗎,還是封裝了更抽象的接口使我們無需關心底層?

BlockManager爲我們提供了put()get()函數,用戶可以使用這兩個函數對block進行存取而無需關心底層實現。

首先我們來看一下put()函數的實現:

  1. def put(blockId: String, values: ArrayBuffer[Any], level: StorageLevel,
  2. tellMaster: Boolean = true) : Long = {
  3. ...
  4. // Remember the block's storage level so that we can correctly drop it to disk if it needs
  5. // to be dropped right after it got put into memory. Note, however, that other threads will
  6. // not be able to get() this block until we call markReady on its BlockInfo.
  7. val myInfo = {
  8. val tinfo = new BlockInfo(level, tellMaster)
  9. // Do atomically !
  10. val oldBlockOpt = blockInfo.putIfAbsent(blockId, tinfo)
  11. if (oldBlockOpt.isDefined) {
  12. if (oldBlockOpt.get.waitForReady()) {
  13. logWarning("Block " + blockId + " already exists on this machine; not re-adding it")
  14. return oldBlockOpt.get.size
  15. }
  16. // TODO: So the block info exists - but previous attempt to load it (?) failed. What do we do now ? Retry on it ?
  17. oldBlockOpt.get
  18. } else {
  19. tinfo
  20. }
  21. }
  22. val startTimeMs = System.currentTimeMillis
  23. // If we need to replicate the data, we'll want access to the values, but because our
  24. // put will read the whole iterator, there will be no values left. For the case where
  25. // the put serializes data, we'll remember the bytes, above; but for the case where it
  26. // doesn't, such as deserialized storage, let's rely on the put returning an Iterator.
  27. var valuesAfterPut: Iterator[Any] = null
  28. // Ditto for the bytes after the put
  29. var bytesAfterPut: ByteBuffer = null
  30. // Size of the block in bytes (to return to caller)
  31. var size = 0L
  32. myInfo.synchronized {
  33. logTrace("Put for block " + blockId + " took " + Utils.getUsedTimeMs(startTimeMs)
  34. + " to get into synchronized block")
  35. var marked = false
  36. try {
  37. if (level.useMemory) {
  38. // Save it just to memory first, even if it also has useDisk set to true; we will later
  39. // drop it to disk if the memory store can't hold it.
  40. val res = memoryStore.putValues(blockId, values, level, true)
  41. size = res.size
  42. res.data match {
  43. case Right(newBytes) => bytesAfterPut = newBytes
  44. case Left(newIterator) => valuesAfterPut = newIterator
  45. }
  46. } else {
  47. // Save directly to disk.
  48. // Don't get back the bytes unless we replicate them.
  49. val askForBytes = level.replication > 1
  50. val res = diskStore.putValues(blockId, values, level, askForBytes)
  51. size = res.size
  52. res.data match {
  53. case Right(newBytes) => bytesAfterPut = newBytes
  54. case _ =>
  55. }
  56. }
  57. // Now that the block is in either the memory or disk store, let other threads read it,
  58. // and tell the master about it.
  59. marked = true
  60. myInfo.markReady(size)
  61. if (tellMaster) {
  62. reportBlockStatus(blockId, myInfo)
  63. }
  64. } finally {
  65. // If we failed at putting the block to memory/disk, notify other possible readers
  66. // that it has failed, and then remove it from the block info map.
  67. if (! marked) {
  68. // Note that the remove must happen before markFailure otherwise another thread
  69. // could've inserted a new BlockInfo before we remove it.
  70. blockInfo.remove(blockId)
  71. myInfo.markFailure()
  72. logWarning("Putting block " + blockId + " failed")
  73. }
  74. }
  75. }
  76. logDebug("Put block " + blockId + " locally took " + Utils.getUsedTimeMs(startTimeMs))
  77. // Replicate block if required
  78. if (level.replication > 1) {
  79. val remoteStartTime = System.currentTimeMillis
  80. // Serialize the block if not already done
  81. if (bytesAfterPut == null) {
  82. if (valuesAfterPut == null) {
  83. throw new SparkException(
  84. "Underlying put returned neither an Iterator nor bytes! This shouldn't happen.")
  85. }
  86. bytesAfterPut = dataSerialize(blockId, valuesAfterPut)
  87. }
  88. replicate(blockId, bytesAfterPut, level)
  89. logDebug("Put block " + blockId + " remotely took " + Utils.getUsedTimeMs(remoteStartTime))
  90. }
  91. BlockManager.dispose(bytesAfterPut)
  92. return size
  93. }

對於put()操作,主要分爲以下3個步驟:

  1. 爲block創建BlockInfo結構體存儲block相關信息,同時將其加鎖使其不能被訪問。
  2. 根據block的storage level將block存儲到memory或是disk上,同時解鎖標識該block已經ready,可被訪問。
  3. 根據block的replication數決定是否將該block replicate到遠端。

接着我們來看一下get()函數的實現:

  1. def get(blockId: String): Option[Iterator[Any]] = {
  2. val local = getLocal(blockId)
  3. if (local.isDefined) {
  4. logInfo("Found block %s locally".format(blockId))
  5. return local
  6. }
  7. val remote = getRemote(blockId)
  8. if (remote.isDefined) {
  9. logInfo("Found block %s remotely".format(blockId))
  10. return remote
  11. }
  12. None
  13. }

get()首先會從local的BlockManager中查找block,如果找到則返回相應的block,若local沒有找到該block,則發起請求從其他的executor上的BlockManager中查找block。在通常情況下Spark任務的分配是根據block的分佈決定的,任務往往會被分配到擁有block的節點上,因此getLocal()就能找到所需的block;但是在資源有限的情況下,Spark會將任務調度到與block不同的節點上,這樣就必須通過getRemote()來獲得block。

我們先來看一下getLocal():

  1. def getLocal(blockId: String): Option[Iterator[Any]] = {
  2. logDebug("Getting local block " + blockId)
  3. val info = blockInfo.get(blockId).orNull
  4. if (info != null) {
  5. info.synchronized {
  6. // In the another thread is writing the block, wait for it to become ready.
  7. if (!info.waitForReady()) {
  8. // If we get here, the block write failed.
  9. logWarning("Block " + blockId + " was marked as failure.")
  10. return None
  11. }
  12. val level = info.level
  13. logDebug("Level for block " + blockId + " is " + level)
  14. // Look for the block in memory
  15. if (level.useMemory) {
  16. logDebug("Getting block " + blockId + " from memory")
  17. memoryStore.getValues(blockId) match {
  18. case Some(iterator) =>
  19. return Some(iterator)
  20. case None =>
  21. logDebug("Block " + blockId + " not found in memory")
  22. }
  23. }
  24. // Look for block on disk, potentially loading it back into memory if required
  25. if (level.useDisk) {
  26. logDebug("Getting block " + blockId + " from disk")
  27. if (level.useMemory && level.deserialized) {
  28. diskStore.getValues(blockId) match {
  29. case Some(iterator) =>
  30. // Put the block back in memory before returning it
  31. // TODO: Consider creating a putValues that also takes in a iterator ?
  32. val elements = new ArrayBuffer[Any]
  33. elements ++= iterator
  34. memoryStore.putValues(blockId, elements, level, true).data match {
  35. case Left(iterator2) =>
  36. return Some(iterator2)
  37. case _ =>
  38. throw new Exception("Memory store did not return back an iterator")
  39. }
  40. case None =>
  41. throw new Exception("Block " + blockId + " not found on disk, though it should be")
  42. }
  43. } else if (level.useMemory && !level.deserialized) {
  44. // Read it as a byte buffer into memory first, then return it
  45. diskStore.getBytes(blockId) match {
  46. case Some(bytes) =>
  47. // Put a copy of the block back in memory before returning it. Note that we can't
  48. // put the ByteBuffer returned by the disk store as that's a memory-mapped file.
  49. // The use of rewind assumes this.
  50. assert (0 == bytes.position())
  51. val copyForMemory = ByteBuffer.allocate(bytes.limit)
  52. copyForMemory.put(bytes)
  53. memoryStore.putBytes(blockId, copyForMemory, level)
  54. bytes.rewind()
  55. return Some(dataDeserialize(blockId, bytes))
  56. case None =>
  57. throw new Exception("Block " + blockId + " not found on disk, though it should be")
  58. }
  59. } else {
  60. diskStore.getValues(blockId) match {
  61. case Some(iterator) =>
  62. return Some(iterator)
  63. case None =>
  64. throw new Exception("Block " + blockId + " not found on disk, though it should be")
  65. }
  66. }
  67. }
  68. }
  69. } else {
  70. logDebug("Block " + blockId + " not registered locally")
  71. }
  72. return None
  73. }

getLocal()首先會根據block id獲得相應的BlockInfo並從中取出該block的storage level,根據storage level的不同getLocal()又進入以下不同分支:

  1. level.useMemory == true:從memory中取出block並返回,若沒有取到則進入分支2。
  2. level.useDisk == true:
    • level.useMemory == true: 將block從disk中讀出並寫入內存以便下次使用時直接從內存中獲得,同時返回該block。
    • level.useMemory == false: 將block從disk中讀出並返回
  3. level.useDisk == false: 沒有在本地找到block,返回None。

接下來我們來看一下getRemote()

  1. def getRemote(blockId: String): Option[Iterator[Any]] = {
  2. if (blockId == null) {
  3. throw new IllegalArgumentException("Block Id is null")
  4. }
  5. logDebug("Getting remote block " + blockId)
  6. // Get locations of block
  7. val locations = master.getLocations(blockId)
  8. // Get block from remote locations
  9. for (loc <- locations) {
  10. logDebug("Getting remote block " + blockId + " from " + loc)
  11. val data = BlockManagerWorker.syncGetBlock(
  12. GetBlock(blockId), ConnectionManagerId(loc.host, loc.port))
  13. if (data != null) {
  14. return Some(dataDeserialize(blockId, data))
  15. }
  16. logDebug("The value of block " + blockId + " is null")
  17. }
  18. logDebug("Block " + blockId + " not found")
  19. return None
  20. }

getRemote()首先取得該block的所有location信息,然後根據location向遠端發送請求獲取block,只要有一個遠端返回block該函數就返回而不繼續發送請求。

至此我們簡單介紹了BlockManager類中的get()put()函數,使用這兩個函數外部類可以輕易地存取block數據。

Partition如何轉化爲Block

在storage模塊裏面所有的操作都是和block相關的,但是在RDD裏面所有的運算都是基於partition的,那麼partition是如何與block對應上的呢?

RDD計算的核心函數是iterator()函數:

  1. final def iterator(split: Partition, context: TaskContext): Iterator[T] = {
  2. if (storageLevel != StorageLevel.NONE) {
  3. SparkEnv.get.cacheManager.getOrCompute(this, split, context, storageLevel)
  4. } else {
  5. computeOrReadCheckpoint(split, context)
  6. }
  7. }

如果當前RDD的storage level不是NONE的話,表示該RDD在BlockManager中有存儲,那麼調用CacheManager中的getOrCompute()函數計算RDD,在這個函數中partition和block發生了關係:

首先根據RDD id和partition index構造出block id (rdd_xx_xx),接着從BlockManager中取出相應的block。

  • 如果該block存在,表示此RDD在之前已經被計算過和存儲在BlockManager中,因此取出即可,無需再重新計算。
  • 如果該block不存在則需要調用RDD的computeOrReadCheckpoint()函數計算出新的block,並將其存儲到BlockManager中。

需要注意的是block的計算和存儲是阻塞的,若另一線程也需要用到此block則需等到該線程block的loading結束。

  1. def getOrCompute[T](rdd: RDD[T], split: Partition, context: TaskContext, storageLevel: StorageLevel)
  2. : Iterator[T] = {
  3. val key = "rdd_%d_%d".format(rdd.id, split.index)
  4. logDebug("Looking for partition " + key)
  5. blockManager.get(key) match {
  6. case Some(values) =>
  7. // Partition is already materialized, so just return its values
  8. return values.asInstanceOf[Iterator[T]]
  9. case None =>
  10. // Mark the split as loading (unless someone else marks it first)
  11. loading.synchronized {
  12. if (loading.contains(key)) {
  13. logInfo("Another thread is loading %s, waiting for it to finish...".format (key))
  14. while (loading.contains(key)) {
  15. try {loading.wait()} catch {case _ : Throwable =>}
  16. }
  17. logInfo("Finished waiting for %s".format(key))
  18. // See whether someone else has successfully loaded it. The main way this would fail
  19. // is for the RDD-level cache eviction policy if someone else has loaded the same RDD
  20. // partition but we didn't want to make space for it. However, that case is unlikely
  21. // because it's unlikely that two threads would work on the same RDD partition. One
  22. // downside of the current code is that threads wait serially if this does happen.
  23. blockManager.get(key) match {
  24. case Some(values) =>
  25. return values.asInstanceOf[Iterator[T]]
  26. case None =>
  27. logInfo("Whoever was loading %s failed; we'll try it ourselves".format (key))
  28. loading.add(key)
  29. }
  30. } else {
  31. loading.add(key)
  32. }
  33. }
  34. try {
  35. // If we got here, we have to load the split
  36. logInfo("Partition %s not found, computing it".format(key))
  37. val computedValues = rdd.computeOrReadCheckpoint(split, context)
  38. // Persist the result, so long as the task is not running locally
  39. if (context.runningLocally) { return computedValues }
  40. val elements = new ArrayBuffer[Any]
  41. elements ++= computedValues
  42. blockManager.put(key, elements, storageLevel, true)
  43. return elements.iterator.asInstanceOf[Iterator[T]]
  44. } finally {
  45. loading.synchronized {
  46. loading.remove(key)
  47. loading.notifyAll()
  48. }
  49. }
  50. }
  51. }

這樣RDD的transformation、action就和block數據建立了聯繫,雖然抽象上我們的操作是在partition層面上進行的,但是partition最終還是被映射成爲block,因此實際上我們的所有操作都是對block的處理和存取。

End

本文就storage模塊的兩個層面進行了介紹-通信層和存儲層。通信層中簡單介紹了類結構和組成以及類在通信層中所扮演的不同角色,還有不同角色之間通信的報文,同時簡單介紹了通信層的啓動和註冊細節。存儲層中分別介紹了DiskStoreMemoryStore中對於block的存和取的實現代碼,同時分析了BlockManagerput()get()接口,最後簡單介紹了Spark RDD中的partition與BlockManager中的block之間的關係,以及如何交互存取block的。

本文從整體上分析了storage模塊的實現,並未就具體實現做非常細節的分析,相信在看完本文對storage模塊有一個整體的印象以後再去分析細節的實現會有事半功倍的效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章