|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""BigQuery DataFrame clients to interact with other cloud resources""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import logging |
| 20 | +import time |
| 21 | +from typing import Optional |
| 22 | + |
| 23 | +import google.api_core.exceptions |
| 24 | +from google.cloud import bigquery_connection_v1, resourcemanager_v3 |
| 25 | +from google.iam.v1 import iam_policy_pb2, policy_pb2 |
| 26 | + |
| 27 | +logging.basicConfig( |
| 28 | + level=logging.INFO, format="[%(levelname)s][%(asctime)s][%(name)s] %(message)s" |
| 29 | +) |
| 30 | +logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | + |
| 33 | +class BqConnectionManager: |
| 34 | + """Manager to handle operations with BQ connections.""" |
| 35 | + |
| 36 | + # Wait time (in seconds) for an IAM binding to take effect after creation |
| 37 | + _IAM_WAIT_SECONDS = 120 |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + bq_connection_client: bigquery_connection_v1.ConnectionServiceClient, |
| 42 | + cloud_resource_manager_client: resourcemanager_v3.ProjectsClient, |
| 43 | + ): |
| 44 | + self._bq_connection_client = bq_connection_client |
| 45 | + self._cloud_resource_manager_client = cloud_resource_manager_client |
| 46 | + |
| 47 | + def create_bq_connection( |
| 48 | + self, project_id: str, location: str, connection_id: str, iam_role: str |
| 49 | + ): |
| 50 | + """Create the BQ connection if not exist. In addition, try to add the IAM role to the connection to ensure required permissions. |
| 51 | +
|
| 52 | + Args: |
| 53 | + project_id: |
| 54 | + ID of the project. |
| 55 | + location: |
| 56 | + Location of the connection. |
| 57 | + connection_id: |
| 58 | + ID of the connection. |
| 59 | + iam_role: |
| 60 | + str of the IAM role that the service account of the created connection needs to aquire. E.g. 'run.invoker', 'aiplatform.user' |
| 61 | + """ |
| 62 | + # TODO(shobs): The below command to enable BigQuery Connection API needs |
| 63 | + # to be automated. Disabling for now since most target users would not |
| 64 | + # have the privilege to enable API in a project. |
| 65 | + # log("Making sure BigQuery Connection API is enabled") |
| 66 | + # if os.system("gcloud services enable bigqueryconnection.googleapis.com"): |
| 67 | + # raise ValueError("Failed to enable BigQuery Connection API") |
| 68 | + # If the intended connection does not exist then create it |
| 69 | + service_account_id = self._get_service_account_if_connection_exists( |
| 70 | + project_id, location, connection_id |
| 71 | + ) |
| 72 | + if service_account_id: |
| 73 | + logger.info( |
| 74 | + f"Connector {project_id}.{location}.{connection_id} already exists" |
| 75 | + ) |
| 76 | + else: |
| 77 | + connection_name, service_account_id = self._create_bq_connection( |
| 78 | + project_id, location, connection_id |
| 79 | + ) |
| 80 | + logger.info( |
| 81 | + f"Created BQ connection {connection_name} with service account id: {service_account_id}" |
| 82 | + ) |
| 83 | + # Ensure IAM role on the BQ connection |
| 84 | + # https://cloud.google.com/bigquery/docs/reference/standard-sql/remote-functions#grant_permission_on_function |
| 85 | + self._ensure_iam_binding(project_id, service_account_id, iam_role) |
| 86 | + |
| 87 | + # Introduce retries to accommodate transient errors like etag mismatch, |
| 88 | + # which can be caused by concurrent operation on the same resource, and |
| 89 | + # manifests with message like: |
| 90 | + # google.api_core.exceptions.Aborted: 409 There were concurrent policy |
| 91 | + # changes. Please retry the whole read-modify-write with exponential |
| 92 | + # backoff. The request's ETag '\007\006\003,\264\304\337\272' did not match |
| 93 | + # the current policy's ETag '\007\006\003,\3750&\363'. |
| 94 | + @google.api_core.retry.Retry( |
| 95 | + predicate=google.api_core.retry.if_exception_type( |
| 96 | + google.api_core.exceptions.Aborted |
| 97 | + ), |
| 98 | + initial=10, |
| 99 | + maximum=20, |
| 100 | + multiplier=2, |
| 101 | + timeout=60, |
| 102 | + ) |
| 103 | + def _ensure_iam_binding( |
| 104 | + self, project_id: str, service_account_id: str, iam_role: str |
| 105 | + ): |
| 106 | + """Ensure necessary IAM role is configured on a service account.""" |
| 107 | + project = f"projects/{project_id}" |
| 108 | + service_account = f"serviceAccount:{service_account_id}" |
| 109 | + role = f"roles/{iam_role}" |
| 110 | + request = iam_policy_pb2.GetIamPolicyRequest(resource=project) |
| 111 | + policy = self._cloud_resource_manager_client.get_iam_policy(request=request) |
| 112 | + |
| 113 | + # Check if the binding already exists, and if does, do nothing more |
| 114 | + for binding in policy.bindings: |
| 115 | + if binding.role == role: |
| 116 | + if service_account in binding.members: |
| 117 | + return |
| 118 | + |
| 119 | + # Create a new binding |
| 120 | + new_binding = policy_pb2.Binding(role=role, members=[service_account]) |
| 121 | + policy.bindings.append(new_binding) |
| 122 | + request = iam_policy_pb2.SetIamPolicyRequest(resource=project, policy=policy) |
| 123 | + self._cloud_resource_manager_client.set_iam_policy(request=request) |
| 124 | + |
| 125 | + # We would wait for the IAM policy change to take effect |
| 126 | + # https://cloud.google.com/iam/docs/access-change-propagation |
| 127 | + logger.info( |
| 128 | + f"Waiting {self._IAM_WAIT_SECONDS} seconds for IAM to take effect.." |
| 129 | + ) |
| 130 | + time.sleep(self._IAM_WAIT_SECONDS) |
| 131 | + |
| 132 | + def _create_bq_connection(self, project_id: str, location: str, connection_id: str): |
| 133 | + """Create the BigQuery Connection and returns corresponding service account id.""" |
| 134 | + client = self._bq_connection_client |
| 135 | + connection = bigquery_connection_v1.Connection( |
| 136 | + cloud_resource=bigquery_connection_v1.CloudResourceProperties() |
| 137 | + ) |
| 138 | + request = bigquery_connection_v1.CreateConnectionRequest( |
| 139 | + parent=client.common_location_path(project_id, location), |
| 140 | + connection_id=connection_id, |
| 141 | + connection=connection, |
| 142 | + ) |
| 143 | + connection = client.create_connection(request) |
| 144 | + return connection.name, connection.cloud_resource.service_account_id |
| 145 | + |
| 146 | + def _get_service_account_if_connection_exists( |
| 147 | + self, project_id: str, location: str, connection_id: str |
| 148 | + ) -> Optional[str]: |
| 149 | + """Check if the BigQuery Connection exists.""" |
| 150 | + client = self._bq_connection_client |
| 151 | + request = bigquery_connection_v1.GetConnectionRequest( |
| 152 | + name=client.connection_path(project_id, location, connection_id) |
| 153 | + ) |
| 154 | + |
| 155 | + service_account = None |
| 156 | + try: |
| 157 | + service_account = client.get_connection( |
| 158 | + request=request |
| 159 | + ).cloud_resource.service_account_id |
| 160 | + except google.api_core.exceptions.NotFound: |
| 161 | + pass |
| 162 | + |
| 163 | + return service_account |
0 commit comments