-
Notifications
You must be signed in to change notification settings - Fork 29k
[SPARK-17063] [SQL] Improve performance of MSCK REPAIR TABLE with Hive metastore #14607
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f2f3150
repair table in batch
ec2d8da
add logging
c442b75
support managed table
b3797c9
speed up addPartition by gather the fast stats in parallel
1c490ef
refactor
f30e387
fix tests
a4d07db
fix tests
8a18bf7
add config, add partition in sequential
0672c89
Update SQLConf.scala
b58ce2a
address comments
48ae071
Merge branch 'repair_batch' of github.com:davies/spark into repair_batch
399e38e
Merge branch 'master' of github.com:apache/spark into repair_batch
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,12 +17,13 @@ | |
|
|
||
| package org.apache.spark.sql.execution.command | ||
|
|
||
| import scala.collection.GenSeq | ||
| import scala.collection.{GenMap, GenSeq} | ||
| import scala.collection.parallel.ForkJoinTaskSupport | ||
| import scala.concurrent.forkjoin.ForkJoinPool | ||
| import scala.util.control.NonFatal | ||
|
|
||
| import org.apache.hadoop.fs.{FileStatus, FileSystem, Path, PathFilter} | ||
| import org.apache.hadoop.conf.Configuration | ||
| import org.apache.hadoop.fs._ | ||
| import org.apache.hadoop.mapred.{FileInputFormat, JobConf} | ||
|
|
||
| import org.apache.spark.sql.{AnalysisException, Row, SparkSession} | ||
|
|
@@ -32,6 +33,7 @@ import org.apache.spark.sql.catalyst.catalog.CatalogTypes.TablePartitionSpec | |
| import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference} | ||
| import org.apache.spark.sql.execution.datasources.PartitioningUtils | ||
| import org.apache.spark.sql.types._ | ||
| import org.apache.spark.util.SerializableConfiguration | ||
|
|
||
| // Note: The definition of these commands are based on the ones described in | ||
| // https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL | ||
|
|
@@ -422,6 +424,9 @@ case class AlterTableDropPartitionCommand( | |
|
|
||
| } | ||
|
|
||
|
|
||
| case class PartitionStatistics(numFiles: Int, totalSize: Long) | ||
|
|
||
| /** | ||
| * Recover Partitions in ALTER TABLE: recover all the partition in the directory of a table and | ||
| * update the catalog. | ||
|
|
@@ -435,6 +440,31 @@ case class AlterTableDropPartitionCommand( | |
| case class AlterTableRecoverPartitionsCommand( | ||
| tableName: TableIdentifier, | ||
| cmd: String = "ALTER TABLE RECOVER PARTITIONS") extends RunnableCommand { | ||
|
|
||
| // These are list of statistics that can be collected quickly without requiring a scan of the data | ||
| // see https://github.com/apache/hive/blob/master/ | ||
| // common/src/java/org/apache/hadoop/hive/common/StatsSetupConst.java | ||
| val NUM_FILES = "numFiles" | ||
| val TOTAL_SIZE = "totalSize" | ||
| val DDL_TIME = "transient_lastDdlTime" | ||
|
|
||
| private def getPathFilter(hadoopConf: Configuration): PathFilter = { | ||
| // Dummy jobconf to get to the pathFilter defined in configuration | ||
| // It's very expensive to create a JobConf(ClassUtil.findContainingJar() is slow) | ||
| val jobConf = new JobConf(hadoopConf, this.getClass) | ||
| val pathFilter = FileInputFormat.getInputPathFilter(jobConf) | ||
| new PathFilter { | ||
| override def accept(path: Path): Boolean = { | ||
| val name = path.getName | ||
| if (name != "_SUCCESS" && name != "_temporary" && !name.startsWith(".")) { | ||
| pathFilter == null || pathFilter.accept(path) | ||
| } else { | ||
| false | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override def run(spark: SparkSession): Seq[Row] = { | ||
| val catalog = spark.sessionState.catalog | ||
| if (!catalog.tableExists(tableName)) { | ||
|
|
@@ -449,10 +479,6 @@ case class AlterTableRecoverPartitionsCommand( | |
| throw new AnalysisException( | ||
| s"Operation not allowed: $cmd on datasource tables: $tableName") | ||
| } | ||
| if (table.tableType != CatalogTableType.EXTERNAL) { | ||
| throw new AnalysisException( | ||
| s"Operation not allowed: $cmd only works on external tables: $tableName") | ||
| } | ||
| if (table.partitionColumnNames.isEmpty) { | ||
| throw new AnalysisException( | ||
| s"Operation not allowed: $cmd only works on partitioned tables: $tableName") | ||
|
|
@@ -463,19 +489,26 @@ case class AlterTableRecoverPartitionsCommand( | |
| } | ||
|
|
||
| val root = new Path(table.storage.locationUri.get) | ||
| logInfo(s"Recover all the partitions in $root") | ||
| val fs = root.getFileSystem(spark.sparkContext.hadoopConfiguration) | ||
| // Dummy jobconf to get to the pathFilter defined in configuration | ||
| // It's very expensive to create a JobConf(ClassUtil.findContainingJar() is slow) | ||
| val jobConf = new JobConf(spark.sparkContext.hadoopConfiguration, this.getClass) | ||
| val pathFilter = FileInputFormat.getInputPathFilter(jobConf) | ||
|
|
||
| val threshold = spark.conf.get("spark.rdd.parallelListingThreshold", "10").toInt | ||
| val hadoopConf = spark.sparkContext.hadoopConfiguration | ||
| val pathFilter = getPathFilter(hadoopConf) | ||
| val partitionSpecsAndLocs = scanPartitions( | ||
| spark, fs, pathFilter, root, Map(), table.partitionColumnNames.map(_.toLowerCase)) | ||
| val parts = partitionSpecsAndLocs.map { case (spec, location) => | ||
| // inherit table storage format (possibly except for location) | ||
| CatalogTablePartition(spec, table.storage.copy(locationUri = Some(location.toUri.toString))) | ||
| spark, fs, pathFilter, root, Map(), table.partitionColumnNames.map(_.toLowerCase), threshold) | ||
| val total = partitionSpecsAndLocs.length | ||
| logInfo(s"Found $total partitions in $root") | ||
|
|
||
| val partitionStats = if (spark.sqlContext.conf.gatherFastStats) { | ||
| gatherPartitionStats(spark, partitionSpecsAndLocs, fs, pathFilter, threshold) | ||
| } else { | ||
| GenMap.empty[String, PartitionStatistics] | ||
| } | ||
| spark.sessionState.catalog.createPartitions(tableName, | ||
| parts.toArray[CatalogTablePartition], ignoreIfExists = true) | ||
| logInfo(s"Finished to gather the fast stats for all $total partitions.") | ||
|
|
||
| addPartitions(spark, table, partitionSpecsAndLocs, partitionStats) | ||
| logInfo(s"Recovered all partitions ($total).") | ||
| Seq.empty[Row] | ||
| } | ||
|
|
||
|
|
@@ -487,15 +520,16 @@ case class AlterTableRecoverPartitionsCommand( | |
| filter: PathFilter, | ||
| path: Path, | ||
| spec: TablePartitionSpec, | ||
| partitionNames: Seq[String]): GenSeq[(TablePartitionSpec, Path)] = { | ||
| if (partitionNames.length == 0) { | ||
| partitionNames: Seq[String], | ||
| threshold: Int): GenSeq[(TablePartitionSpec, Path)] = { | ||
| if (partitionNames.isEmpty) { | ||
| return Seq(spec -> path) | ||
| } | ||
|
|
||
| val statuses = fs.listStatus(path) | ||
| val threshold = spark.conf.get("spark.rdd.parallelListingThreshold", "10").toInt | ||
| val statuses = fs.listStatus(path, filter) | ||
| val statusPar: GenSeq[FileStatus] = | ||
| if (partitionNames.length > 1 && statuses.length > threshold || partitionNames.length > 2) { | ||
| // parallelize the list of partitions here, then we can have better parallelism later. | ||
| val parArray = statuses.par | ||
| parArray.tasksupport = evalTaskSupport | ||
| parArray | ||
|
|
@@ -510,21 +544,89 @@ case class AlterTableRecoverPartitionsCommand( | |
| // TODO: Validate the value | ||
| val value = PartitioningUtils.unescapePathName(ps(1)) | ||
| // comparing with case-insensitive, but preserve the case | ||
| if (columnName == partitionNames(0)) { | ||
| scanPartitions( | ||
| spark, fs, filter, st.getPath, spec ++ Map(columnName -> value), partitionNames.drop(1)) | ||
| if (columnName == partitionNames.head) { | ||
| scanPartitions(spark, fs, filter, st.getPath, spec ++ Map(columnName -> value), | ||
| partitionNames.drop(1), threshold) | ||
| } else { | ||
| logWarning(s"expect partition column ${partitionNames(0)}, but got ${ps(0)}, ignore it") | ||
| logWarning(s"expect partition column ${partitionNames.head}, but got ${ps(0)}, ignore it") | ||
| Seq() | ||
| } | ||
| } else { | ||
| if (name != "_SUCCESS" && name != "_temporary" && !name.startsWith(".")) { | ||
| logWarning(s"ignore ${new Path(path, name)}") | ||
| } | ||
| logWarning(s"ignore ${new Path(path, name)}") | ||
| Seq() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private def gatherPartitionStats( | ||
| spark: SparkSession, | ||
| partitionSpecsAndLocs: GenSeq[(TablePartitionSpec, Path)], | ||
| fs: FileSystem, | ||
| pathFilter: PathFilter, | ||
| threshold: Int): GenMap[String, PartitionStatistics] = { | ||
| if (partitionSpecsAndLocs.length > threshold) { | ||
| val hadoopConf = spark.sparkContext.hadoopConfiguration | ||
| val serializableConfiguration = new SerializableConfiguration(hadoopConf) | ||
| val serializedPaths = partitionSpecsAndLocs.map(_._2.toString).toArray | ||
|
|
||
| // Set the number of parallelism to prevent following file listing from generating many tasks | ||
| // in case of large #defaultParallelism. | ||
| val numParallelism = Math.min(serializedPaths.length, | ||
| Math.min(spark.sparkContext.defaultParallelism, 10000)) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It'd be nice to add a comment about why we picked 10000 here. If there is no good reason, we can make it configurable too.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Copied from HadoopFsRelation |
||
| // gather the fast stats for all the partitions otherwise Hive metastore will list all the | ||
| // files for all the new partitions in sequential way, which is super slow. | ||
| logInfo(s"Gather the fast stats in parallel using $numParallelism tasks.") | ||
| spark.sparkContext.parallelize(serializedPaths, numParallelism) | ||
| .mapPartitions { paths => | ||
| val pathFilter = getPathFilter(serializableConfiguration.value) | ||
| paths.map(new Path(_)).map{ path => | ||
| val fs = path.getFileSystem(serializableConfiguration.value) | ||
| val statuses = fs.listStatus(path, pathFilter) | ||
| (path.toString, PartitionStatistics(statuses.length, statuses.map(_.getLen).sum)) | ||
| } | ||
| }.collectAsMap() | ||
| } else { | ||
| partitionSpecsAndLocs.map { case (_, location) => | ||
| val statuses = fs.listStatus(location, pathFilter) | ||
| (location.toString, PartitionStatistics(statuses.length, statuses.map(_.getLen).sum)) | ||
| }.toMap | ||
| } | ||
| } | ||
|
|
||
| private def addPartitions( | ||
| spark: SparkSession, | ||
| table: CatalogTable, | ||
| partitionSpecsAndLocs: GenSeq[(TablePartitionSpec, Path)], | ||
| partitionStats: GenMap[String, PartitionStatistics]): Unit = { | ||
| val total = partitionSpecsAndLocs.length | ||
| var done = 0L | ||
| // Hive metastore may not have enough memory to handle millions of partitions in single RPC, | ||
| // we should split them into smaller batches. Since Hive client is not thread safe, we cannot | ||
| // do this in parallel. | ||
| val batchSize = 100 | ||
| partitionSpecsAndLocs.toIterator.grouped(batchSize).foreach { batch => | ||
| val now = System.currentTimeMillis() / 1000 | ||
| val parts = batch.map { case (spec, location) => | ||
| val params = partitionStats.get(location.toString).map { | ||
| case PartitionStatistics(numFiles, totalSize) => | ||
| // This two fast stat could prevent Hive metastore to list the files again. | ||
| Map(NUM_FILES -> numFiles.toString, | ||
| TOTAL_SIZE -> totalSize.toString, | ||
| // Workaround a bug in HiveMetastore that try to mutate a read-only parameters. | ||
| // see metastore/src/java/org/apache/hadoop/hive/metastore/HiveMetaStore.java | ||
| DDL_TIME -> now.toString) | ||
| }.getOrElse(Map.empty) | ||
| // inherit table storage format (possibly except for location) | ||
| CatalogTablePartition( | ||
| spec, | ||
| table.storage.copy(locationUri = Some(location.toUri.toString)), | ||
| params) | ||
| } | ||
| spark.sessionState.catalog.createPartitions(tableName, parts, ignoreIfExists = true) | ||
| done += parts.length | ||
| logDebug(s"Recovered ${parts.length} partitions ($done/$total so far)") | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's add some more explanation about the hive metastore bug that requires this parameter.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There are comments on this below