当前位置: 移动技术网 > IT编程>软件设计>架构 > spark的存储系统--BlockManager源码分析

spark的存储系统--BlockManager源码分析

2019年06月10日  | 移动技术网IT编程  | 我要评论

spark的存储系统--blockmanager源码分析

根据之前的一系列分析,我们对spark作业从创建到调度分发,到执行,最后结果回传driver的过程有了一个大概的了解。但是在分析源码的过程中也留下了大量的问题,最主要的就是涉及到的spark中重要的几个基础模块,我们对这些基础设施的内部细节并不是很了解,之前走读源码时基本只是大概了解每个模块的作用以及对外的主要接口,这些重要的模块包括blockmananger, memorymananger, shufflemanager, mapoutputtracker, rpc模块nettyrpcenv,以及broadcastmanager。 而对于调度系统涉及到的几个类包括dagschedulermanager, taskschedulermanager, coarsegrainedschedulerbackend, coarsegrainedexecutorbackend, executor, taskrunner,我们之前已经做了较为详细的分析,因此这几个模块暂告一段落。
本篇,我们来看一下spark中最基础的一个的模块--存储系统blockmanager的内部实现。

blockmanager调用时机

首先,我们来整理一下在一个作业的运行过程中都有哪些地方使用到了blockmanager。

  • dagscheduler.getcachelocs。这个方法的调用是在提交一个stage时,需要获取分区的偏向位置时会调用该方法。我们知道rdd是可以缓存的,而rdd的缓存就是通过blockmanager来管理的,有一个专门的rddblockid用来表示一个rdd缓存块的唯一标识。

      最终调用的方法是:blockmanagermaster.getlocations(blockids)
  • 广播变量。在dagscheduler中提交stage时需要把rdd和shuffledependency(对于resultstage则是一个函数)对象序列化用于网络传输,实际上序列化后的字节数组是通过broadcastmanager组件进行网络传输的,而broadcastmanager实际又是通过blockmananger来将要广播的数据存储成block,并在executor端发送rpc请求向blockmanangermaster请求数据。每个广播变量会对应一个torrentbroadcast对象,torrentbroadcast对象内的writeblocks和readblocks是读写广播变量的方法,

      最终调用的方法是:blockmanager.putsingle和blockmanager.putbytes
  • shuffle的map阶段输出。如果我们没有启动外部shuffle服务及externalshuffle,那么就会用spark自己的shuffle机制,在map阶段输出时通过blockmanager对输出的文件进行管理。shuffle这部分主要使用的是diskblockmanager组件。

      最终调用的是:diskblockmanager相关方法包括createtempshuffleblock,getdiskwriter,
      diskblockobjectwriter相关方法,包括write方法和commitandget方法
  • 任务运行结果序列化后传回driver。这里分为两种情况,如果结果序列化后体积较小,小于maxdirectresultsize,则直接通过rpc接口传回,如果体积较大,就需要先通过blockmanager写入executor几点的内存和磁盘中,然后在driver端进行拉取。

      最终调用的是:blockmanager.putbytes

此外,我们还注意到,以上几种情形中使用的blockid都是不同的,具体可以看一下blockid.scala文件中关于各种blockid的定义。
所以,接下来,我们的思路就很清晰了,以上面提到的对blockmanager的方法调用为切入点进行分析。

blockmanagermaster.getlocations

这个方法用于获取指定的blockid对应的块所在存储位置。

def getlocations(blockids: array[blockid]): indexedseq[seq[blockmanagerid]] = {
driverendpoint.asksync[indexedseq[seq[blockmanagerid]]](
  getlocationsmultipleblockids(blockids))

}

这里向driverendpoint发送了一个getlocations消息,注意这里的driverendpoint并不是driverendpoint的端点引用,在sparkenv的构造过程我们可以看到,这是一个blockmanagermasterendpoint端点的引用。所以我们需要在blockmanagermasterendpoint中寻找对于该消息的处理。注意,由于这里调用了ask方法,所以在服务端是由receiveandreply方法来处理并响应的。

blockmanagermasterendpoint.receiveandreply

我们截取了对getlocations处理的部分代码

case getlocationsmultipleblockids(blockids) =>
  context.reply(getlocationsmultipleblockids(blockids))

调用的是getlocations方法:

private def getlocations(blockid: blockid): seq[blockmanagerid] = {
  if (blocklocations.containskey(blockid)) blocklocations.get(blockid).toseq else seq.empty
}

这个方法很简单,就是直接从缓存中查找blockid对应的位置,位置信息用blockmanagerid封装。那么缓存中的信息什么时候加进去呢?当然是写入新的block并更新block位置信息的时候,后面的会分析到。

blockmanager.putsingle

这个方法写入一个有单个对象组成的块,

def putsingle[t: classtag](
  blockid: blockid,
  value: t,
  level: storagelevel,
  tellmaster: boolean = true): boolean = {
putiterator(blockid, iterator(value), level, tellmaster)
}

可以看到,把对象包装成了一个只有一个元素的迭代器,然后调用putiterator方法,最后调用doputiterator方法

blockmanager.doputiterator

上面的方法,最终调用了doputiterator方法。

private def doputiterator[t](
  blockid: blockid,
  iterator: () => iterator[t],
  level: storagelevel,
  classtag: classtag[t],
  tellmaster: boolean = true,
  keepreadlock: boolean = false): option[partiallyunrollediterator[t]] = {
//
doput(blockid, level, classtag, tellmaster = tellmaster, keepreadlock = keepreadlock) { info =>
  val starttimems = system.currenttimemillis
  var iteratorfromfailedmemorystoreput: option[partiallyunrollediterator[t]] = none
  // size of the block in bytes
  var size = 0l
  // 如果存储等级中包含内存级别,那么我们优先写入内存中
  if (level.usememory) {
    // put it in memory first, even if it also has usedisk set to true;
    // we will drop it to disk later if the memory store can't hold it.
    // 对于不进行序列化的情况,只能存储内存中
    if (level.deserialized) {
      memorystore.putiteratorasvalues(blockid, iterator(), classtag) match {
        case right(s) =>
          size = s
        case left(iter) =>
          // not enough space to unroll this block; drop to disk if applicable
          // 内存空间不够时,如果存储等级允许磁盘,则存储到磁盘中
          if (level.usedisk) {
            logwarning(s"persisting block $blockid to disk instead.")
            diskstore.put(blockid) { channel =>
              val out = channels.newoutputstream(channel)
              // 注意对于存储到磁盘的情况一定是要序列化的
              serializermanager.dataserializestream(blockid, out, iter)(classtag)
            }
            size = diskstore.getsize(blockid)
          } else {
            iteratorfromfailedmemorystoreput = some(iter)
          }
      }
    } else { // !level.deserialized
      // 以序列化的形式进行存储
      memorystore.putiteratorasbytes(blockid, iterator(), classtag, level.memorymode) match {
        case right(s) =>
          size = s
        case left(partiallyserializedvalues) =>
          // not enough space to unroll this block; drop to disk if applicable
          if (level.usedisk) {
            logwarning(s"persisting block $blockid to disk instead.")
            diskstore.put(blockid) { channel =>
              val out = channels.newoutputstream(channel)
              partiallyserializedvalues.finishwritingtostream(out)
            }
            size = diskstore.getsize(blockid)
          } else {
            iteratorfromfailedmemorystoreput = some(partiallyserializedvalues.valuesiterator)
          }
      }
    }
  } else if (level.usedisk) {// 对于存储级别不允许存入内存的情况,我们只能选择存入磁盘
    diskstore.put(blockid) { channel =>
      val out = channels.newoutputstream(channel)
      // 存储到磁盘是一定要序列化的
      serializermanager.dataserializestream(blockid, out, iterator())(classtag)
    }
    size = diskstore.getsize(blockid)
  }

  // 获取刚刚刚刚写入的块的状态信息
  val putblockstatus = getcurrentblockstatus(blockid, info)
  val blockwassuccessfullystored = putblockstatus.storagelevel.isvalid
  // 如果块存储成功,那么进行接下来的动作
  if (blockwassuccessfullystored) {
    // now that the block is in either the memory or disk store, tell the master about it.
    info.size = size
    // 向driver汇报块信息
    if (tellmaster && info.tellmaster) {
      reportblockstatus(blockid, putblockstatus)
    }
    // 更新任务度量系统中关于块信息的相关统计值
    addupdatedblockstatustotaskmetrics(blockid, putblockstatus)
    logdebug("put block %s locally took %s".format(blockid, utils.getusedtimems(starttimems)))
    // 如果副本数大于1,那么需要进行额外的复制
    if (level.replication > 1) {
      val remotestarttime = system.currenttimemillis
      val bytestoreplicate = dogetlocalbytes(blockid, info)
      // [spark-16550] erase the typed classtag when using default serialization, since
      // nettyblockrpcserver crashes when deserializing repl-defined classes.
      // todo(ekl) remove this once the classloader issue on the remote end is fixed.
      val remoteclasstag = if (!serializermanager.canusekryo(classtag)) {
        scala.reflect.classtag[any]
      } else {
        classtag
      }
      try {
        replicate(blockid, bytestoreplicate, level, remoteclasstag)
      } finally {
        bytestoreplicate.dispose()
      }
      logdebug("put block %s remotely took %s"
        .format(blockid, utils.getusedtimems(remotestarttime)))
    }
  }
  assert(blockwassuccessfullystored == iteratorfromfailedmemorystoreput.isempty)
  iteratorfromfailedmemorystoreput
}
}

总结一下这段代码的主要逻辑:

  • 如果存储等级允许存入内存,那么优先存入内存中。根据存储的数据是否需要序列化分别选择调用memorystore的不同方法。
  • 如果存储等级不允许内存,那么只能存入磁盘中,存入磁盘中的数据一定是经过序列化的,这点要注意。
  • 向blockmanagermaster汇报刚写入的块的位置信息
  • 更新任务度量系统中关于块信息的相关统计值
  • 如果副本数大于1,那么需要进行额外的复制

从上面的步骤可以看到,在完成数据写入后,会通过rpc调用向blockmanagermaster汇报块的信息,这也解答了blockmanagermaster.getlocations方法从内存的map结构中查询块的位置信息的来源。

单纯就存储数据来说,最重要的无疑是内存管理器memorystore和磁盘管理器diskstore。
对于memorystore和diskstore调用的存储方法有:

memorystore.putiteratorasvalues
memorystore.putiteratorasbytes
diskstore.put(blockid: blockid)(writefunc: writablebytechannel => unit): unit 
diskstore.getsize(blockid)

blockmanager.putbytes

我们再来接着看另一个写入方法,putbytes,即写入字节数组数据。它的实际写入的逻辑在doputbytes方法中,我们看一下这个方法:

blockmanager.doputbytes

这个方法的主要步骤与doputiterator方法差不多。只不过doputiterator方法插入的是java对象,如果存储级别要求序列化或者存储到磁盘时,需要将对象序列化。

private def doputbytes[t](
  blockid: blockid,
  bytes: chunkedbytebuffer,
  level: storagelevel,
  classtag: classtag[t],
  tellmaster: boolean = true,
  keepreadlock: boolean = false): boolean = {
doput(blockid, level, classtag, tellmaster = tellmaster, keepreadlock = keepreadlock) { info =>
  val starttimems = system.currenttimemillis
  // since we're storing bytes, initiate the replication before storing them locally.
  // this is faster as data is already serialized and ready to send.
  // 启动副本复制
  val replicationfuture = if (level.replication > 1) {
    future {
      // this is a blocking action and should run in futureexecutioncontext which is a cached
      // thread pool. the bytebufferblockdata wrapper is not disposed of to avoid releasing
      // buffers that are owned by the caller.
      replicate(blockid, new bytebufferblockdata(bytes, false), level, classtag)
    }(futureexecutioncontext)
  } else {
    null
  }

  val size = bytes.size

  // 如果缓存级别中包含内存,优先写入内存中
  if (level.usememory) {
    // put it in memory first, even if it also has usedisk set to true;
    // we will drop it to disk later if the memory store can't hold it.
    // 是否以序列化形式存储
    val putsucceeded = if (level.deserialized) {
      val values =
        serializermanager.datadeserializestream(blockid, bytes.toinputstream())(classtag)
      memorystore.putiteratorasvalues(blockid, values, classtag) match {
        case right(_) => true
        case left(iter) =>
          // if putting deserialized values in memory failed, we will put the bytes directly to
          // disk, so we don't need this iterator and can close it to free resources earlier.
          iter.close()
          false
      }
    } else {
      // 如果以序列化格式存储,则不需要反序列化
      val memorymode = level.memorymode
      memorystore.putbytes(blockid, size, memorymode, () => {
        // 如果存在非直接内存,那么需要将数据拷贝一份到直接内存中
        if (memorymode == memorymode.off_heap &&
            bytes.chunks.exists(buffer => !buffer.isdirect)) {
          bytes.copy(platform.allocatedirectbuffer)
        } else {
          bytes
        }
      })
    }
    // 如果插入内存失败,并且允许写入磁盘的话,就将数据写入磁盘
    // 插入内存失败一般是因为内存不够引起
    if (!putsucceeded && level.usedisk) {
      logwarning(s"persisting block $blockid to disk instead.")
      diskstore.putbytes(blockid, bytes)
    }
  } else if (level.usedisk) {// 如果只允许存储到磁盘,那就只能存到磁盘了
    // 存储到磁盘的数据一定是序列化的
    diskstore.putbytes(blockid, bytes)
  }

  // 刚刚插入的块的信息
  val putblockstatus = getcurrentblockstatus(blockid, info)
  val blockwassuccessfullystored = putblockstatus.storagelevel.isvalid
  if (blockwassuccessfullystored) {
    // now that the block is in either the memory or disk store,
    // tell the master about it.
    info.size = size
    // 向driver端的blockmanagermaster组件汇报块信息
    if (tellmaster && info.tellmaster) {
      reportblockstatus(blockid, putblockstatus)
    }
    // 更新任务度量值
    addupdatedblockstatustotaskmetrics(blockid, putblockstatus)
  }
  logdebug("put block %s locally took %s".format(blockid, utils.getusedtimems(starttimems)))
  if (level.replication > 1) {
    // wait for asynchronous replication to finish
    // 等待之前启动的副本复制线程完成
    // 注意这里的超时被设成了无穷大
    try {
      threadutils.awaitready(replicationfuture, duration.inf)
    } catch {
      case nonfatal(t) =>
        throw new exception("error occurred while waiting for replication to finish", t)
    }
  }
  if (blockwassuccessfullystored) {
    none
  } else {
    some(bytes)
  }
}.isempty
}

对于memorystore和diskstore调用的方法有:

memorystore.putbytes
diskstore.putbytes(blockid, bytes)

总结

综上,我们把一个spark作业运行过程中需要调用到blockmanager的时机以及调用的blockmanager的一些写入数据的方法大致整理了一下。blockmanager主要是通过内部的两个组件memorystore和diskstore来管理数据向内存或磁盘写入的。此外diskblockmanager组件主要是用来管理block和磁盘文件之间的对应关系,分配文件路径,管理本地文件系统路径等作用。对于memorystore和diskstore的调用主要有如下几个方法:

memorystore.putiteratorasvalues
memorystore.putiteratorasbytes
diskstore.put(blockid: blockid)(writefunc: writablebytechannel => unit): unit 
diskstore.getsize(blockid)
memorystore.putbytes
diskstore.putbytes(blockid, bytes)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网