talatuyarer commented on code in PR #12808: URL: https://github.com/apache/iceberg/pull/12808#discussion_r2081046612
########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java: ########## @@ -0,0 +1,385 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.ServiceOptions; +import com.google.cloud.bigquery.BigQueryOptions; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.base.Strings; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.apache.iceberg.util.LocationUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Iceberg Bigquery Metastore Catalog implementation. */ +public class BigQueryMetastoreCatalog extends BaseMetastoreCatalog + implements SupportsNamespaces, Configurable { + + // User provided properties. + public static final String PROJECT_ID = "gcp.bigquery.project-id"; + public static final String GCP_LOCATION = "gcp.bigquery.location"; + public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables"; + + private static final Logger LOG = LoggerFactory.getLogger(BigQueryMetastoreCatalog.class); + + private static final String DEFAULT_GCP_LOCATION = "us"; + + private String catalogName; + private Map<String, String> catalogProperties; + private FileIO fileIO; + private Configuration conf; + private String projectId; + private String projectLocation; + private BigQueryMetastoreClient client; + private boolean listAllTables; + private String warehouseLocation; + + public BigQueryMetastoreCatalog() {} + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument( + properties.containsKey(PROJECT_ID), + "Invalid GCP project: %s must be specified", + PROJECT_ID); Review Comment: You can find my comment under your other comment. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreClientImpl.java: ########## @@ -0,0 +1,579 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetastoreClientImpl implements BigQueryMetastoreClient { + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + // Retry on connection failures due to transient network issues. + .retryOn(java.net.ConnectException.class) + // Retry to recover from temporary DNS resolution failures. + .retryOn(java.net.UnknownHostException.class) + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetastoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); Review Comment: Thank you @ebyhr Good catch! If it is not very important for you. I would like to address that support after merging this. I already received so much comments on this PR. I want to merge this first. This PR will cover most of use cases and also provide main basic functionality for GCP users. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java: ########## @@ -0,0 +1,366 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.ServiceOptions; +import com.google.cloud.bigquery.BigQueryOptions; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.base.Strings; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.apache.iceberg.util.LocationUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Iceberg Bigquery Metastore Catalog implementation. */ +public class BigQueryMetastoreCatalog extends BaseMetastoreCatalog + implements SupportsNamespaces, Configurable { + + // User provided properties. + public static final String PROJECT_ID = "gcp.bigquery.project-id"; + public static final String GCP_LOCATION = "gcp.bigquery.location"; + public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables"; + + private static final Logger LOG = LoggerFactory.getLogger(BigQueryMetastoreCatalog.class); + + private static final String DEFAULT_GCP_LOCATION = "us"; + + private String catalogName; + private Map<String, String> catalogProperties; + private FileIO fileIO; + private Configuration conf; + private String projectId; + private String projectLocation; + private BigQueryMetastoreClient client; + private boolean listAllTables; + private String warehouseLocation; + + public BigQueryMetastoreCatalog() {} + + @Override + public void initialize(String name, Map<String, String> properties) { + Preconditions.checkArgument( + properties.containsKey(PROJECT_ID), + "Invalid GCP project: %s must be specified", + PROJECT_ID); + + this.projectId = properties.get(PROJECT_ID); + this.projectLocation = properties.getOrDefault(GCP_LOCATION, DEFAULT_GCP_LOCATION); + + BigQueryOptions options = + BigQueryOptions.newBuilder() + .setProjectId(projectId) + .setLocation(projectLocation) + .setRetrySettings(ServiceOptions.getDefaultRetrySettings()) + .build(); + + try { + client = new BigQueryMetastoreClientImpl(options); + } catch (IOException e) { + throw new UncheckedIOException("Creating BigQuery client failed", e); + } catch (GeneralSecurityException e) { + throw new RuntimeException("Creating BigQuery client failed due to a security issue", e); + } + + initialize(name, properties, projectId, projectLocation, client); + } + + @VisibleForTesting + void initialize( + String name, + Map<String, String> properties, + String initialProjectId, + String initialLocation, + BigQueryMetastoreClient bigQueryMetaStoreClient) { + Preconditions.checkArgument(bigQueryMetaStoreClient != null, "Invalid BigQuery client: null"); + this.catalogName = name; + this.catalogProperties = ImmutableMap.copyOf(properties); + this.projectId = initialProjectId; + this.projectLocation = initialLocation; + this.client = bigQueryMetaStoreClient; + + if (this.conf == null) { + LOG.warn("No configuration was set, using the default environment Configuration"); + this.conf = new Configuration(); + } + + LOG.info("Using BigQuery Metastore Iceberg Catalog: {}", name); + + if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) { + this.warehouseLocation = + LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION)); + } + + this.fileIO = + CatalogUtil.loadFileIO( + properties.getOrDefault( + CatalogProperties.FILE_IO_IMPL, "org.apache.iceberg.io.ResolvingFileIO"), + properties, + conf); + + this.listAllTables = Boolean.parseBoolean(properties.getOrDefault(LIST_ALL_TABLES, "true")); + } + + @Override + protected TableOperations newTableOps(TableIdentifier identifier) { + return new BigQueryTableOperations(client, fileIO, toTableReference(identifier), conf); + } + + @Override + protected String defaultWarehouseLocation(TableIdentifier identifier) { + String locationUri = null; + DatasetReference datasetReference = toDatasetReference(identifier.namespace()); + Dataset dataset = client.load(datasetReference); + if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) { + locationUri = dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri(); + } + + return String.format( + "%s/%s", + Strings.isNullOrEmpty(locationUri) + ? createDefaultStorageLocationUri(datasetReference.getDatasetId()) + : LocationUtil.stripTrailingSlash(locationUri), + identifier.name()); + } + + @Override + public List<TableIdentifier> listTables(Namespace namespace) { + validateNamespace(namespace); + + return client.list(toDatasetReference(namespace), listAllTables).stream() + .map( + table -> TableIdentifier.of(namespace.level(0), table.getTableReference().getTableId())) + .collect(ImmutableList.toImmutableList()); + } + + @Override + public boolean dropTable(TableIdentifier identifier, boolean purge) { + try { + TableOperations ops = newTableOps(identifier); + TableMetadata lastMetadata = ops.current(); + + client.delete(toTableReference(identifier)); + + if (purge && lastMetadata != null) { + CatalogUtil.dropTableData(ops.io(), lastMetadata); + } + } catch (NoSuchTableException e) { + return false; + } + + return true; + } + + @Override + public void renameTable(TableIdentifier from, TableIdentifier to) { + // TODO: Enable once supported by BigQuery API. + throw new UnsupportedOperationException("Table rename operation is unsupported."); + } + + @Override + public void createNamespace(Namespace namespace, Map<String, String> metadata) { + Dataset builder = new Dataset(); + DatasetReference datasetReference = toDatasetReference(namespace); + builder.setLocation(this.projectLocation); + builder.setDatasetReference(datasetReference); + builder.setExternalCatalogDatasetOptions( + BigQueryMetastoreUtils.createExternalCatalogDatasetOptions( + createDefaultStorageLocationUri(datasetReference.getDatasetId()), metadata)); + + client.create(builder); + } + + @Override + public List<Namespace> listNamespaces() { + try { + return listNamespaces(Namespace.empty()); + } catch (NoSuchNamespaceException e) { + return ImmutableList.of(); + } + } + + /** + * Since this catalog only supports one-level namespaces, it always returns an empty list unless + * passed an empty namespace to list all namespaces within the catalog. + */ + @Override + public List<Namespace> listNamespaces(Namespace namespace) { + List<Datasets> allDatasets = client.list(projectId); + + ImmutableList<Namespace> namespaces = + allDatasets.stream().map(this::toNamespace).collect(ImmutableList.toImmutableList()); + if (namespaces.isEmpty()) { + throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace); + } + + return namespaces; + } + + @Override + public boolean dropNamespace(Namespace namespace) { + try { + client.delete(toDatasetReference(namespace)); Review Comment: I agree but I am testing against BigQueryProduction using real client too. Otherwise there is no point to have this code in Iceberg Repo :) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org