Repository navigation
Expand file tree
/
Copy pathmonitored_cache.py
More file actions
178 lines (157 loc) · 6.53 KB
/
Copy pathmonitored_cache.py
File metadata and controls
178 lines (157 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# Copyright 2025 Google LLC
#
# Licensed 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.
from __future__ import annotations
import asyncio
from collections.abc import Callable
import logging
import ssl
from typing import Any
import aiohttp
from google.cloud.sql.connector.connection_info import ConnectionInfo
from google.cloud.sql.connector.connection_info import ConnectionInfoCache
from google.cloud.sql.connector.exceptions import CacheClosedError
from google.cloud.sql.connector.exceptions import DnsLoopError
from google.cloud.sql.connector.instance import RefreshAheadCache
from google.cloud.sql.connector.lazy import LazyRefreshCache
from google.cloud.sql.connector.resolver import DefaultResolver
from google.cloud.sql.connector.resolver import DnsResolver
from google.cloud.sql.connector.resolver import is_instance_dns_name
logger = logging.getLogger(name=__name__)
class MonitoredCache(ConnectionInfoCache):
def __init__(
self,
cache: RefreshAheadCache | LazyRefreshCache,
failover_period: int,
resolver: DefaultResolver | DnsResolver,
) -> None:
self.resolver = resolver
self.cache = cache
self.domain_name_ticker: asyncio.Task | None = None
self.sockets: list[ssl.SSLSocket] = []
# If domain name is configured for instance and failover period is set,
# poll for DNS record changes.
is_instance_dns = False
if self.cache.conn_name.domain_name:
is_instance_dns = is_instance_dns_name(
self.cache.conn_name.domain_name or ""
)
if (
self.cache.conn_name.domain_name
and failover_period > 0
and not is_instance_dns
):
self.domain_name_ticker = asyncio.create_task(
ticker(failover_period, self._check_domain_name)
)
logger.debug(
f"['{self.cache.conn_name}']: Configured polling of domain "
f"name with failover period of {failover_period} seconds."
)
@property
def closed(self) -> bool:
return self.cache.closed
def _purge_closed_sockets(self) -> None:
"""Remove closed sockets from monitored cache.
If a socket is closed by the database driver we should remove it from
list of sockets.
"""
open_sockets = []
for socket in self.sockets:
# Check fileno for if socket is closed. Will return
# -1 on failure, which will be used to signal socket closed.
if socket.fileno() != -1:
open_sockets.append(socket)
self.sockets = open_sockets
async def _check_domain_name(self) -> None:
# remove any closed connections from cache
self._purge_closed_sockets()
try:
# Resolve domain name and see if Cloud SQL instance connection name
# has changed. If it has, close all connections.
new_conn_name = await self.resolver.resolve(
self.cache.conn_name.domain_name
)
if new_conn_name != self.cache.conn_name:
logger.debug(
f"['{self.cache.conn_name}']: Cloud SQL instance changed "
f"from {self.cache.conn_name.get_connection_string()} to "
f"{new_conn_name.get_connection_string()}, closing all "
"connections!"
)
await self.close()
except Exception as e: # noqa: BLE001
if self._is_non_transient(e):
logger.debug(
f"['{self.cache.conn_name}']: Domain name check failed with "
f"non-transient error, closing all connections: {e}"
)
await self.close()
else:
# Domain name checks should not be fatal for transient errors, log error and continue.
logger.debug(
f"['{self.cache.conn_name}']: Unable to check domain name, "
f"domain name {self.cache.conn_name.domain_name} did not "
f"resolve (transient error): {e}"
)
def _is_non_transient(self, e: Exception) -> bool:
return (
isinstance(e, (ValueError, DnsLoopError))
or (
isinstance(e, aiohttp.ClientResponseError)
and e.status in (403, 404)
)
)
async def connect_info(self) -> ConnectionInfo:
if self.closed:
raise CacheClosedError(
"Can not get connection info, cache has already been closed."
)
return await self.cache.connect_info()
async def force_refresh(self) -> None:
# if cache is closed do not refresh
if self.closed:
return
return await self.cache.force_refresh()
async def close(self) -> None:
# Cancel domain name ticker task.
if self.domain_name_ticker:
self.domain_name_ticker.cancel()
try:
await self.domain_name_ticker
except asyncio.CancelledError:
logger.debug(
f"['{self.cache.conn_name}']: Cancelled domain name polling task."
)
finally:
self.domain_name_ticker = None
# If cache is already closed, no further work.
if self.closed:
return
# Close underyling ConnectionInfoCache
await self.cache.close()
# Close any still open sockets
for socket in self.sockets:
# Check fileno for if socket is closed. Will return
# -1 on failure, which will be used to signal socket closed.
if socket.fileno() != -1:
socket.close()
async def ticker(interval: int, function: Callable, *args: Any, **kwargs: Any) -> None:
"""
Ticker function to sleep for specified interval and then schedule call
to given function.
"""
while True:
# Sleep for interval and then schedule task
await asyncio.sleep(interval)
asyncio.create_task(function(*args, **kwargs))