|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.sql.pipelines.graph |
| 19 | + |
| 20 | +import scala.jdk.CollectionConverters._ |
| 21 | +import scala.util.control.{NonFatal, NoStackTrace} |
| 22 | + |
| 23 | +import org.apache.spark.SparkException |
| 24 | +import org.apache.spark.internal.Logging |
| 25 | +import org.apache.spark.sql.catalyst.TableIdentifier |
| 26 | +import org.apache.spark.sql.connector.catalog.{ |
| 27 | + CatalogV2Util, |
| 28 | + Identifier, |
| 29 | + TableCatalog, |
| 30 | + TableChange, |
| 31 | + TableInfo |
| 32 | +} |
| 33 | +import org.apache.spark.sql.connector.expressions.Expressions |
| 34 | +import org.apache.spark.sql.pipelines.graph.QueryOrigin.ExceptionHelpers |
| 35 | +import org.apache.spark.sql.pipelines.util.SchemaInferenceUtils.diffSchemas |
| 36 | +import org.apache.spark.sql.pipelines.util.SchemaMergingUtils |
| 37 | + |
| 38 | +/** |
| 39 | + * [[DatasetManager]] is responsible for materializing tables in the catalog based on the given |
| 40 | + * graph. For each table in the graph, it will create a table if none exists (or if this is a |
| 41 | + * full refresh), or merge the schema of an existing table to match the new flows writing to it. |
| 42 | + */ |
| 43 | +object DatasetManager extends Logging { |
| 44 | + |
| 45 | + /** |
| 46 | + * Wraps table materialization exceptions. |
| 47 | + * |
| 48 | + * The target use case of this exception is merely as a means to capture attribution - |
| 49 | + * 1. Indicate that the exception is associated with table materialization. |
| 50 | + * 2. Indicate which table materialization failed for. |
| 51 | + * |
| 52 | + * @param tableName The name of the table that failed to materialize. |
| 53 | + * @param cause The underlying exception that caused the materialization to fail. |
| 54 | + */ |
| 55 | + case class TableMaterializationException( |
| 56 | + tableName: String, |
| 57 | + cause: Throwable |
| 58 | + ) extends Exception(cause) |
| 59 | + with NoStackTrace |
| 60 | + |
| 61 | + /** |
| 62 | + * Materializes the tables in the given graph. This method will create or update the tables |
| 63 | + * in the catalog based on the given graph and context. |
| 64 | + * |
| 65 | + * @param virtualizedConnectedGraphWithTables The connected graph. |
| 66 | + * @param context The context for the pipeline update. |
| 67 | + * @return The graph with materialized tables. |
| 68 | + */ |
| 69 | + def materializeDatasets( |
| 70 | + virtualizedConnectedGraphWithTables: DataflowGraph, |
| 71 | + context: PipelineUpdateContext): DataflowGraph = { |
| 72 | + val (_, refreshTableIdentsSet, fullRefreshTableIdentsSet) = { |
| 73 | + DatasetManager.constructFullRefreshSet(virtualizedConnectedGraphWithTables.tables, context) |
| 74 | + } |
| 75 | + |
| 76 | + /** Return all the tables that need to be materialized from the given graph. */ |
| 77 | + def tablesToMatz(graph: DataflowGraph): Seq[TableRefreshType] = { |
| 78 | + graph.tables |
| 79 | + .filter(t => fullRefreshTableIdentsSet.contains(t.identifier)) |
| 80 | + .map(table => TableRefreshType(table, isFullRefresh = true)) ++ |
| 81 | + graph.tables |
| 82 | + .filter(t => refreshTableIdentsSet.contains(t.identifier)) |
| 83 | + .map(table => TableRefreshType(table, isFullRefresh = false)) |
| 84 | + } |
| 85 | + |
| 86 | + val tablesToMaterialize = |
| 87 | + tablesToMatz(virtualizedConnectedGraphWithTables).map(t => t.table.identifier -> t).toMap |
| 88 | + |
| 89 | + // normalized graph where backing tables for all dataset have been created and datasets |
| 90 | + // are all marked as normalized. |
| 91 | + val virtualizedMaterializedConnectedGraphWithTables: DataflowGraph = try { |
| 92 | + DataflowGraphTransformer |
| 93 | + .withDataflowGraphTransformer(virtualizedConnectedGraphWithTables) { transformer => |
| 94 | + transformer.transformTables { table => |
| 95 | + if (tablesToMaterialize.keySet.contains(table.identifier)) { |
| 96 | + try { |
| 97 | + materializeTable( |
| 98 | + virtualizedConnectedGraphWithTables, |
| 99 | + table, |
| 100 | + tablesToMaterialize(table.identifier).isFullRefresh, |
| 101 | + context |
| 102 | + ) |
| 103 | + } catch { |
| 104 | + case NonFatal(e) => |
| 105 | + throw TableMaterializationException( |
| 106 | + table.displayName, |
| 107 | + cause = e.addOrigin(table.origin) |
| 108 | + ) |
| 109 | + } |
| 110 | + } else { |
| 111 | + table |
| 112 | + } |
| 113 | + } |
| 114 | + // TODO: Publish persisted views to the metastore. |
| 115 | + } |
| 116 | + .getDataflowGraph |
| 117 | + } catch { |
| 118 | + case e: SparkException if e.getCause != null => throw e.getCause |
| 119 | + } |
| 120 | + |
| 121 | + virtualizedMaterializedConnectedGraphWithTables |
| 122 | + } |
| 123 | + |
| 124 | + /** |
| 125 | + * Materializes a table in the catalog. This method will create or update the table in the |
| 126 | + * catalog based on the given table and context. |
| 127 | + * @param virtualizedConnectedGraphWithTables The connected graph. Used to infer the table schema. |
| 128 | + * @param table The table to be materialized. |
| 129 | + * @param isFullRefresh Whether this table should be full refreshed or not. |
| 130 | + * @param context The context for the pipeline update. |
| 131 | + * @return The materialized table (with additional metadata set). |
| 132 | + */ |
| 133 | + private def materializeTable( |
| 134 | + virtualizedConnectedGraphWithTables: DataflowGraph, |
| 135 | + table: Table, |
| 136 | + isFullRefresh: Boolean, |
| 137 | + context: PipelineUpdateContext |
| 138 | + ): Table = { |
| 139 | + logInfo(s"Materializing metadata for table ${table.identifier}.") |
| 140 | + val catalogManager = context.spark.sessionState.catalogManager |
| 141 | + val catalog = (table.identifier.catalog match { |
| 142 | + case Some(catalogName) => |
| 143 | + catalogManager.catalog(catalogName) |
| 144 | + case None => |
| 145 | + catalogManager.currentCatalog |
| 146 | + }).asInstanceOf[TableCatalog] |
| 147 | + |
| 148 | + val identifier = |
| 149 | + Identifier.of(Array(table.identifier.database.get), table.identifier.identifier) |
| 150 | + val outputSchema = table.specifiedSchema.getOrElse( |
| 151 | + virtualizedConnectedGraphWithTables.inferredSchema(table.identifier).asNullable |
| 152 | + ) |
| 153 | + val mergedProperties = resolveTableProperties(table, identifier) |
| 154 | + |
| 155 | + val exists = catalog.tableExists(identifier) |
| 156 | + |
| 157 | + // Wipe the data if we need to |
| 158 | + if ((isFullRefresh || !table.isStreamingTableOpt.get) && exists) { |
| 159 | + context.spark.sql(s"TRUNCATE TABLE ${table.identifier.quotedString}") |
| 160 | + } |
| 161 | + |
| 162 | + // Alter the table if we need to |
| 163 | + if (exists) { |
| 164 | + val existingSchema = catalog.loadTable(identifier).schema() |
| 165 | + |
| 166 | + val targetSchema = if (table.isStreamingTableOpt.get && !isFullRefresh) { |
| 167 | + SchemaMergingUtils.mergeSchemas(existingSchema, outputSchema) |
| 168 | + } else { |
| 169 | + outputSchema |
| 170 | + } |
| 171 | + |
| 172 | + val columnChanges = diffSchemas(existingSchema, targetSchema) |
| 173 | + val setProperties = mergedProperties.map { case (k, v) => TableChange.setProperty(k, v) } |
| 174 | + catalog.alterTable(identifier, (columnChanges ++ setProperties).toArray: _*) |
| 175 | + } |
| 176 | + |
| 177 | + // Create the table if we need to |
| 178 | + if (!exists) { |
| 179 | + catalog.createTable( |
| 180 | + identifier, |
| 181 | + new TableInfo.Builder() |
| 182 | + .withProperties(mergedProperties.asJava) |
| 183 | + .withColumns(CatalogV2Util.structTypeToV2Columns(outputSchema)) |
| 184 | + .withPartitions(table.partitionCols.toSeq.flatten.map(Expressions.identity).toArray) |
| 185 | + .build() |
| 186 | + ) |
| 187 | + } |
| 188 | + |
| 189 | + table.copy( |
| 190 | + normalizedPath = |
| 191 | + Option(catalog.loadTable(identifier).properties().get(TableCatalog.PROP_LOCATION)) |
| 192 | + ) |
| 193 | + } |
| 194 | + |
| 195 | + /** |
| 196 | + * Some fields on the [[Table]] object are represented as reserved table properties by the catalog |
| 197 | + * APIs. This method creates a table properties map that merges the user-provided table properties |
| 198 | + * with these reserved properties. |
| 199 | + */ |
| 200 | + private def resolveTableProperties(table: Table, identifier: Identifier): Map[String, String] = { |
| 201 | + val validatedAndCanonicalizedProps = |
| 202 | + PipelinesTableProperties.validateAndCanonicalize( |
| 203 | + table.properties, |
| 204 | + warnFunction = s => logWarning(s) |
| 205 | + ) |
| 206 | + |
| 207 | + val specialProps = Seq( |
| 208 | + (table.comment, "comment", TableCatalog.PROP_COMMENT), |
| 209 | + (table.format, "format", TableCatalog.PROP_PROVIDER) |
| 210 | + ).map { |
| 211 | + case (value, name, reservedPropKey) => |
| 212 | + validatedAndCanonicalizedProps.get(reservedPropKey).foreach { pc => |
| 213 | + if (value.isDefined && value.get != pc) { |
| 214 | + throw new IllegalArgumentException( |
| 215 | + s"For dataset $identifier, $name '${value.get}' does not match value '$pc' for " + |
| 216 | + s"reserved table property '$reservedPropKey''" |
| 217 | + ) |
| 218 | + } |
| 219 | + } |
| 220 | + reservedPropKey -> value |
| 221 | + } |
| 222 | + .collect { case (key, Some(value)) => key -> value } |
| 223 | + |
| 224 | + validatedAndCanonicalizedProps ++ specialProps |
| 225 | + } |
| 226 | + |
| 227 | + /** |
| 228 | + * A case class that represents the type of refresh for a table. |
| 229 | + * @param table The table to be refreshed. |
| 230 | + * @param isFullRefresh Whether this table should be fully refreshed or not. |
| 231 | + */ |
| 232 | + private case class TableRefreshType(table: Table, isFullRefresh: Boolean) |
| 233 | + |
| 234 | + /** |
| 235 | + * Constructs the set of tables that should be fully refreshed and the set of tables that |
| 236 | + * should be refreshed. |
| 237 | + */ |
| 238 | + private def constructFullRefreshSet( |
| 239 | + graphTables: Seq[Table], |
| 240 | + context: PipelineUpdateContext |
| 241 | + ): (Seq[Table], Seq[TableIdentifier], Seq[TableIdentifier]) = { |
| 242 | + val (fullRefreshTablesSet, refreshTablesSet) = { |
| 243 | + val specifiedFullRefreshTables = context.fullRefreshTables.filter(graphTables) |
| 244 | + val specifiedRefreshTables = context.refreshTables.filter(graphTables) |
| 245 | + |
| 246 | + val (fullRefreshAllowed, fullRefreshNotAllowed) = specifiedFullRefreshTables.partition { t => |
| 247 | + PipelinesTableProperties.resetAllowed.fromMap(t.properties) |
| 248 | + } |
| 249 | + |
| 250 | + val refreshTables = (specifiedRefreshTables ++ fullRefreshNotAllowed).filterNot { t => |
| 251 | + fullRefreshAllowed.contains(t) |
| 252 | + } |
| 253 | + |
| 254 | + if (fullRefreshNotAllowed.nonEmpty) { |
| 255 | + logInfo( |
| 256 | + s"Skipping full refresh on some flows because " + |
| 257 | + s"${PipelinesTableProperties.resetAllowed.key} was set to false. Flows: " + |
| 258 | + s"$fullRefreshNotAllowed" |
| 259 | + ) |
| 260 | + } |
| 261 | + |
| 262 | + (fullRefreshAllowed, refreshTables) |
| 263 | + } |
| 264 | + val allRefreshTables = fullRefreshTablesSet ++ refreshTablesSet |
| 265 | + val refreshTableIdentsSet = refreshTablesSet.map(_.identifier) |
| 266 | + val fullRefreshTableIdentsSet = fullRefreshTablesSet.map(_.identifier) |
| 267 | + (allRefreshTables, refreshTableIdentsSet, fullRefreshTableIdentsSet) |
| 268 | + } |
| 269 | +} |
0 commit comments