-
Notifications
You must be signed in to change notification settings - Fork 83
feat: reset connection when the DNS record changes #1241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
3b01b0d
chore: add failover_period to Connector
jackwotherspoon d783d63
feat: automatically reset connection on failover
jackwotherspoon 555a957
chore: Merge branch 'main' into dns-reset-connection
jackwotherspoon 4f2fc4c
chore: add integration test with domain name
jackwotherspoon f92fd88
chore: update type hint
jackwotherspoon 7a1812a
chore: attempt moving socket into ConnectionInfo
jackwotherspoon 6f6d5e4
chore: revert connection_info.py
jackwotherspoon e8702a2
chore: move socket initialization to Connector level
jackwotherspoon 0a1ca17
chore: merge main
jackwotherspoon ff9d6c9
chore: change secret back
jackwotherspoon 24a6230
chore: lint
jackwotherspoon ac5fca0
chore: update unit tests
jackwotherspoon a101003
chore: add additional tests
jackwotherspoon d260934
chore: improve tests
jackwotherspoon c6b74e8
chore: update header
jackwotherspoon 9c4d4d1
chore: update typo
jackwotherspoon ce2c30a
chore: review comments
jackwotherspoon 0998f8d
chore: update based on feedback
jackwotherspoon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # 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. | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from typing import Any, Callable, Optional, Union | ||
|
|
||
| from google.cloud.sql.connector.connection_info import ConnectionInfo | ||
| from google.cloud.sql.connector.connection_info import ConnectionInfoCache | ||
| 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 | ||
|
|
||
| logger = logging.getLogger(name=__name__) | ||
|
|
||
|
|
||
| class MonitoredCache(ConnectionInfoCache): | ||
| def __init__( | ||
| self, | ||
| cache: Union[RefreshAheadCache, LazyRefreshCache], | ||
| failover_period: int, | ||
| resolver: Union[DefaultResolver, DnsResolver], | ||
| ) -> None: | ||
| self.resolver = resolver | ||
| self.cache = cache | ||
| self.domain_name_ticker: Optional[asyncio.Task] = None | ||
| self.open_conns_count: int = 0 | ||
|
|
||
| if self.cache.conn_name.domain_name: | ||
| 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 | ||
|
|
||
| async def _check_domain_name(self) -> None: | ||
| 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: | ||
| # Domain name checks should not be fatal, 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: {e}" | ||
| ) | ||
|
|
||
| async def connect_info(self) -> ConnectionInfo: | ||
| return await self.cache.connect_info() | ||
|
|
||
| async def force_refresh(self) -> None: | ||
| 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." | ||
| ) | ||
|
|
||
| # If cache is already closed, no further work. | ||
| if self.cache.closed: | ||
| return | ||
| await self.cache.close() | ||
jackwotherspoon marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| 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)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This allows for a reliable way to get the instance connection name for a Cloud SQL instance whether the connector is connecting via domain name or instance connection name.