Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions aws_advanced_python_wrapper/aio/failover_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ class AsyncFailoverPlugin(AsyncPlugin):
DbApiMethod.INIT_HOST_PROVIDER.method_name,
DbApiMethod.CONNECT.method_name,
DbApiMethod.FORCE_CONNECT.method_name,
DbApiMethod.CONNECTION_CURSOR.method_name,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this required?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, its also there in the sync version of failover. Without it, the async version misses the connection closed in the cursor() which fails to failover

DbApiMethod.CURSOR_EXECUTE.method_name,
DbApiMethod.CURSOR_EXECUTEMANY.method_name,
DbApiMethod.CURSOR_FETCHONE.method_name,
Expand All @@ -80,7 +81,7 @@ def __init__(
host_list_provider: AsyncHostListProvider,
props: Properties) -> None:
self._plugin_service = plugin_service
self._host_list_provider = host_list_provider
self._factory_host_list_provider = host_list_provider
self._props = props
# Shared writer-failover convergence helper (also reused by the GDB
# failover subclass). See AsyncRetryUtil.get_writer_connection.
Expand Down Expand Up @@ -132,6 +133,15 @@ def _determine_mode(props: Properties) -> FailoverMode:
mode = get_failover_mode(props)
return mode if mode is not None else FailoverMode.STRICT_WRITER

@property
def _host_list_provider(self) -> AsyncHostListProvider:
# The service replaces its provider once the dialect is confirmed
# (_update_host_list_provider), so read it at call time. Sync reads
# the topology through the plugin service too.
# The factory's provider only serves a service that has none.
current = self._plugin_service.host_list_provider
return current if current is not None else self._factory_host_list_provider

@property
def subscribed_methods(self) -> Set[str]:
return set(self._SUBSCRIBED)
Expand Down Expand Up @@ -555,8 +565,6 @@ async def _failover_reader_impl(
new_conn = await self._within_deadline(
self._open_connection(candidate, driver_dialect), deadline)
except Exception as e: # noqa: BLE001
self._plugin_service.set_availability(
candidate, HostAvailability.UNAVAILABLE)
last_error = e
if candidate in remaining:
remaining.remove(candidate)
Expand Down Expand Up @@ -607,8 +615,6 @@ async def _failover_reader_impl(
new_conn = await self._within_deadline(
self._open_connection(original_writer, driver_dialect), deadline)
except Exception as e: # noqa: BLE001
self._plugin_service.set_availability(
original_writer, HostAvailability.UNAVAILABLE)
last_error = e
else:
role = await self._probe_role(new_conn)
Expand Down
14 changes: 9 additions & 5 deletions aws_advanced_python_wrapper/aio/plugin_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -798,12 +798,16 @@ async def _update_host_list_provider(self, connection: Any) -> None:
type(previous).__name__)
return

if previous is not None:
# Carry the panic-mode probe across.
# Carry the panic-mode probe across, or arm it when the previous
# provider has none (a static one, built from the guessed dialect).
set_probe = getattr(replacement, "set_probe_host", None)
if callable(set_probe):
probe_host = getattr(previous, "_probe_host", None)
set_probe = getattr(replacement, "set_probe_host", None)
if probe_host is not None and callable(set_probe):
set_probe(probe_host)
if probe_host is None:
from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \
build_probe_host
probe_host = build_probe_host(self, self._props)
set_probe(probe_host)

self._host_list_provider = replacement
logger.debug(
Expand Down
11 changes: 10 additions & 1 deletion aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def __init__(
host_list_provider: AsyncHostListProvider,
props: Properties) -> None:
self._plugin_service = plugin_service
self._host_list_provider = host_list_provider
self._factory_host_list_provider = host_list_provider
self._props = props
self._writer_conn: Optional[Any] = None
self._writer_host_info: Optional[HostInfo] = None
Expand All @@ -101,6 +101,15 @@ def __init__(
self._switch_to_writer_counter = tf.create_counter(
"rws.switches.to_writer.count")

@property
def _host_list_provider(self) -> AsyncHostListProvider:
# The service replaces its provider once the dialect is confirmed
# (_update_host_list_provider), so read it at call time. Sync reads
# the topology through the plugin service too.
# The factory's provider only serves a service that has none.
current = self._plugin_service.host_list_provider
return current if current is not None else self._factory_host_list_provider

@property
def subscribed_methods(self) -> Set[str]:
return set(self._SUBSCRIBED)
Expand Down
3 changes: 2 additions & 1 deletion aws_advanced_python_wrapper/aio/stale_dns_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,8 @@ def notify_host_list_changed(
or changes.get(key_host_port)
or changes.get(self._writer_host_info.host))
if (writer_changes is not None
and HostEvent.CONVERTED_TO_READER in writer_changes):
and (HostEvent.CONVERTED_TO_READER in writer_changes
or HostEvent.HOST_DELETED in writer_changes)):
logger.debug("StaleDnsHelper.Reset")
self._writer_host_info = None
self._writer_host_address = None
Expand Down
2 changes: 1 addition & 1 deletion aws_advanced_python_wrapper/stale_dns_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]) -> None:
return

writer_changes = changes.get(self._writer_host_info.url, None)
if writer_changes is not None and HostEvent.CONVERTED_TO_READER in writer_changes:
if writer_changes is not None and (HostEvent.CONVERTED_TO_READER in writer_changes or HostEvent.HOST_DELETED in writer_changes):
logger.debug("StaleDnsHelper.Reset")
self._writer_host_info = None
self._writer_host_address = None
Expand Down
2 changes: 2 additions & 0 deletions aws_advanced_python_wrapper/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,8 @@ def __init__(
self._plugin_service: PluginService = plugin_service
self._plugin_manager: PluginManager = plugin_manager
self._target_cursor: Cursor = target_cursor
# The driver cursor may hold only a weak reference to its connection (mysql-connector), so keep that connection alive.
self._target_connection: Optional[Connection] = plugin_service.driver_dialect.unwrap_connection(plugin_service.current_connection)

# It's not part of PEP249
@property
Expand Down
18 changes: 17 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ types-boto3 = "^1.42.95"
coverage = "^7.13.5"
debugpy = "^1.8.20"
pydevd-pycharm = "^263.7031.30"
pytest = ">=7.4.4,<10.0.0"
pytest = ">=8.2,!=8.2.2,<10.0.0"
pytest-mock = "^3.15.1"
pytest-html = "^4.2.0"
pytest-html-merger = ">=0.1.0,<0.1.1"
Expand All @@ -85,6 +85,7 @@ opentelemetry-exporter-otlp-proto-grpc = "^1.43.0"
opentelemetry-sdk-extension-aws = "^2.1.0"
pytest-timeout = "^2.4.0"
pytest-repeat = "^0.9.4"
pytest-rerunfailures = "^16.7"
greenlet = ">=3"

[tool.isort]
Expand Down
123 changes: 122 additions & 1 deletion tests/integration/container/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

from aws_xray_sdk.core import xray_recorder

from aws_advanced_python_wrapper.aio.plugin_service import \
AsyncPluginServiceImpl
from aws_advanced_python_wrapper.connection_provider import \
ConnectionProviderManager
from aws_advanced_python_wrapper.custom_endpoint_plugin import \
Expand All @@ -39,20 +41,34 @@
import socket
import timeit
from time import sleep
from typing import List
from typing import ClassVar, List

import boto3
import pytest
import pytest_timeout # type: ignore[import-untyped]
from botocore.config import Config
from pytest_html import extras as html_extras # type: ignore[import-untyped]

from .utils.connection_utils import ConnectionUtils
from .utils.database_engine_deployment import DatabaseEngineDeployment
from .utils.proxy_helper import ProxyHelper
from .utils.rds_test_utility import RdsTestUtility
from .utils.test_environment import TestEnvironment
from .utils.test_environment_features import TestEnvironmentFeatures
from .utils.test_timings import (CLUSTER_OUTAGE_RERUN_DELAY_SEC,
RDS_EVENTS_BUDGET_SEC,
RDS_EVENTS_CALL_TIMEOUT_SEC,
RDS_EVENTS_LOOKBACK_SEC)

logger = Logger(__name__)

_CLUSTER_DEPLOYMENTS = (DatabaseEngineDeployment.AURORA, DatabaseEngineDeployment.RDS_MULTI_AZ_CLUSTER)
# During a long outage every test fails, so cap the reruns for the whole session
_MAX_CLUSTER_OUTAGE_RERUNS = 5
_NO_RERUN_MODULE_PREFIXES = (
"test_autoscaling", "test_blue_green_deployment", "test_failover_performance",
"test_read_write_splitting_performance")


@pytest.fixture(scope="session", autouse=True)
def _prewarm_aws_pipeline():
Expand Down Expand Up @@ -101,6 +117,13 @@ def pytest_runtest_setup(item):

logger.info("Starting test preparation for: " + test_name)

_Attempt.failed_other_than_outage = False
ProxyHelper.connectivity_disabled = False
RdsTestUtility.failover_requested = False
# pytest-timeout cancels its timer when an attempt fails, so a rerun needs a new one
if getattr(item, "execution_count", 1) > 1:
_set_timeout_timer(item)

segment: Optional[Segment] = None
if TestEnvironmentFeatures.TELEMETRY_TRACES_ENABLED in TestEnvironment.get_current().get_features():
segment = xray_recorder.begin_segment("test: setup")
Expand Down Expand Up @@ -169,6 +192,7 @@ def pytest_runtest_setup(item):
RdsUtils.clear_cache()
services_container.release_resources()
PluginServiceImpl._host_availability_expiring_cache.clear()
AsyncPluginServiceImpl._host_availability_expiring_cache.clear()
DatabaseDialectManager._known_endpoint_dialects.clear()
CustomEndpointMonitor._custom_endpoint_info_cache.clear()

Expand Down Expand Up @@ -232,6 +256,103 @@ def pytest_collection_modifyitems(config, items):
reason=f"{kind} driver {driver.value} not applicable to "
f"{file_kind} test file"))

# On Aurora and Multi-AZ DB clusters, run a test once more when it failed because the cluster stopped
# accepting connections. Autoscaling and blue/green tests change the cluster, and performance tests
# would measure a different run, so they are not rerun.
if TestEnvironment.get_current().get_deployment() in _CLUSTER_DEPLOYMENTS:
config.option.max_suite_reruns = _MAX_CLUSTER_OUTAGE_RERUNS
rerun_on_outage = pytest.mark.flaky(
reruns=1, reruns_delay=CLUSTER_OUTAGE_RERUN_DELAY_SEC, condition=_rerun_after_cluster_outage)
for item in items:
if not item.path.name.startswith(_NO_RERUN_MODULE_PREFIXES):
item.add_marker(rerun_on_outage)


class _Attempt:
# Set when a failed phase of the current attempt was not a cluster outage
failed_other_than_outage: ClassVar[bool] = False


def _phase_failed_on_cluster_outage(error: Optional[BaseException]) -> bool:
# A failure the test caused by cutting connectivity is not an outage
return not ProxyHelper.connectivity_disabled and RdsTestUtility.is_cluster_outage(
error, RdsTestUtility.failover_requested)


def _rerun_after_cluster_outage(error: Optional[BaseException]) -> bool:
# Rerun only when every failed phase of the attempt was an outage
return not _Attempt.failed_other_than_outage and _phase_failed_on_cluster_outage(error)


def _set_timeout_timer(item):
timeout_settings = pytest_timeout.get_env_settings(item.config)
timeout_marker = item.get_closest_marker("timeout")
if timeout_marker is not None:
if timeout_marker.args:
timeout = timeout_marker.args[0]
else:
timeout = timeout_marker.kwargs.get("timeout", timeout_settings.timeout)
if len(timeout_marker.args) > 1:
method = timeout_marker.args[1]
else:
method = timeout_marker.kwargs.get("method", timeout_settings.method)
timeout_settings = timeout_settings._replace(
timeout=timeout,
method=method,
func_only=timeout_marker.kwargs.get("func_only", timeout_settings.func_only))
# pytest-timeout sets a function-only timer itself at the call. No timeout, or 0, means none.
if timeout_settings.func_only or not timeout_settings.timeout:
return
item.config.hook.pytest_timeout_set_timer(item=item, settings=timeout_settings)


# trylast makes this the inner wrapper, so the attempt's failures are recorded before
# pytest-rerunfailures evaluates the rerun condition in its own wrapper
@pytest.hookimpl(wrapper=True, trylast=True)
def pytest_runtest_makereport(item, call):
report = yield
if report.failed:
try:
outage = _phase_failed_on_cluster_outage(call.excinfo.value if call.excinfo is not None else None)
except Exception as e: # noqa: BLE001 -- an error here would end the whole session
logger.warning(f"Could not classify the failure, so the test is not rerun: {e}")
outage = False
if not outage:
_Attempt.failed_other_than_outage = True
if report.when in ("setup", "call"):
_attach_recent_rds_events(item, report)
return report


def _attach_recent_rds_events(item, report):
# Shows whether RDS restarted or failed over an instance around a failure
try:
info = TestEnvironment.get_current().get_info()
if info.get_request().get_database_engine_deployment() not in _CLUSTER_DEPLOYMENTS:
return
# pytest-timeout stops the test's timer only after this hook, and a lookup that ran past it
# would end the whole session instead of reporting this failure
item.config.hook.pytest_timeout_cancel_timer(item=item)
call_config = Config(
connect_timeout=RDS_EVENTS_CALL_TIMEOUT_SEC, read_timeout=RDS_EVENTS_CALL_TIMEOUT_SEC,
retries={"total_max_attempts": 1})
rds_utility = RdsTestUtility(info.get_region(), info.get_rds_endpoint(), call_config)
instance_ids = [instance.get_instance_id() for instance in TestEnvironment.get_current().get_instances()]
events = rds_utility.get_recent_events(
info.get_db_name(), instance_ids, RDS_EVENTS_LOOKBACK_SEC, RDS_EVENTS_BUDGET_SEC)
lines = [f"{event.get('Date')} {event.get('SourceIdentifier')}: {event.get('Message')}" for event in events]
except Exception as e:
logger.warning(f"Could not read RDS events: {e}")
return

for line in lines:
logger.warning(f"RDS event {line}")
if lines:
text = "\n".join(lines)
report.sections.append(("RDS events", text))
# pytest-html leaves sections out of rerun reports, but keeps extras
report.extras = [*getattr(report, "extras", []), html_extras.text(text, name="RDS events")]


def pytest_sessionstart(session):
TestEnvironment.get_current()
Expand Down
9 changes: 9 additions & 0 deletions tests/integration/container/test_aurora_failover_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@

from aws_advanced_python_wrapper.utils.log import Logger
from .utils.rds_test_utility import RdsTestUtility
from .utils.retry_helper import retry_until
from .utils.test_environment import TestEnvironment
from .utils.test_environment_features import TestEnvironmentFeatures
from .utils.test_timings import FAILOVER_WITHIN_TRANSACTION_PYTEST_TIMEOUT_SEC
Expand Down Expand Up @@ -269,6 +270,8 @@ async def inner() -> None:
# than the control-plane ``DescribeDBClusters.IsClusterWriter``,
# which can lag by tens of seconds to minutes post-failover.
assert await query_host_role_async(conn) == HostRole.WRITER
# RDS API lags behind the writer election, so we retry the check.
assert retry_until(lambda: aurora_utility.is_db_instance_writer(current_connection_id))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we still need this retry_util? I believe the RDS team pushed a fix that should have addressed the RDS API lag issue that we have been seeing?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just added to keep it the same as the sync tests but can remove it from both if it is not required.

next_cluster_writer_id = aurora_utility.get_cluster_writer_instance_id()
assert current_connection_id == next_cluster_writer_id
assert current_connection_id != initial_writer_id
Expand Down Expand Up @@ -318,6 +321,8 @@ async def inner() -> None:
# than the control-plane ``DescribeDBClusters.IsClusterWriter``,
# which can lag by tens of seconds to minutes post-failover.
assert await query_host_role_async(conn) == HostRole.WRITER
# RDS API lags behind the writer election, so we retry the check.
assert retry_until(lambda: aurora_utility.is_db_instance_writer(current_connection_id))
next_cluster_writer_id = aurora_utility.get_cluster_writer_instance_id()
assert current_connection_id == next_cluster_writer_id
assert current_connection_id != initial_writer_id
Expand Down Expand Up @@ -367,6 +372,8 @@ async def inner() -> None:
# assert that we are connected to the new writer after failover happens
# Data-plane writer check; see earlier sites for rationale.
assert await query_host_role_async(conn) == HostRole.WRITER
# RDS API lags behind the writer election, so we retry the check.
assert retry_until(lambda: aurora_utility.is_db_instance_writer(current_connection_id))
next_cluster_writer_id: str = aurora_utility.get_cluster_writer_instance_id()

assert current_connection_id == next_cluster_writer_id
Expand Down Expand Up @@ -424,6 +431,8 @@ async def inner() -> None:
# assert that we are connected to the new writer after failover happens
# Data-plane writer check; see earlier sites for rationale.
assert await query_host_role_async(conn) == HostRole.WRITER
# RDS API lags behind the writer election, so we retry the check.
assert retry_until(lambda: aurora_utility.is_db_instance_writer(current_connection_id))
next_cluster_writer_id: str = aurora_utility.get_cluster_writer_instance_id()

assert current_connection_id == next_cluster_writer_id
Expand Down
Loading
Loading