SPARK中InMemoryFileIndex文件缓存导致的REFRESH TABLE tableName问题

简介: SPARK中InMemoryFileIndex文件缓存导致的REFRESH TABLE tableName问题

背景


在spark中,有时候会报出running ‘REFRESH TABLE tableName’ command in SQL or by recreating the Dataset/DataFrame involved.的错误,这种错误的原因有一种隐形的原因,那就是InMemoryFileIndex会缓存需要scan的文件在内存中,


分析


在scan file的过程中,最主要涉及的是CatalogFileIndex类,该类中的方法filterPartitions会创建InMemoryFileIndex

def filterPartitions(filters: Seq[Expression]): InMemoryFileIndex = {
    if (table.partitionColumnNames.nonEmpty) {
      val startTime = System.nanoTime()
      val selectedPartitions = sparkSession.sessionState.catalog.listPartitionsByFilter(
        table.identifier, filters)
      val partitions = selectedPartitions.map { p =>
        val path = new Path(p.location)
        val fs = path.getFileSystem(hadoopConf)
        PartitionPath(
          p.toRow(partitionSchema, sparkSession.sessionState.conf.sessionLocalTimeZone),
          path.makeQualified(fs.getUri, fs.getWorkingDirectory))
      }
      val partitionSpec = PartitionSpec(partitionSchema, partitions)
      val timeNs = System.nanoTime() - startTime
      new InMemoryFileIndex(sparkSession,
        rootPathsSpecified = partitionSpec.partitions.map(_.path),
        parameters = Map.empty,
        userSpecifiedSchema = Some(partitionSpec.partitionColumns),
        fileStatusCache = fileStatusCache,
        userSpecifiedPartitionSpec = Some(partitionSpec),
        metadataOpsTimeNs = Some(timeNs))
    } else {
      new InMemoryFileIndex(sparkSession, rootPaths, parameters = table.storage.properties,
        userSpecifiedSchema = None, fileStatusCache = fileStatusCache)
    }
  }

而在该InMemoryFileIndex中有成员变量fileStatusCache,该成员变量的赋值通过*FileStatusCache.getOrCreate(sparkSession)*而来:

def getOrCreate(session: SparkSession): FileStatusCache = synchronized {
    if (session.sqlContext.conf.manageFilesourcePartitions &&
      session.sqlContext.conf.filesourcePartitionFileCacheSize > 0) {
      if (sharedCache == null) {
        sharedCache = new SharedInMemoryCache(
          session.sqlContext.conf.filesourcePartitionFileCacheSize,
          session.sqlContext.conf.metadataCacheTTL
        )
      }
      sharedCache.createForNewClient()
    } else {
      NoopCache
    }
  }

SharedInMemoryCache的会调用guavaCacheBuilder方法:

var builder = CacheBuilder.newBuilder()
      .weigher(weigher)
      .removalListener(removalListener)
      .maximumWeight(maxSizeInBytes / weightScale)
    if (cacheTTL > 0) {
      builder = builder.expireAfterWrite(cacheTTL, TimeUnit.SECONDS)
    }
    builder.build[(ClientId, Path), Array[FileStatus]]()

该方法会对最终要scan的文件进行缓存处理,该缓存文件的调用路径如下:

  FileSourceScanExec.doExecute => inputRDD => createBucketedReadRDD或者createNonBucketedReadRDD => dynamicallySelectedPartitions => selectedPartitions
   ||
   \/
   CatalogFileIndex.listFiles => filterPartitions
   ||
   \/
   InMemoryFileIndex.listFiles => partitionSpec => inferPartitioning => leafDirToChildrenFiles

其中cachedLeafDirToChildrenFiles的值会在InMemoryFileIndex对象初始化的时候进行赋值,对应的方法为refresh0

private def refresh0(): Unit = {
   val files = listLeafFiles(rootPaths)
   cachedLeafFiles =
     new mutable.LinkedHashMap[Path, FileStatus]() ++= files.map(f => f.getPath -> f)
   cachedLeafDirToChildrenFiles = files.toArray.groupBy(_.getPath.getParent)
   cachedPartitionSpec = null
 }

listLeafFiles方法就会对调用fileStatusCache.getLeafFile从而获取到缓存的文件路径


结论


文中提到的 REFRESH TABLE tableName’ command in SQL错误,在两个不同的jvm进程中对于同一个表的读写中回经常出现,这里有三个参数可以去设置:

spark.sql.hive.filesourcePartitionFileCacheSize
spark.sql.hive.manageFilesourcePartitions
spark.sql.metadataCacheTTLSeconds

其他


1.那为什么在同一个jvm中对一个表的读写不会报这种错误呢?那是因为,在一个jvm中,比如说是写了之后再读取,会进行refresh操作,从而调用fileStatusCache.invalidateAll()方法,最终使文件缓存失效.


拿SQL:insert overwrite table a举例,该语句最终会生成InsertIntoHadoopFsRelationCommand物理计划,该run方法最终会调用fileIndex的refresh方法,从而调用*fileStatusCache.invalidateAll()*方法:


2.spark.sql.metadataCacheTTLSeconds还有其他的作用


在开启spark.sql.hive.convertMetastoreParquet或者spark.sql.hive.convertMetastoreOrc的情况下,在转换对应的逻辑计划当中,如果缓存中存在对应的表,则会复用缓存中的,具体的方法在HiveMetastoreCatalog.convertToLogicalRelation 中 ,最主要的点是会公用同一个CatalogFileIndex对象,从而实现了文件的复用,从未导致问题

相关文章
|
6月前
|
存储 缓存
.NET 6中Startup.cs文件注入本地缓存策略与服务生命周期管理实践:AddTransient, AddScoped, AddSingleton。
记住,选择正确的服务生命周期并妥善管理它们是至关重要的,因为它们直接影响你的应用程序的性能和行为。就像一个成功的建筑工地,工具箱如果整理得当,工具选择和使用得当,工地的整体效率将会大大提高。
252 0
|
10月前
|
存储 数据挖掘 虚拟化
vsan数据恢复—vsan缓存盘故障导致虚拟机磁盘文件丢失的数据恢复案例
VMware vsan架构采用2+1模式。每台设备只有一个磁盘组(7+1),缓存盘的大小为240GB,容量盘的大小为1.2TB。 由于其中一台主机(0号组设备)的缓存盘出现故障,导致VMware虚拟化环境中搭建的2台虚拟机的磁盘文件(vmdk)丢失。
|
10月前
|
存储 缓存 分布式计算
【赵渝强老师】Spark RDD的缓存机制
Spark RDD通过`persist`或`cache`方法可将计算结果缓存,但并非立即生效,而是在触发action时才缓存到内存中供重用。`cache`方法实际调用了`persist(StorageLevel.MEMORY_ONLY)`。RDD缓存可能因内存不足被删除,建议结合检查点机制保证容错。示例中,读取大文件并多次调用`count`,使用缓存后执行效率显著提升,最后一次计算仅耗时98ms。
297 0
【赵渝强老师】Spark RDD的缓存机制
|
SQL 缓存 Java
JVM知识体系学习三:class文件初始化过程、硬件层数据一致性(硬件层)、缓存行、指令乱序执行问题、如何保证不乱序(volatile等)
这篇文章详细介绍了JVM中类文件的初始化过程、硬件层面的数据一致性问题、缓存行和伪共享、指令乱序执行问题,以及如何通过`volatile`关键字和`synchronized`关键字来保证数据的有序性和可见性。
190 3
|
存储 缓存 分布式计算
大数据-89 Spark 集群 RDD 编程-高阶 编写代码、RDD依赖关系、RDD持久化/缓存
大数据-89 Spark 集群 RDD 编程-高阶 编写代码、RDD依赖关系、RDD持久化/缓存
180 4
|
JSON 分布式计算 大数据
大数据-85 Spark 集群 RDD创建 RDD-Action Key-Value RDD详解 RDD的文件输入输出
大数据-85 Spark 集群 RDD创建 RDD-Action Key-Value RDD详解 RDD的文件输入输出
163 1
|
缓存 NoSQL Linux
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
330 1
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
|
消息中间件 分布式计算 Kafka
大数据-99 Spark 集群 Spark Streaming DStream 文件数据流、Socket、RDD队列流
大数据-99 Spark 集群 Spark Streaming DStream 文件数据流、Socket、RDD队列流
196 0
|
存储 缓存 NoSQL
【Azure Redis 缓存 Azure Cache For Redis】如何设置让Azure Redis中的RDB文件暂留更久(如7天)
【Azure Redis 缓存 Azure Cache For Redis】如何设置让Azure Redis中的RDB文件暂留更久(如7天)
143 1
|
存储 缓存 API
file_cache: 使用文件缓存函数结果
file_cache: 使用文件缓存函数结果
199 15