-
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 12 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| """" | ||
| """ | ||
| Copyright 2019 Google LLC | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
|
|
||
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 |
|---|---|---|
|
|
@@ -20,9 +20,10 @@ | |
| from functools import partial | ||
| import logging | ||
| import os | ||
| import socket | ||
| from threading import Thread | ||
| from types import TracebackType | ||
| from typing import Any, Optional, Union | ||
| from typing import Any, Callable, Optional, Union | ||
|
|
||
| import google.auth | ||
| from google.auth.credentials import Credentials | ||
|
|
@@ -35,6 +36,7 @@ | |
| from google.cloud.sql.connector.enums import RefreshStrategy | ||
| from google.cloud.sql.connector.instance import RefreshAheadCache | ||
| from google.cloud.sql.connector.lazy import LazyRefreshCache | ||
| from google.cloud.sql.connector.monitored_cache import MonitoredCache | ||
| import google.cloud.sql.connector.pg8000 as pg8000 | ||
| import google.cloud.sql.connector.pymysql as pymysql | ||
| import google.cloud.sql.connector.pytds as pytds | ||
|
|
@@ -46,6 +48,7 @@ | |
| logger = logging.getLogger(name=__name__) | ||
|
|
||
| ASYNC_DRIVERS = ["asyncpg"] | ||
| SERVER_PROXY_PORT = 3307 | ||
| _DEFAULT_SCHEME = "https://" | ||
| _DEFAULT_UNIVERSE_DOMAIN = "googleapis.com" | ||
| _SQLADMIN_HOST_TEMPLATE = "sqladmin.{universe_domain}" | ||
|
|
@@ -67,6 +70,7 @@ def __init__( | |
| universe_domain: Optional[str] = None, | ||
| refresh_strategy: str | RefreshStrategy = RefreshStrategy.BACKGROUND, | ||
| resolver: type[DefaultResolver] | type[DnsResolver] = DefaultResolver, | ||
| failover_period: int = 30, | ||
| ) -> None: | ||
| """Initializes a Connector instance. | ||
|
|
||
|
|
@@ -114,6 +118,11 @@ def __init__( | |
| name. To resolve a DNS record to an instance connection name, use | ||
| DnsResolver. | ||
| Default: DefaultResolver | ||
|
|
||
| failover_period (int): The time interval in seconds between each | ||
| attempt to check if a failover has occured for a given instance. | ||
| Must be used with `resolver=DnsResolver` to have any effect. | ||
| Default: 30 | ||
| """ | ||
| # if refresh_strategy is str, convert to RefreshStrategy enum | ||
| if isinstance(refresh_strategy, str): | ||
|
|
@@ -143,9 +152,7 @@ def __init__( | |
| ) | ||
| # initialize dict to store caches, key is a tuple consisting of instance | ||
| # connection name string and enable_iam_auth boolean flag | ||
| self._cache: dict[ | ||
| tuple[str, bool], Union[RefreshAheadCache, LazyRefreshCache] | ||
| ] = {} | ||
| self._cache: dict[tuple[str, bool], MonitoredCache] = {} | ||
| self._client: Optional[CloudSQLClient] = None | ||
|
|
||
| # initialize credentials | ||
|
|
@@ -167,6 +174,7 @@ def __init__( | |
| self._enable_iam_auth = enable_iam_auth | ||
| self._user_agent = user_agent | ||
| self._resolver = resolver() | ||
| self._failover_period = failover_period | ||
| # if ip_type is str, convert to IPTypes enum | ||
| if isinstance(ip_type, str): | ||
| ip_type = IPTypes._from_str(ip_type) | ||
|
|
@@ -285,15 +293,16 @@ async def connect_async( | |
| driver=driver, | ||
| ) | ||
| enable_iam_auth = kwargs.pop("enable_iam_auth", self._enable_iam_auth) | ||
| if (instance_connection_string, enable_iam_auth) in self._cache: | ||
| cache = self._cache[(instance_connection_string, enable_iam_auth)] | ||
|
|
||
| conn_name = await self._resolver.resolve(instance_connection_string) | ||
| if (str(conn_name), enable_iam_auth) in self._cache: | ||
jackwotherspoon marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| monitored_cache = self._cache[(str(conn_name), enable_iam_auth)] | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Update cache key to be
|
||
| else: | ||
| conn_name = await self._resolver.resolve(instance_connection_string) | ||
| if self._refresh_strategy == RefreshStrategy.LAZY: | ||
| logger.debug( | ||
| f"['{conn_name}']: Refresh strategy is set to lazy refresh" | ||
| ) | ||
| cache = LazyRefreshCache( | ||
| cache: Union[LazyRefreshCache, RefreshAheadCache] = LazyRefreshCache( | ||
| conn_name, | ||
| self._client, | ||
| self._keys, | ||
|
|
@@ -309,8 +318,14 @@ async def connect_async( | |
| self._keys, | ||
| enable_iam_auth, | ||
| ) | ||
| # wrap cache as a MonitoredCache | ||
| monitored_cache = MonitoredCache( | ||
| cache, | ||
| self._failover_period, | ||
| self._resolver, | ||
| ) | ||
| logger.debug(f"['{conn_name}']: Connection info added to cache") | ||
| self._cache[(instance_connection_string, enable_iam_auth)] = cache | ||
| self._cache[(str(conn_name), enable_iam_auth)] = monitored_cache | ||
|
|
||
| connect_func = { | ||
| "pymysql": pymysql.connect, | ||
|
|
@@ -321,7 +336,7 @@ async def connect_async( | |
|
|
||
| # only accept supported database drivers | ||
| try: | ||
| connector = connect_func[driver] | ||
| connector: Callable = connect_func[driver] # type: ignore | ||
| except KeyError: | ||
| raise KeyError(f"Driver '{driver}' is not supported.") | ||
|
|
||
|
|
@@ -339,14 +354,14 @@ async def connect_async( | |
|
|
||
| # attempt to get connection info for Cloud SQL instance | ||
| try: | ||
| conn_info = await cache.connect_info() | ||
| conn_info = await monitored_cache.connect_info() | ||
| # validate driver matches intended database engine | ||
| DriverMapping.validate_engine(driver, conn_info.database_version) | ||
| ip_address = conn_info.get_preferred_ip(ip_type) | ||
| except Exception: | ||
| # with an error from Cloud SQL Admin API call or IP type, invalidate | ||
| # the cache and re-raise the error | ||
| await self._remove_cached(instance_connection_string, enable_iam_auth) | ||
| await self._remove_cached(str(conn_name), enable_iam_auth) | ||
| raise | ||
| logger.debug(f"['{conn_info.conn_name}']: Connecting to {ip_address}:3307") | ||
| # format `user` param for automatic IAM database authn | ||
|
|
@@ -367,18 +382,28 @@ async def connect_async( | |
| await conn_info.create_ssl_context(enable_iam_auth), | ||
| **kwargs, | ||
| ) | ||
| # synchronous drivers are blocking and run using executor | ||
| # Create socket with SSLContext for sync drivers | ||
| ctx = await conn_info.create_ssl_context(enable_iam_auth) | ||
| sock = ctx.wrap_socket( | ||
| socket.create_connection((ip_address, SERVER_PROXY_PORT)), | ||
| server_hostname=ip_address, | ||
| ) | ||
| # If this connection was opened using a domain name, then store it | ||
| # for later in case we need to forcibly close it on failover. | ||
| if conn_info.conn_name.domain_name: | ||
| monitored_cache.sockets.append(sock) | ||
| # Synchronous drivers are blocking and run using executor | ||
| connect_partial = partial( | ||
| connector, | ||
| ip_address, | ||
| await conn_info.create_ssl_context(enable_iam_auth), | ||
| sock, | ||
| **kwargs, | ||
| ) | ||
| return await self._loop.run_in_executor(None, connect_partial) | ||
|
|
||
| except Exception: | ||
| # with any exception, we attempt a force refresh, then throw the error | ||
| await cache.force_refresh() | ||
| await monitored_cache.force_refresh() | ||
| raise | ||
|
|
||
| async def _remove_cached( | ||
|
|
@@ -456,6 +481,7 @@ async def create_async_connector( | |
| universe_domain: Optional[str] = None, | ||
| refresh_strategy: str | RefreshStrategy = RefreshStrategy.BACKGROUND, | ||
| resolver: type[DefaultResolver] | type[DnsResolver] = DefaultResolver, | ||
| failover_period: int = 30, | ||
| ) -> Connector: | ||
| """Helper function to create Connector object for asyncio connections. | ||
|
|
||
|
|
@@ -507,6 +533,11 @@ async def create_async_connector( | |
| DnsResolver. | ||
| Default: DefaultResolver | ||
|
|
||
| failover_period (int): The time interval in seconds between each | ||
| attempt to check if a failover has occured for a given instance. | ||
| Must be used with `resolver=DnsResolver` to have any effect. | ||
| Default: 30 | ||
|
|
||
| Returns: | ||
| A Connector instance configured with running event loop. | ||
| """ | ||
|
|
@@ -525,4 +556,5 @@ async def create_async_connector( | |
| universe_domain=universe_domain, | ||
| refresh_strategy=refresh_strategy, | ||
| resolver=resolver, | ||
| failover_period=failover_period, | ||
| ) | ||
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
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.