|
| 1 | +# Copyright 2025 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 | +import datetime |
| 16 | +import logging |
| 17 | +import threading |
| 18 | +from typing import Callable, Optional, Sequence |
| 19 | +import uuid |
| 20 | + |
| 21 | +# TODO: Non-ibis implementation |
| 22 | +import bigframes_vendored.ibis.backends.bigquery.datatypes as ibis_bq |
| 23 | +import google.cloud.bigquery as bigquery |
| 24 | + |
| 25 | +from bigframes.core.compile import googlesql |
| 26 | + |
| 27 | +KEEPALIVE_QUERY_TIMEOUT_SECONDS = 5.0 |
| 28 | + |
| 29 | +KEEPALIVE_FREQUENCY = datetime.timedelta(hours=6) |
| 30 | + |
| 31 | + |
| 32 | +logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | + |
| 35 | +class SessionResourceManager: |
| 36 | + """ |
| 37 | + Responsible for allocating and cleaning up temporary gbq tables used by a BigFrames session. |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__( |
| 41 | + self, bqclient: bigquery.Client, location: str, *, kms_key: Optional[str] = None |
| 42 | + ): |
| 43 | + self.bqclient = bqclient |
| 44 | + self.location = location |
| 45 | + self._kms_key = kms_key |
| 46 | + self._session_id: Optional[str] = None |
| 47 | + self._sessiondaemon: Optional[RecurringTaskDaemon] = None |
| 48 | + self._session_lock = threading.RLock() |
| 49 | + |
| 50 | + def create_temp_table( |
| 51 | + self, schema: Sequence[bigquery.SchemaField], cluster_cols: Sequence[str] = [] |
| 52 | + ) -> bigquery.TableReference: |
| 53 | + """Create a temporary session table. Session is an exclusive resource, so throughput is limited""" |
| 54 | + # Can't set a table in _SESSION as destination via query job API, so we |
| 55 | + # run DDL, instead. |
| 56 | + with self._session_lock: |
| 57 | + table_ref = bigquery.TableReference( |
| 58 | + bigquery.DatasetReference(self.bqclient.project, "_SESSION"), |
| 59 | + uuid.uuid4().hex, |
| 60 | + ) |
| 61 | + job_config = bigquery.QueryJobConfig( |
| 62 | + connection_properties=[ |
| 63 | + bigquery.ConnectionProperty("session_id", self._get_session_id()) |
| 64 | + ] |
| 65 | + ) |
| 66 | + if self._kms_key: |
| 67 | + job_config.destination_encryption_configuration = ( |
| 68 | + bigquery.EncryptionConfiguration(kms_key_name=self._kms_key) |
| 69 | + ) |
| 70 | + |
| 71 | + ibis_schema = ibis_bq.BigQuerySchema.to_ibis(list(schema)) |
| 72 | + |
| 73 | + fields = [ |
| 74 | + f"{googlesql.identifier(name)} {ibis_bq.BigQueryType.from_ibis(ibis_type)}" |
| 75 | + for name, ibis_type in ibis_schema.fields.items() |
| 76 | + ] |
| 77 | + fields_string = ",".join(fields) |
| 78 | + |
| 79 | + cluster_string = "" |
| 80 | + if cluster_cols: |
| 81 | + cluster_cols_sql = ", ".join( |
| 82 | + f"{googlesql.identifier(cluster_col)}" |
| 83 | + for cluster_col in cluster_cols |
| 84 | + ) |
| 85 | + cluster_string = f"\nCLUSTER BY {cluster_cols_sql}" |
| 86 | + |
| 87 | + ddl = f"CREATE TEMP TABLE `_SESSION`.{googlesql.identifier(table_ref.table_id)} ({fields_string}){cluster_string}" |
| 88 | + |
| 89 | + job = self.bqclient.query(ddl, job_config=job_config) |
| 90 | + |
| 91 | + job.result() |
| 92 | + # return the fully qualified table, so it can be used outside of the session |
| 93 | + return job.destination |
| 94 | + |
| 95 | + def close(self): |
| 96 | + if self._sessiondaemon is not None: |
| 97 | + self._sessiondaemon.stop() |
| 98 | + |
| 99 | + if self._session_id is not None and self.bqclient is not None: |
| 100 | + self.bqclient.query_and_wait(f"CALL BQ.ABORT_SESSION('{self._session_id}')") |
| 101 | + |
| 102 | + def _get_session_id(self) -> str: |
| 103 | + if self._session_id: |
| 104 | + return self._session_id |
| 105 | + with self._session_lock: |
| 106 | + if self._session_id is None: |
| 107 | + job_config = bigquery.QueryJobConfig(create_session=True) |
| 108 | + # Make sure the session is a new one, not one associated with another query. |
| 109 | + job_config.use_query_cache = False |
| 110 | + query_job = self.bqclient.query( |
| 111 | + "SELECT 1", job_config=job_config, location=self.location |
| 112 | + ) |
| 113 | + query_job.result() # blocks until finished |
| 114 | + assert query_job.session_info is not None |
| 115 | + assert query_job.session_info.session_id is not None |
| 116 | + self._session_id = query_job.session_info.session_id |
| 117 | + self._sessiondaemon = RecurringTaskDaemon( |
| 118 | + task=self._keep_session_alive, frequency=KEEPALIVE_FREQUENCY |
| 119 | + ) |
| 120 | + self._sessiondaemon.start() |
| 121 | + return query_job.session_info.session_id |
| 122 | + else: |
| 123 | + return self._session_id |
| 124 | + |
| 125 | + def _keep_session_alive(self): |
| 126 | + # bq sessions will default expire after 24 hours of disuse, but if queried, this is renewed to a maximum of 7 days |
| 127 | + with self._session_lock: |
| 128 | + job_config = bigquery.QueryJobConfig( |
| 129 | + connection_properties=[ |
| 130 | + bigquery.ConnectionProperty("session_id", self._get_session_id()) |
| 131 | + ] |
| 132 | + ) |
| 133 | + try: |
| 134 | + self.bqclient.query_and_wait( |
| 135 | + "SELECT 1", |
| 136 | + location=self.location, |
| 137 | + job_config=job_config, |
| 138 | + wait_timeout=KEEPALIVE_QUERY_TIMEOUT_SECONDS, |
| 139 | + ) |
| 140 | + except Exception as e: |
| 141 | + logging.warning("BigQuery session keep-alive query errored : %s", e) |
| 142 | + |
| 143 | + |
| 144 | +class RecurringTaskDaemon: |
| 145 | + def __init__(self, task: Callable[[], None], frequency: datetime.timedelta): |
| 146 | + self._stop_event = threading.Event() |
| 147 | + self._frequency = frequency |
| 148 | + self._thread = threading.Thread(target=self._run_loop, daemon=True) |
| 149 | + self._task = task |
| 150 | + |
| 151 | + def start(self): |
| 152 | + """Start the daemon. Cannot be restarted once stopped.""" |
| 153 | + if self._stop_event.is_set(): |
| 154 | + raise RuntimeError("Cannot restart daemon thread.") |
| 155 | + self._thread.start() |
| 156 | + |
| 157 | + def _run_loop(self): |
| 158 | + while True: |
| 159 | + self._stop_event.wait(self._frequency.total_seconds()) |
| 160 | + if self._stop_event.is_set(): |
| 161 | + return |
| 162 | + try: |
| 163 | + self._task() |
| 164 | + except Exception as e: |
| 165 | + logging.warning("RecurringTaskDaemon task errorred: %s", e) |
| 166 | + |
| 167 | + def stop(self, timeout_seconds: Optional[float] = None): |
| 168 | + """Stop and cleanup the daemon.""" |
| 169 | + if self._thread.is_alive(): |
| 170 | + self._stop_event.set() |
| 171 | + self._thread.join(timeout=timeout_seconds) |
0 commit comments