Spark源碼分析之-Storage模塊

原文連接:http://jerryshao.me/architecture/2013/10/08/spark-storage-module-analysis/java

Background

前段時間雜事頗多,一直沒有時間整理本身的博客,Spark源碼分析寫到一半也擱置了。以前介紹了deployscheduler兩大模塊,此次介紹Spark中的另外一大模塊 - storage模塊。node

在寫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相應接口來實現。app

Storage模塊通訊層

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

communication layer class chart

其次咱們來看看各個類在master和slave上所扮演的不一樣角色:dom

communication character class chart

對於master和slave,BlockManager的建立有所不一樣:ide

  • 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 =newBlockManagerMaster(registerOrLookup(
  15. "BlockManagerMaster",
  16. newBlockManagerMasterActor(isLocal)))
  17. val blockManager =newBlockManager(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. privatedef 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. privatedefregister(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. }elseif(!blockManagerInfo.contains(id)){
  5. blockManagerIdByExecutor.get(id.executorId) match {
  6. caseSome(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. caseNone=>
  12. blockManagerIdByExecutor(id.executorId)= id
  13. }
  14. blockManagerInfo(id)=newBlockManagerMasterActor.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=newMemoryStore(this, maxMemory)
  2. private[storage] val diskStore:DiskStore=
  3. newDiskStore(this,System.getProperty("spark.local.dir",System.getProperty("java.io.tmpdir")))
  4. privatedef 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. privatedef createLocalDirs():Array[File]={
  2. logDebug("Creating local directories at root dirs '"+ rootDirs +"'")
  3. val dateFormat =newSimpleDateFormat("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 =newRandom()
  10. while(!foundLocalDir && tries < MAX_DIR_CREATION_ATTEMPTS){
  11. tries +=1
  12. try{
  13. localDirId ="%s-%04x".format(dateFormat.format(newDate), rand.nextInt(65536))
  14. localDir =newFile(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. privatedef 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 =newFile(localDirs(dirId),"%02x".format(subDirId))
  16. newDir.mkdir()
  17. subDirs(dirId)(subDirId)= newDir
  18. newDir
  19. }
  20. }
  21. }
  22. newFile(subDir, blockId)
  23. }

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

  1. overridedef 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 =newRandomAccessFile(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. overridedef 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. caseclassEntry(value:Any, size:Long, deserialized:Boolean)
  2. private val entries =newLinkedHashMap[String,Entry](32,0.75f,true)

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

  1. overridedef 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 =newArrayBuffer[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. privatedef 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 =newEntry(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. overridedef getValues(blockId:String):Option[Iterator[Any]]={
  2. val entry = entries.synchronized{
  3. entries.get(blockId)
  4. }
  5. if(entry ==null){
  6. None
  7. }elseif(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 =newBlockInfo(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. caseRight(newBytes)=> bytesAfterPut = newBytes
  44. caseLeft(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. caseRight(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. thrownewSparkException(
  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. defget(blockId:String):Option[Iterator[Any]]={
  2. val local= getLocal(blockId)
  3. if(local.isDefined){
  4. logInfo("Found block %s locally".format(blockId))
  5. returnlocal
  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. returnNone
  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. caseSome(iterator)=>
  19. returnSome(iterator)
  20. caseNone=>
  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. caseSome(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 =newArrayBuffer[Any]
  33. elements ++= iterator
  34. memoryStore.putValues(blockId, elements, level,true).data match {
  35. caseLeft(iterator2)=>
  36. returnSome(iterator2)
  37. case _ =>
  38. thrownewException("Memory store did not return back an iterator")
  39. }
  40. caseNone=>
  41. thrownewException("Block "+ blockId +" not found on disk, though it should be")
  42. }
  43. }elseif(level.useMemory &&!level.deserialized){
  44. // Read it as a byte buffer into memory first, then return it
  45. diskStore.getBytes(blockId) match {
  46. caseSome(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. returnSome(dataDeserialize(blockId, bytes))
  56. caseNone=>
  57. thrownewException("Block "+ blockId +" not found on disk, though it should be")
  58. }
  59. }else{
  60. diskStore.getValues(blockId) match {
  61. caseSome(iterator)=>
  62. returnSome(iterator)
  63. caseNone=>
  64. thrownewException("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. returnNone
  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. thrownewIllegalArgumentException("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. returnSome(dataDeserialize(blockId, data))
  15. }
  16. logDebug("The value of block "+ blockId +" is null")
  17. }
  18. logDebug("Block "+ blockId +" not found")
  19. returnNone
  20. }

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

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

Partition如何轉化爲Block

在storage模塊裏面全部的操做都是和block相關的,可是在RDD裏面全部的運算都是基於partition的,那麼partition是如何與block對應上的呢?

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

  1. finaldef 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. caseSome(values)=>
  7. // Partition is already materialized, so just return its values
  8. return values.asInstanceOf[Iterator[T]]
  9. caseNone=>
  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. caseSome(values)=>
  25. return values.asInstanceOf[Iterator[T]]
  26. caseNone=>
  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 =newArrayBuffer[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模塊有一個總體的印象之後再去分析細節的實現會有事半功倍的效果。

相關文章
相關標籤/搜索