|
| 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 asyncio |
| 16 | +import logging |
| 17 | +from typing import Any, Callable, Optional, Union |
| 18 | + |
| 19 | +from google.cloud.sql.connector.connection_info import ConnectionInfo |
| 20 | +from google.cloud.sql.connector.connection_info import ConnectionInfoCache |
| 21 | +from google.cloud.sql.connector.instance import RefreshAheadCache |
| 22 | +from google.cloud.sql.connector.lazy import LazyRefreshCache |
| 23 | +from google.cloud.sql.connector.resolver import DefaultResolver |
| 24 | +from google.cloud.sql.connector.resolver import DnsResolver |
| 25 | + |
| 26 | +logger = logging.getLogger(name=__name__) |
| 27 | + |
| 28 | + |
| 29 | +class MonitoredCache(ConnectionInfoCache): |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + cache: Union[RefreshAheadCache, LazyRefreshCache], |
| 33 | + failover_period: int, |
| 34 | + resolver: Union[DefaultResolver, DnsResolver], |
| 35 | + ) -> None: |
| 36 | + self.resolver = resolver |
| 37 | + self.cache = cache |
| 38 | + self.domain_name_ticker: Optional[asyncio.Task] = None |
| 39 | + self.open_conns_count: int = 0 |
| 40 | + |
| 41 | + if self.cache.conn_name.domain_name: |
| 42 | + self.domain_name_ticker = asyncio.create_task( |
| 43 | + ticker(failover_period, self._check_domain_name) |
| 44 | + ) |
| 45 | + logger.debug( |
| 46 | + f"['{self.cache.conn_name}']: Configured polling of domain " |
| 47 | + f"name with failover period of {failover_period} seconds." |
| 48 | + ) |
| 49 | + |
| 50 | + @property |
| 51 | + def closed(self) -> bool: |
| 52 | + return self.cache.closed |
| 53 | + |
| 54 | + async def _check_domain_name(self) -> None: |
| 55 | + try: |
| 56 | + # Resolve domain name and see if Cloud SQL instance connection name |
| 57 | + # has changed. If it has, close all connections. |
| 58 | + new_conn_name = await self.resolver.resolve( |
| 59 | + self.cache.conn_name.domain_name |
| 60 | + ) |
| 61 | + if new_conn_name != self.cache.conn_name: |
| 62 | + logger.debug( |
| 63 | + f"['{self.cache.conn_name}']: Cloud SQL instance changed " |
| 64 | + f"from {self.cache.conn_name.get_connection_string()} to " |
| 65 | + f"{new_conn_name.get_connection_string()}, closing all " |
| 66 | + "connections!" |
| 67 | + ) |
| 68 | + await self.close() |
| 69 | + |
| 70 | + except Exception as e: |
| 71 | + # Domain name checks should not be fatal, log error and continue. |
| 72 | + logger.debug( |
| 73 | + f"['{self.cache.conn_name}']: Unable to check domain name, " |
| 74 | + f"domain name {self.cache.conn_name.domain_name} did not " |
| 75 | + f"resolve: {e}" |
| 76 | + ) |
| 77 | + |
| 78 | + async def connect_info(self) -> ConnectionInfo: |
| 79 | + return await self.cache.connect_info() |
| 80 | + |
| 81 | + async def force_refresh(self) -> None: |
| 82 | + return await self.cache.force_refresh() |
| 83 | + |
| 84 | + async def close(self) -> None: |
| 85 | + # Cancel domain name ticker task. |
| 86 | + if self.domain_name_ticker: |
| 87 | + self.domain_name_ticker.cancel() |
| 88 | + try: |
| 89 | + await self.domain_name_ticker |
| 90 | + except asyncio.CancelledError: |
| 91 | + logger.debug( |
| 92 | + f"['{self.cache.conn_name}']: Cancelled domain name polling task." |
| 93 | + ) |
| 94 | + |
| 95 | + # If cache is already closed, no further work. |
| 96 | + if self.cache.closed: |
| 97 | + return |
| 98 | + await self.cache.close() |
| 99 | + |
| 100 | + |
| 101 | +async def ticker(interval: int, function: Callable, *args: Any, **kwargs: Any) -> None: |
| 102 | + """ |
| 103 | + Ticker function to sleep for specified interval and then schedule call |
| 104 | + to given function. |
| 105 | + """ |
| 106 | + while True: |
| 107 | + # Sleep for interval and then schedule task |
| 108 | + await asyncio.sleep(interval) |
| 109 | + asyncio.create_task(function(*args, **kwargs)) |
0 commit comments