|
| 1 | +package ai.chronon.integrations.cloud_gcp |
| 2 | + |
| 3 | +import com.google.cloud.bigquery.{ |
| 4 | + BigQuery, |
| 5 | + BigQueryOptions, |
| 6 | + ExternalTableDefinition, |
| 7 | + StandardTableDefinition, |
| 8 | + TableDefinition, |
| 9 | + TableId |
| 10 | +} |
| 11 | +import com.google.cloud.spark.bigquery.BigQueryCatalog |
| 12 | +import org.apache.iceberg.spark.SparkCatalog |
| 13 | +import org.apache.spark.sql.SparkSession |
| 14 | +import org.apache.spark.sql.connector.catalog._ |
| 15 | +import org.apache.spark.sql.connector.catalog.functions.UnboundFunction |
| 16 | +import org.apache.spark.sql.connector.expressions.Transform |
| 17 | +import org.apache.spark.sql.connector.read.ScanBuilder |
| 18 | +import org.apache.spark.sql.connector.write.{LogicalWriteInfo, WriteBuilder} |
| 19 | +import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat |
| 20 | +import org.apache.spark.sql.execution.datasources.v2.parquet.ParquetTable |
| 21 | +import org.apache.spark.sql.types.StructType |
| 22 | +import org.apache.spark.sql.util.CaseInsensitiveStringMap |
| 23 | + |
| 24 | +import java.util |
| 25 | +import scala.jdk.CollectionConverters._ |
| 26 | +import scala.util.Try |
| 27 | + |
| 28 | +/** A table that delegates all operations to an internal table, but with additional properties. |
| 29 | + * This is mostly for enriching SparkTables with metadata that cannot be accessed by spark directly. |
| 30 | + * For example, we can use a bigquery client to fetch table metadata / properties and then hydrate the Spark table |
| 31 | + * with that information, before we pass it back to the Spark compute engine. |
| 32 | + * |
| 33 | + * Down the line, we could also support custom partition management. |
| 34 | + */ |
| 35 | +class DelegatingTable(internalTable: Table, |
| 36 | + additionalProperties: Map[String, String], |
| 37 | + partitioning: Option[Array[Transform]] = None) |
| 38 | + extends Table |
| 39 | + with SupportsRead |
| 40 | + with SupportsWrite { |
| 41 | + |
| 42 | + override def name(): String = internalTable.name |
| 43 | + |
| 44 | + override def schema(): StructType = internalTable.schema |
| 45 | + |
| 46 | + override def capabilities(): util.Set[TableCapability] = internalTable.capabilities() |
| 47 | + |
| 48 | + override def newScanBuilder(options: CaseInsensitiveStringMap): ScanBuilder = |
| 49 | + internalTable.asInstanceOf[SupportsRead].newScanBuilder(options) |
| 50 | + |
| 51 | + override def newWriteBuilder(info: LogicalWriteInfo): WriteBuilder = |
| 52 | + internalTable.asInstanceOf[SupportsWrite].newWriteBuilder(info) |
| 53 | + |
| 54 | + override def properties(): util.Map[String, String] = |
| 55 | + (internalTable.properties().asScala ++ additionalProperties).asJava |
| 56 | + |
| 57 | + override def partitioning(): Array[Transform] = partitioning.getOrElse(internalTable.partitioning()) |
| 58 | + |
| 59 | +} |
| 60 | + |
| 61 | +object DelegatingTable { |
| 62 | + def apply(table: Table, additionalProperties: Map[String, String] = Map.empty): Table = |
| 63 | + new DelegatingTable(table, additionalProperties = additionalProperties) |
| 64 | +} |
| 65 | + |
| 66 | +/** Galactus catalog that allows us to interact with BigQuery metastore as a spark catalog. This allows for |
| 67 | + * querying of a variety of table types directly in spark sql or the dataframe api. |
| 68 | + * This is analogous to iceberg's [[org.apache.iceberg.spark.SparkSessionCatalog]] in that it will |
| 69 | + * apply a fallback when querying for tables. It will always attempt to load a table reference |
| 70 | + * as an iceberg table first and falling back to bigquery. |
| 71 | + * |
| 72 | + * To interact with iceberg, we use Google's https://cloud.google.com/blog/products/data-analytics/introducing-bigquery-metastore-fully-managed-metadata-service |
| 73 | + * metastore catalog library. By default, all catalog operations will delegate to this library, and this abstraction |
| 74 | + * is meant to remain incredibly thin. BE CAREFUL WHEN OVERRIDING THIS BEHAVIOR. You shouldn't be needing too much additional |
| 75 | + * functionality. Before you do this, consider upgrading the `iceberg_bigquery_catalog_lib` dependency and/or iceberg first. |
| 76 | + * |
| 77 | + * NOTE that this abstraction currently only supports querying tables that all belong to the same GCP project. Multi-project |
| 78 | + * support will depend on underlying libraries to support them. |
| 79 | + */ |
| 80 | +class DelegatingBigQueryMetastoreCatalog extends CatalogExtension { |
| 81 | + |
| 82 | + @transient private lazy val bqOptions = BigQueryOptions.getDefaultInstance |
| 83 | + @transient private lazy val bigQueryClient: BigQuery = bqOptions.getService |
| 84 | + |
| 85 | + @transient private lazy val icebergCatalog: SparkCatalog = new SparkCatalog() |
| 86 | + @transient private lazy val connectorCatalog: BigQueryCatalog = new BigQueryCatalog() |
| 87 | + |
| 88 | + // Some stupid spark settings. |
| 89 | + private var defaultSessionCatalog: CatalogPlugin = null |
| 90 | + private var catalogName: String = |
| 91 | + null // This corresponds to `spark_catalog in `spark.sql.catalog.spark_catalog`. This is necessary for spark to correctly choose which implementation to use. |
| 92 | + |
| 93 | + override def listNamespaces: Array[Array[String]] = icebergCatalog.listNamespaces() |
| 94 | + |
| 95 | + override def listNamespaces(namespace: Array[String]): Array[Array[String]] = icebergCatalog.listNamespaces(namespace) |
| 96 | + |
| 97 | + override def loadNamespaceMetadata(namespace: Array[String]): util.Map[String, String] = |
| 98 | + icebergCatalog.loadNamespaceMetadata(namespace) |
| 99 | + |
| 100 | + override def createNamespace(namespace: Array[String], metadata: util.Map[String, String]): Unit = { |
| 101 | + icebergCatalog.createNamespace(namespace, metadata) |
| 102 | + } |
| 103 | + |
| 104 | + override def purgeTable(ident: Identifier): Boolean = { |
| 105 | + icebergCatalog.purgeTable(ident) |
| 106 | + } |
| 107 | + |
| 108 | + override def alterNamespace(namespace: Array[String], changes: NamespaceChange*): Unit = { |
| 109 | + icebergCatalog.alterNamespace(namespace, changes: _*) |
| 110 | + } |
| 111 | + |
| 112 | + override def dropNamespace(namespace: Array[String], cascade: Boolean): Boolean = |
| 113 | + icebergCatalog.dropNamespace(namespace, cascade) |
| 114 | + |
| 115 | + override def listTables(namespace: Array[String]): Array[Identifier] = icebergCatalog.listTables(namespace) |
| 116 | + |
| 117 | + override def loadTable(rawIdent: Identifier): Table = { |
| 118 | + val ident = Identifier.of(rawIdent.namespace.flatMap(_.split("\\.")), rawIdent.name) |
| 119 | + Try { icebergCatalog.loadTable(ident) } |
| 120 | + .recover { |
| 121 | + case _ => { |
| 122 | + val tId = ident.namespace().toList match { |
| 123 | + case database :: Nil => TableId.of(database, ident.name()) |
| 124 | + case project :: database :: Nil => TableId.of(project, database, ident.name()) |
| 125 | + case Nil => |
| 126 | + throw new IllegalArgumentException(s"Table identifier namespace ${rawIdent} must have at least one part.") |
| 127 | + } |
| 128 | + val table = bigQueryClient.getTable(tId) |
| 129 | + table.getDefinition.asInstanceOf[TableDefinition] match { |
| 130 | + case externalTable: ExternalTableDefinition => { |
| 131 | + val uris = externalTable.getSourceUris.asScala |
| 132 | + val uri = scala |
| 133 | + .Option(externalTable.getHivePartitioningOptions) |
| 134 | + .map(_.getSourceUriPrefix) |
| 135 | + .getOrElse { |
| 136 | + require(uris.size == 1, s"External table ${table} can be backed by only one URI.") |
| 137 | + uris.head.replaceAll("/\\*\\.parquet$", "") |
| 138 | + } |
| 139 | + |
| 140 | + val fileBasedTable = ParquetTable(tId.toString, |
| 141 | + SparkSession.active, |
| 142 | + CaseInsensitiveStringMap.empty(), |
| 143 | + List(uri), |
| 144 | + None, |
| 145 | + classOf[ParquetFileFormat]) |
| 146 | + DelegatingTable(fileBasedTable, |
| 147 | + Map(TableCatalog.PROP_EXTERNAL -> "true", TableCatalog.PROP_LOCATION -> uri)) |
| 148 | + } |
| 149 | + case _: StandardTableDefinition => { |
| 150 | + //todo(tchow): Support partitioning |
| 151 | + |
| 152 | + // Hack because there's a bug in the BigQueryCatalog where they ignore the projectId. |
| 153 | + // See: https://github.com/GoogleCloudDataproc/spark-bigquery-connector/pull/1340 |
| 154 | + val connectorTable = connectorCatalog.loadTable(Identifier.of(Array(tId.getDataset), tId.getTable)) |
| 155 | + // ideally it should be the below: |
| 156 | + // val connectorTable = connectorCatalog.loadTable(ident) |
| 157 | + DelegatingTable(connectorTable, Map(TableCatalog.PROP_EXTERNAL -> "false")) |
| 158 | + } |
| 159 | + case _ => throw new IllegalStateException(s"Cannot support table of type: ${table.getFriendlyName}") |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | + .getOrElse(defaultSessionCatalog.asInstanceOf[TableCatalog].loadTable(rawIdent)) |
| 164 | + } |
| 165 | + |
| 166 | + override def createTable(ident: Identifier, |
| 167 | + schema: StructType, |
| 168 | + partitions: Array[Transform], |
| 169 | + properties: util.Map[String, String]): Table = { |
| 170 | + icebergCatalog.createTable(ident, schema, partitions, properties) |
| 171 | + } |
| 172 | + |
| 173 | + override def alterTable(ident: Identifier, changes: TableChange*): Table = { |
| 174 | + icebergCatalog.alterTable(ident, changes: _*) |
| 175 | + } |
| 176 | + |
| 177 | + override def dropTable(ident: Identifier): Boolean = icebergCatalog.dropTable(ident) |
| 178 | + |
| 179 | + override def renameTable(oldIdent: Identifier, newIdent: Identifier): Unit = { |
| 180 | + icebergCatalog.renameTable(oldIdent, newIdent) |
| 181 | + } |
| 182 | + |
| 183 | + override def initialize(name: String, options: CaseInsensitiveStringMap): Unit = { |
| 184 | + icebergCatalog.initialize(name, options) |
| 185 | + connectorCatalog.initialize(name, options) |
| 186 | + catalogName = name |
| 187 | + } |
| 188 | + |
| 189 | + override def name(): String = catalogName |
| 190 | + |
| 191 | + override def setDelegateCatalog(delegate: CatalogPlugin): Unit = { |
| 192 | + defaultSessionCatalog = delegate |
| 193 | + } |
| 194 | + |
| 195 | + override def listFunctions(namespace: Array[String]): Array[Identifier] = icebergCatalog.listFunctions(namespace) |
| 196 | + |
| 197 | + override def loadFunction(ident: Identifier): UnboundFunction = icebergCatalog.loadFunction(ident) |
| 198 | + |
| 199 | +} |
0 commit comments