diff --git a/aws_advanced_python_wrapper/cluster_topology_monitor.py b/aws_advanced_python_wrapper/cluster_topology_monitor.py index ae3df67ab..0b3ee7df1 100644 --- a/aws_advanced_python_wrapper/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/cluster_topology_monitor.py @@ -840,10 +840,10 @@ def __call__(self) -> None: try: is_writer = self._monitor._topology_utils.get_writer_id_if_connected( connection, self._monitor._plugin_service.driver_dialect) is not None - except Exception: + except Exception as ex: + logger.debug("HostMonitor.WriterCheckFailed", self._host_info.host, ex) self._monitor._close_connection(connection) connection = None - continue if is_writer: try: diff --git a/aws_advanced_python_wrapper/host_list_provider.py b/aws_advanced_python_wrapper/host_list_provider.py index e136a20f7..8f655657f 100644 --- a/aws_advanced_python_wrapper/host_list_provider.py +++ b/aws_advanced_python_wrapper/host_list_provider.py @@ -583,16 +583,13 @@ def create_host( return host_info def get_writer_id_if_connected(self, connection: Connection, driver_dialect: DriverDialect) -> Optional[str]: - try: - cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( - self._thread_pool, self._max_timeout_sec, driver_dialect, connection)(self._get_writer_id) - result = cursor_execute_func_with_timeout(connection) - if result: - host_id: str = result[0] - return host_id - return None - except Exception: - return None + cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( + self._thread_pool, self._max_timeout_sec, driver_dialect, connection)(self._get_writer_id) + result = cursor_execute_func_with_timeout(connection) + if result: + host_id: str = result[0] + return host_id + return None def _get_writer_id(self, conn: Connection): with closing(conn.cursor()) as cursor: diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 3c5726725..1d5cd7325 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -243,6 +243,7 @@ HostMonitor.Exception=[HostMonitor] Host monitor for host {} is exiting due to a HostMonitor.MonitorCompleted=[HostMonitor] Host monitor for {} completed in {} ms. HostMonitor.WriterHostChanged=[HostMonitor] Writer host changed from {} to {}. HostMonitor.WriterChangeExitTriggered=[HostMonitor] Reader observed a writer change to {} while some regions are inaccessible; signaling panic-mode exit. +HostMonitor.WriterCheckFailed=[HostMonitor] The writer check on host '{}' failed, so the host monitor connects to it again. Error: '{}' HostMonitoringPlugin.ActivatedMonitoring=[HostMonitoringPlugin] Executing method '{}', monitoring is activated. HostMonitoringPlugin.ClusterEndpointHostInfo=[HostMonitoringPlugin] The HostInfo to monitor is associated with a cluster endpoint. The plugin will attempt to identify the connected database instance. diff --git a/tests/integration/container/conftest.py b/tests/integration/container/conftest.py index 017e6897e..079dd264c 100644 --- a/tests/integration/container/conftest.py +++ b/tests/integration/container/conftest.py @@ -49,10 +49,11 @@ from botocore.config import Config from pytest_html import extras as html_extras # type: ignore[import-untyped] +from tests.integration.container.utils.attempt_state import AttemptState 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.rds_test_utility import RDS_API_RETRY_CONFIG, RdsTestUtility from .utils.test_environment import TestEnvironment from .utils.test_environment_features import TestEnvironmentFeatures from .utils.test_timings import (CLUSTER_OUTAGE_RERUN_DELAY_SEC, @@ -120,9 +121,11 @@ def pytest_runtest_setup(item): _Attempt.failed_other_than_outage = False ProxyHelper.connectivity_disabled = False RdsTestUtility.failover_requested = False + timeout_settings = _get_attempt_timeout_settings(item) + AttemptState.reset(None if timeout_settings is None else timeit.default_timer() + timeout_settings.timeout) # 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) + if timeout_settings is not None and getattr(item, "execution_count", 1) > 1: + item.config.hook.pytest_timeout_set_timer(item=item, settings=timeout_settings) segment: Optional[Segment] = None if TestEnvironmentFeatures.TELEMETRY_TRACES_ENABLED in TestEnvironment.get_current().get_features(): @@ -142,7 +145,7 @@ def pytest_runtest_setup(item): deployment = request.get_database_engine_deployment() if DatabaseEngineDeployment.AURORA == deployment or DatabaseEngineDeployment.RDS_MULTI_AZ_CLUSTER == deployment: - rds_utility = RdsTestUtility(info.get_region(), info.get_rds_endpoint()) + rds_utility = RdsTestUtility(info.get_region(), info.get_rds_endpoint(), RDS_API_RETRY_CONFIG) rds_utility.wait_until_cluster_has_desired_status(info.get_db_name(), "available") # Need to ensure that cluster details through API matches topology fetched through SQL @@ -274,9 +277,7 @@ class _Attempt: 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) + return RdsTestUtility.is_rerun_cause(error, RdsTestUtility.failover_requested, ProxyHelper.connectivity_disabled) def _rerun_after_cluster_outage(error: Optional[BaseException]) -> bool: @@ -284,7 +285,7 @@ def _rerun_after_cluster_outage(error: Optional[BaseException]) -> bool: return not _Attempt.failed_other_than_outage and _phase_failed_on_cluster_outage(error) -def _set_timeout_timer(item): +def _get_attempt_timeout_settings(item): timeout_settings = pytest_timeout.get_env_settings(item.config) timeout_marker = item.get_closest_marker("timeout") if timeout_marker is not None: @@ -302,8 +303,8 @@ def _set_timeout_timer(item): 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) + return None + return timeout_settings # trylast makes this the inner wrapper, so the attempt's failures are recorded before diff --git a/tests/integration/container/django/test_django_plugins.py b/tests/integration/container/django/test_django_plugins.py index cfd542583..5e89f23a9 100644 --- a/tests/integration/container/django/test_django_plugins.py +++ b/tests/integration/container/django/test_django_plugins.py @@ -33,7 +33,8 @@ from aws_advanced_python_wrapper.errors import FailoverSuccessError from aws_advanced_python_wrapper.hostinfo import HostRole -from tests.integration.container.utils.rds_test_utility import RdsTestUtility +from tests.integration.container.utils.rds_test_utility import ( + RDS_API_RETRY_CONFIG, RdsTestUtility) from ..utils.conditions import (disable_on_features, enable_on_deployments, enable_on_engines, enable_on_features, enable_on_num_instances) @@ -103,7 +104,7 @@ def create_custom_endpoint(self): env_info = TestEnvironment.get_current().get_info() region = env_info.get_region() - rds_client = client('rds', region_name=region) + rds_client = client('rds', region_name=region, config=RDS_API_RETRY_CONFIG) if not self.reuse_existing_endpoint: instances = env_info.get_database_info().get_instances() self._create_endpoint(rds_client, instances[0:1]) diff --git a/tests/integration/container/test_custom_endpoint.py b/tests/integration/container/test_custom_endpoint.py index d109d81c1..200f3a4e1 100644 --- a/tests/integration/container/test_custom_endpoint.py +++ b/tests/integration/container/test_custom_endpoint.py @@ -39,7 +39,8 @@ from tests.integration.container.utils.database_engine_deployment import \ DatabaseEngineDeployment from tests.integration.container.utils.driver_helper import DriverHelper -from tests.integration.container.utils.rds_test_utility import RdsTestUtility +from tests.integration.container.utils.rds_test_utility import ( + RDS_API_RETRY_CONFIG, RdsTestUtility) from tests.integration.container.utils.retry_helper import retry_until from tests.integration.container.utils.test_environment import TestEnvironment from tests.integration.container.utils.test_environment_features import \ @@ -114,7 +115,7 @@ def setup_and_teardown(self): env_info = TestEnvironment.get_current().get_info() region = env_info.get_region() - rds_client = client('rds', region_name=region) + rds_client = client('rds', region_name=region, config=RDS_API_RETRY_CONFIG) if not self.reuse_existing_endpoint: instances = env_info.get_database_info().get_instances() self._create_endpoint(rds_client, instances[0:1]) @@ -370,7 +371,7 @@ def test_custom_endpoint_read_write_splitting__with_custom_endpoint_changes__wit with pytest.raises(ReadWriteSplittingError): conn.read_only = False - rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region()) + rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region(), config=RDS_API_RETRY_CONFIG) # Capture writer_id from the control plane, but re-confirm it after # the endpoint stabilization wait. The preceding test_custom_endpoint_failover @@ -484,7 +485,7 @@ def test_custom_endpoint_read_write_splitting__with_custom_endpoint_changes__wit reader_id_to_add = instance_id break - rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region()) + rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region(), config=RDS_API_RETRY_CONFIG) rds_client.modify_db_cluster_endpoint( DBClusterEndpointIdentifier=self.endpoint_id, StaticMembers=[original_writer_id, reader_id_to_add] diff --git a/tests/integration/container/test_custom_endpoint_async.py b/tests/integration/container/test_custom_endpoint_async.py index 078738adb..7079d6424 100644 --- a/tests/integration/container/test_custom_endpoint_async.py +++ b/tests/integration/container/test_custom_endpoint_async.py @@ -54,7 +54,8 @@ from tests.integration.container.utils.database_engine import DatabaseEngine from tests.integration.container.utils.database_engine_deployment import \ DatabaseEngineDeployment -from tests.integration.container.utils.rds_test_utility import RdsTestUtility +from tests.integration.container.utils.rds_test_utility import ( + RDS_API_RETRY_CONFIG, RdsTestUtility) from tests.integration.container.utils.test_environment import TestEnvironment from tests.integration.container.utils.test_environment_features import \ TestEnvironmentFeatures @@ -106,6 +107,8 @@ async def _query_host_role_async( @disable_on_features([TestEnvironmentFeatures.RUN_AUTOSCALING_TESTS_ONLY, TestEnvironmentFeatures.BLUE_GREEN_DEPLOYMENT, TestEnvironmentFeatures.PERFORMANCE]) +# Custom-endpoint changes can outlast the harness's 600 s per-test timeout. +@pytest.mark.timeout(1800) class TestCustomEndpointAsync: logger: ClassVar[Logger] = Logger(__name__) endpoint_id: ClassVar[str] = f"test-endpoint-1-async-{uuid4()}" @@ -151,7 +154,7 @@ def setup_and_teardown(self): env_info = TestEnvironment.get_current().get_info() region = env_info.get_region() - rds_client = client('rds', region_name=region) + rds_client = client('rds', region_name=region, config=RDS_API_RETRY_CONFIG) if not self.reuse_existing_endpoint: instances = env_info.get_database_info().get_instances() self._create_endpoint(rds_client, instances[0:1]) @@ -441,7 +444,7 @@ async def inner(): writer_id = rds_utils.get_cluster_writer_instance_id() - rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region()) + rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region(), config=RDS_API_RETRY_CONFIG) rds_client.modify_db_cluster_endpoint( DBClusterEndpointIdentifier=self.endpoint_id, StaticMembers=[original_reader_id, writer_id] @@ -533,7 +536,7 @@ async def inner(): reader_id_to_add = instance_id break - rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region()) + rds_client = client('rds', region_name=TestEnvironment.get_current().get_aurora_region(), config=RDS_API_RETRY_CONFIG) rds_client.modify_db_cluster_endpoint( DBClusterEndpointIdentifier=self.endpoint_id, StaticMembers=[original_writer_id, reader_id_to_add] diff --git a/tests/integration/container/utils/attempt_state.py b/tests/integration/container/utils/attempt_state.py new file mode 100644 index 000000000..36a8681f0 --- /dev/null +++ b/tests/integration/container/utils/attempt_state.py @@ -0,0 +1,34 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# 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 + +from typing import ClassVar, Optional + + +class AttemptState: + """What the failover helper and the conftest share about the current test attempt. + + The container imports these utils under two package names, so every user imports this module as + ``tests.integration.container.utils.attempt_state`` to get the one copy. + """ + + # The timeit.default_timer() value at which pytest-timeout ends the attempt + deadline: ClassVar[Optional[float]] = None + slow_failover_sec: ClassVar[Optional[float]] = None + + @classmethod + def reset(cls, deadline: Optional[float]) -> None: + cls.deadline = deadline + cls.slow_failover_sec = None diff --git a/tests/integration/container/utils/rds_test_utility.py b/tests/integration/container/utils/rds_test_utility.py index e42ed3736..951d13fef 100644 --- a/tests/integration/container/utils/rds_test_utility.py +++ b/tests/integration/container/utils/rds_test_utility.py @@ -20,12 +20,12 @@ cast) import botocore.exceptions +from botocore.config import Config +from tests.integration.container.utils.attempt_state import AttemptState from tests.integration.container.utils.proxy_helper import ProxyHelper if TYPE_CHECKING: - from botocore.config import Config - from aws_advanced_python_wrapper.pep249 import Connection from .test_database_info import TestDatabaseInfo @@ -34,7 +34,7 @@ import socket import timeit from datetime import datetime, timedelta, timezone -from time import perf_counter_ns, sleep +from time import sleep import boto3 import psycopg @@ -52,7 +52,8 @@ CLUSTER_STATUS_TIMEOUT_SEC, FAILOVER_DEADLINE_SEC, FAILOVER_MAX_REISSUES, FAILOVER_REISSUE_MIN_REMAINING_SEC, INITIAL_WRITER_POLL_INTERVAL_SEC, INITIAL_WRITER_REVERT_WINDOW_SEC, INSTANCE_STATUS_POLL_INTERVAL_SEC, - INSTANCE_UP_TIMEOUT_SEC, WRITER_CHANGE_TIMEOUT_SEC, + INSTANCE_UP_TIMEOUT_SEC, RDS_API_CALL_TIMEOUT_SEC, RDS_API_MAX_ATTEMPTS, + SLOW_FAILOVER_SEC, WRAPPER_FAILOVER_RESERVE_SEC, WRITER_CHANGE_TIMEOUT_SEC, WRITER_CHANGED_PROBE_CONNECT_TIMEOUT_SEC, WRITER_CHANGED_PROBE_POLL_INTERVAL_SEC) from .database_engine import DatabaseEngine @@ -67,6 +68,7 @@ # reruns a test that fails this way once. _HELPER_OUTAGE_PATTERNS = ( re.compile(r"did not finish within"), + re.compile(r"No time left for a failover"), re.compile(r"did not accept a connection"), re.compile(r"did not become available"), ) @@ -82,6 +84,10 @@ # What a connect timeout is raised from. Anything else in the chain, such as an assertion whose cleanup then # failed to connect, or a query the test ran, is the test's own failure. _CONNECT_TIMEOUT_CAUSES = (OSError, asyncio.TimeoutError, MySQLConnectionTimeoutError, psycopg.errors.ConnectionTimeout) +# Not given to the failover helper, so a throttled call there cannot use the wrapper's failover time +RDS_API_RETRY_CONFIG = Config( + connect_timeout=RDS_API_CALL_TIMEOUT_SEC, read_timeout=RDS_API_CALL_TIMEOUT_SEC, + retries={"mode": "adaptive", "total_max_attempts": RDS_API_MAX_ATTEMPTS}) class RdsTestUtility: @@ -245,6 +251,20 @@ def is_cluster_outage(error: Optional[BaseException], after_failover: bool = Fal # Every exception the outermost one was raised from or while handling must be part of a connect timeout return all(isinstance(exception, _CONNECT_TIMEOUT_CAUSES) for exception in chain[1:]) + @staticmethod + def is_rerun_cause(error: Optional[BaseException], after_failover: bool, connectivity_disabled: bool) -> bool: + """Tell whether the conftest reruns a test attempt that failed with this error. + + :param error: the exception the test failed with, or None. + :param after_failover: whether the test requested a failover before it failed. + :param connectivity_disabled: whether the test had cut its own connectivity through the proxy. + :return: True for any failure after a failover that took longer than ``SLOW_FAILOVER_SEC``, since the + cluster was then slow. Otherwise True for a cluster outage, unless the test cut its own connectivity. + """ + if AttemptState.slow_failover_sec is not None: + return True + return not connectivity_disabled and RdsTestUtility.is_cluster_outage(error, after_failover) + def get_db_cluster(self, cluster_id: str) -> Any: response: Any = self._client.describe_db_clusters(DBClusterIdentifier=cluster_id) clusters = response.get("DBClusters") @@ -261,8 +281,14 @@ def failover_cluster_and_wait_until_writer_changed( if DatabaseEngineDeployment.RDS_MULTI_AZ_CLUSTER == deployment and target_id is not None: raise Exception(Messages.get_formatted("RdsTestUtility.FailoverToTargetNotSupported", target_id, deployment)) - start = perf_counter_ns() - deadline = timeit.default_timer() + FAILOVER_DEADLINE_SEC + start = timeit.default_timer() + deadline = start + FAILOVER_DEADLINE_SEC + if AttemptState.deadline is not None: + attempt_left_sec = AttemptState.deadline - start + if attempt_left_sec <= WRAPPER_FAILOVER_RESERVE_SEC: + pytest.fail(f"No time left for a failover: the test's timeout leaves {attempt_left_sec:.0f} s, " + f"less than the {WRAPPER_FAILOVER_RESERVE_SEC:.0f} s the wrapper's failover needs") + deadline = min(deadline, AttemptState.deadline - WRAPPER_FAILOVER_RESERVE_SEC) self._last_connect_error = None if cluster_id is None: cluster_id = TestEnvironment.get_current().get_info().get_db_name() @@ -272,39 +298,52 @@ def failover_cluster_and_wait_until_writer_changed( database_info = TestEnvironment.get_current().get_database_info() cluster_endpoint = database_info.get_cluster_endpoint() - initial_cluster_address = socket.gethostbyname(cluster_endpoint) + previous_cluster_address = socket.gethostbyname(cluster_endpoint) self.failover_cluster(cluster_id, target_id, deadline - timeit.default_timer()) + previous_writer_id = initial_writer_id remaining_reissues = FAILOVER_MAX_REISSUES while True: remaining_sec = deadline - timeit.default_timer() if remaining_sec <= 0: # The conftest reruns a test that fails with this message once - pytest.fail(f"Failover from {initial_writer_id} did not finish within {FAILOVER_DEADLINE_SEC} s. " + pytest.fail(f"Failover from {initial_writer_id} did not finish within {deadline - start:.0f} s. " f"Last connect error: {self._last_connect_error}") - if self.writer_changed(initial_writer_id, cluster_id, min(WRITER_CHANGE_TIMEOUT_SEC, remaining_sec)): - if not self._initial_writer_kept_writer_role(initial_writer_id, deadline): + if self.writer_changed(previous_writer_id, cluster_id, min(WRITER_CHANGE_TIMEOUT_SEC, remaining_sec)): + if not self._initial_writer_kept_writer_role(previous_writer_id, deadline): if timeit.default_timer() >= deadline: self.logger.warning( - f"Initial writer {initial_writer_id} did not answer as a reader before the failover deadline") - break + f"Writer {previous_writer_id} did not answer as a reader before the failover deadline") + writer_id = self._writer_instead_of_target(cluster_id, target_id, deadline, deadline - start) + if writer_id is None: + break + if remaining_reissues == 0 or deadline - timeit.default_timer() < FAILOVER_REISSUE_MIN_REMAINING_SEC: + pytest.fail(f"Failover to {target_id} did not finish within {deadline - start:.0f} s: " + f"{writer_id} is the writer") + self.logger.warning( + f"Failover went to {writer_id} instead of {target_id}; requesting a failover to {target_id} again") + previous_writer_id = writer_id + previous_cluster_address = socket.gethostbyname(cluster_endpoint) elif DatabaseEngineDeployment.AURORA == deployment: # No new writer yet. If the initial writer doesn't answer, or stops answering as the writer, # a second failover would not help, and on two instances it hands the writer role back. # Check for a new writer again once the initial writer's window can't complete. - if self._query_instance_role(initial_writer_id) != HostRole.WRITER: + if self._query_instance_role(previous_writer_id) != HostRole.WRITER: continue window_deadline = min(deadline, timeit.default_timer() + 2 * INITIAL_WRITER_REVERT_WINDOW_SEC) - if not self._initial_writer_kept_writer_role(initial_writer_id, window_deadline): + if not self._initial_writer_kept_writer_role(previous_writer_id, window_deadline): continue - # The failover did not take, or the initial writer is the writer again: request it again - if remaining_reissues == 0 or deadline - timeit.default_timer() < FAILOVER_REISSUE_MIN_REMAINING_SEC: + # Failover did not take, hit a non-target instance, or the initial writer is the writer again: request again + if remaining_reissues == 0: raise Exception(Messages.get("RdsTestUtility.FailoverRequestNotSuccessful")) + if deadline - timeit.default_timer() < FAILOVER_REISSUE_MIN_REMAINING_SEC: + pytest.fail(f"Failover from {initial_writer_id} did not finish within {deadline - start:.0f} s: " + f"{previous_writer_id} kept the writer role") self.wait_until_cluster_has_desired_status(cluster_id, "available", deadline - timeit.default_timer()) if (DatabaseEngineDeployment.AURORA == deployment - and self._query_instance_role(initial_writer_id) != HostRole.WRITER): + and self._query_instance_role(previous_writer_id) != HostRole.WRITER): # A failover that was still running has finished while the cluster was busy continue remaining_reissues -= 1 @@ -312,14 +351,36 @@ def failover_cluster_and_wait_until_writer_changed( # Failover has finished, wait for DNS to be updated so cluster endpoint resolves to the new writer instance. cluster_address = socket.gethostbyname(cluster_endpoint) - while cluster_address == initial_cluster_address and timeit.default_timer() < deadline: + while cluster_address == previous_cluster_address and timeit.default_timer() < deadline: sleep(1) cluster_address = socket.gethostbyname(cluster_endpoint) - # wait until all instances except initial writer instance to be available - instances = [x.get_instance_id() for x in TestEnvironment.get_current().get_instances() if x.get_instance_id() != initial_writer_id] + # The demoted writer may still be restarting, so only the other instances must be up + instances = [x.get_instance_id() for x in TestEnvironment.get_current().get_instances() if x.get_instance_id() != previous_writer_id] self.make_sure_instances_up(instances, deadline) - self.logger.debug("Testing.FinishedFailover", initial_writer_id, str((perf_counter_ns() - start) / 1_000_000)) + failover_sec = timeit.default_timer() - start + if failover_sec > SLOW_FAILOVER_SEC: + if AttemptState.slow_failover_sec is None or failover_sec > AttemptState.slow_failover_sec: + AttemptState.slow_failover_sec = failover_sec + self.logger.warning(f"Failover from {initial_writer_id} took {failover_sec:.0f} s, more than " + f"{SLOW_FAILOVER_SEC:.0f} s, so a failure of this attempt is rerun") + self.logger.debug("Testing.FinishedFailover", initial_writer_id, str(failover_sec * 1000)) + + def _writer_instead_of_target( + self, cluster_id: str, target_id: Optional[str], deadline: float, budget_sec: float) -> Optional[str]: + if target_id is None or DatabaseEngineDeployment.AURORA != TestEnvironment.get_current().get_deployment(): + return None + while True: + # Aurora can still move the writer elsewhere, for example while the target restarts as a reader + writer_id = self.get_cluster_writer_instance_id(cluster_id) + if writer_id != target_id and self._query_instance_role(writer_id) == HostRole.WRITER: + return writer_id + if self._query_instance_role(target_id) == HostRole.WRITER: + return None + if timeit.default_timer() >= deadline: + pytest.fail(f"Failover to {target_id} did not finish within {budget_sec:.0f} s: " + "it does not answer as the writer") + sleep(WRITER_CHANGED_PROBE_POLL_INTERVAL_SEC) def failover_cluster( self, diff --git a/tests/integration/container/utils/test_timings.py b/tests/integration/container/utils/test_timings.py index 26d342859..ff08cdac5 100644 --- a/tests/integration/container/utils/test_timings.py +++ b/tests/integration/container/utils/test_timings.py @@ -61,15 +61,17 @@ WRITER_CHANGED_PROBE_POLL_INTERVAL_SEC: float = 2.0 # ───── Failover helper deadline ──────────────────────────────────────── -# ``RdsTestUtility.failover_cluster_and_wait_until_writer_changed`` waits -# for a new writer, for the initial writer to restart as a reader, for the -# cluster endpoint's DNS and for the other instances. Every wait shares one -# deadline, so a cluster that stops answering for minutes fails one test -# instead of running past pytest's 600 s ``--timeout``, which ends the -# whole session. This bounds one call to about 420 s (one RDS status read, -# and one connect attempt for each instance, can run past it); the setup -# hook's waits are separate. A normal failover takes 20 to 35 s. +# One deadline shared by every wait in the failover helper, so a dead +# cluster fails one test instead of running past pytest's 600 s +# ``--timeout``, which ends the whole session. A call is bounded to about +# 420 s, less when the test's remaining pytest timeout is below this plus +# ``WRAPPER_FAILOVER_RESERVE_SEC``. A normal failover takes 16 to 35 s. FAILOVER_DEADLINE_SEC: float = 420 +# 300 s for the wrapper's own failover (``failover_timeout_sec`` default) +# plus 30 s for asserts, teardown, helper overrun and pytest-timeout +# starting before setup. With less left, the helper fails at once as an +# outage. +WRAPPER_FAILOVER_RESERVE_SEC: float = 330 # How long one failover request gets to produce a new writer before the # helper checks whether the initial writer is still the writer. WRITER_CHANGE_TIMEOUT_SEC: float = 180 @@ -93,6 +95,14 @@ INSTANCE_UP_TIMEOUT_SEC: float = 300 # How often ``make_sure_instances_up`` reads the instances' RDS status. INSTANCE_STATUS_POLL_INTERVAL_SEC: float = 2 +# The CI jobs share the account's RDS API rate. A throttled RDS API call is +# tried this many times in all, in botocore's adaptive retry mode, which +# also slows the client's own requests after a throttle. +RDS_API_MAX_ATTEMPTS: int = 13 +# The connect and read timeout of each of those attempts, so that all +# attempts of a call to an RDS API endpoint that stops answering, with +# their backoff, end inside the test's pytest timeout. +RDS_API_CALL_TIMEOUT_SEC: float = 10 # ───── RDS events on a failed test ──────────────────────────────────── # When a test fails on an Aurora or Multi-AZ DB cluster, the conftest logs @@ -111,6 +121,9 @@ # cluster stopped accepting connections is run once more after this delay, # so the instances can come back first. CLUSTER_OUTAGE_RERUN_DELAY_SEC: float = 60 +# A failover slower than this means the cluster was slow, so any failure +# of the attempt is rerun once. +SLOW_FAILOVER_SEC: float = 120 # ───── Long-running failover-during-transaction test ─────────────────── # ``test_writer_fail_within_transaction_start_transaction`` exercises a diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 95a1ae254..7827f83f6 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import pytest + from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ AsyncOpenedConnectionTracker from aws_advanced_python_wrapper.aio.minor_plugins import AsyncDeveloperPlugin @@ -43,3 +45,9 @@ def pytest_runtest_setup(item): DatabaseDialectManager.reset_custom_dialect() DriverDialectManager.reset_custom_dialect() ExceptionManager.reset_custom_handler() + + +@pytest.fixture +def release_topology_utils_pool(): + yield + services_container.release_thread_pool("AuroraTopologyUtils", wait=True) diff --git a/tests/unit/test_cluster_topology_monitor.py b/tests/unit/test_cluster_topology_monitor.py index 66f39f73f..5b56f3af3 100644 --- a/tests/unit/test_cluster_topology_monitor.py +++ b/tests/unit/test_cluster_topology_monitor.py @@ -14,17 +14,56 @@ from __future__ import annotations +import threading import time from unittest.mock import MagicMock, patch +import psycopg.errors import pytest +from mysql.connector.errors import ProgrammingError from aws_advanced_python_wrapper.cluster_topology_monitor import ( ClusterTopologyMonitorImpl, HostMonitor) +from aws_advanced_python_wrapper.database_dialect import AuroraPgDialect +from aws_advanced_python_wrapper.host_list_provider import AuroraTopologyUtils from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) +_INSTANCE_HOST = "instance-1.xyz.us-east-2.rds.amazonaws.com" + + +class _WriterQueryError(Exception): + pass + + +def _aurora_topology_utils(auxiliary_query_timeout_sec=5): + props = Properties({"host": _INSTANCE_HOST}) + WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.set(props, str(auxiliary_query_timeout_sec)) + return AuroraTopologyUtils(AuroraPgDialect(), props) + + +def _dead_connection(error): + connection = MagicMock() + connection.cursor.return_value.execute.side_effect = error + return connection + + +def _writer_connection(writer_id): + connection = MagicMock() + connection.cursor.return_value.fetchone.return_value = (writer_id,) + return connection + + +def _stop_after_calls(monitor_impl_mock, calls): + call_count = [0] + + def stop(): + call_count[0] += 1 + return call_count[0] > calls + + monitor_impl_mock._host_threads_stop.is_set.side_effect = stop + @pytest.fixture def plugin_service_mock(): @@ -213,6 +252,20 @@ def test_open_any_connection_and_update_topology_verifies_writer(self, cluster_m assert cluster_monitor._is_verified_writer_connection assert cluster_monitor._writer_host_info.get() is not None + def test_open_any_connection_writer_check_error_keeps_connection( + self, cluster_monitor, release_topology_utils_pool): + connection = _dead_connection(_WriterQueryError("the connection is closed")) + cluster_monitor._topology_utils = _aurora_topology_utils() + cluster_monitor._writer_host_info.set(None) + cluster_monitor._plugin_service.force_connect.return_value = connection + cluster_monitor._fetch_topology_and_update_cache = MagicMock( + return_value=(HostInfo("writer.com", 5432, HostRole.WRITER),)) + + cluster_monitor._open_any_connection_and_update_topology() + + assert cluster_monitor._is_verified_writer_connection is False + assert cluster_monitor._monitoring_connection.get() is connection + class TestHostMonitor: @pytest.fixture @@ -322,6 +375,75 @@ def test_call_login_exception_raises(self, monitor_impl_mock): # Verify force_connect was called monitor_impl_mock._plugin_service.force_connect.assert_called() + @pytest.mark.parametrize("error", [ + _WriterQueryError("the connection is closed"), + psycopg.errors.SyntaxError("syntax error at or near \"SELEC\""), + ProgrammingError("Cursor is not connected"), + ], ids=["query_error", "pg_syntax_error", "mysql_programming_error"]) + def test_call_writer_check_error_reconnects(self, monitor_impl_mock, error, release_topology_utils_pool): + monitor = HostMonitor(monitor_impl_mock, HostInfo(_INSTANCE_HOST, 5432, HostRole.WRITER), None) + monitor_impl_mock._topology_utils = _aurora_topology_utils() + dead_connection = _dead_connection(error) + writer_connection = _writer_connection("instance-1") + monitor_impl_mock._plugin_service.force_connect.side_effect = [dead_connection, writer_connection] + monitor_impl_mock._plugin_service.get_host_role.return_value = HostRole.WRITER + _stop_after_calls(monitor_impl_mock, 20) + + with patch('time.sleep'): + monitor() + + assert monitor_impl_mock._plugin_service.force_connect.call_count == 2 + monitor_impl_mock._close_connection.assert_any_call(dead_connection) + monitor_impl_mock._host_threads_writer_connection.compare_and_set.assert_called_once_with(None, writer_connection) + + def test_call_writer_check_error_sleeps_before_reconnect(self, monitor_impl_mock, release_topology_utils_pool): + monitor = HostMonitor(monitor_impl_mock, HostInfo(_INSTANCE_HOST, 5432, HostRole.WRITER), None) + monitor_impl_mock._topology_utils = _aurora_topology_utils() + connections = iter([_dead_connection(_WriterQueryError("the connection is closed")), + _writer_connection("instance-1")]) + test_thread = threading.current_thread() + events = [] + + def connect(host_info, props): + events.append("connect") + return next(connections) + + def sleep(seconds): + if threading.current_thread() is test_thread: + events.append(seconds) + + monitor_impl_mock._plugin_service.force_connect.side_effect = connect + monitor_impl_mock._plugin_service.get_host_role.return_value = HostRole.WRITER + _stop_after_calls(monitor_impl_mock, 20) + + with patch('time.sleep', side_effect=sleep): + monitor() + + assert events == ["connect", 0.1, "connect"] + + def test_call_writer_check_timeout_reconnects(self, monitor_impl_mock, release_topology_utils_pool): + monitor = HostMonitor(monitor_impl_mock, HostInfo(_INSTANCE_HOST, 5432, HostRole.WRITER), None) + monitor_impl_mock._topology_utils = _aurora_topology_utils(auxiliary_query_timeout_sec=1) + aborted = threading.Event() + + def blocked_execute(query): + aborted.wait(5) + raise _WriterQueryError("the connection is closed") + + stuck_connection = MagicMock() + stuck_connection.cursor.return_value.execute.side_effect = blocked_execute + writer_connection = _writer_connection("instance-1") + monitor_impl_mock._plugin_service.force_connect.side_effect = [stuck_connection, writer_connection] + monitor_impl_mock._plugin_service.driver_dialect.abort_connection.side_effect = lambda conn: aborted.set() + monitor_impl_mock._plugin_service.get_host_role.return_value = HostRole.WRITER + _stop_after_calls(monitor_impl_mock, 20) + + with patch('time.sleep'): + monitor() + + assert monitor_impl_mock._plugin_service.force_connect.call_count == 2 + monitor_impl_mock._host_threads_writer_connection.compare_and_set.assert_called_once_with(None, writer_connection) + def test_reader_thread_fetch_topology(self, monitor_impl_mock): host_info = HostInfo("reader.com", 5432, HostRole.READER) writer_info = HostInfo("writer.com", 5432, HostRole.WRITER) diff --git a/tests/unit/test_monitoring_connection_handler.py b/tests/unit/test_monitoring_connection_handler.py index 4e291e388..2a68fd85c 100644 --- a/tests/unit/test_monitoring_connection_handler.py +++ b/tests/unit/test_monitoring_connection_handler.py @@ -18,6 +18,8 @@ from aws_advanced_python_wrapper.concrete_monitoring_connection_handlers import ( AuroraMonitoringConnectionHandler, GdbMonitoringConnectionHandler) +from aws_advanced_python_wrapper.database_dialect import AuroraPgDialect +from aws_advanced_python_wrapper.host_list_provider import AuroraTopologyUtils from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.utils.atomic import AtomicReference from aws_advanced_python_wrapper.utils.properties import (Properties, @@ -154,3 +156,28 @@ def test_primary_region_from_cached_writer(self): writer_ref: AtomicReference = AtomicReference(WRITER_EAST) handler, _ = _make_gdb_handler("strict-writer-primary", writer_ref) assert handler._get_primary_region() == "us-east-1" + + +class _WriterQueryError(Exception): + pass + + +def test_attempt_connection_upgrade_writer_check_error_drops_upgrade_connection(release_topology_utils_pool): + props = Properties({"host": "instance-1.xyz.us-east-1.rds.amazonaws.com"}) + WrapperProperties.MONITORING_CONNECTION_PRIORITY.set(props, "strict-reader,strict-writer") + dead_connection = MagicMock() + dead_connection.cursor.return_value.execute.side_effect = _WriterQueryError("the connection is closed") + plugin_service = MagicMock() + plugin_service.force_connect.return_value = dead_connection + monitoring_conn = ThreadSafeConnectionHolder(None) + handler = AuroraMonitoringConnectionHandler( + monitoring_conn, plugin_service, AuroraTopologyUtils(AuroraPgDialect(), props), props, Properties()) + writer_conn = MagicMock() + handler.accept_connection(writer_conn, True, WRITER_EAST) + handler.attempt_connection_upgrade((WRITER_EAST, READER_EAST)) + handler._upgrade_done.wait(5) + + handler.attempt_connection_upgrade(None) + + assert monitoring_conn.get() is writer_conn + dead_connection.close.assert_called_once() diff --git a/tests/unit/test_rds_host_list_provider.py b/tests/unit/test_rds_host_list_provider.py index 627d33be8..00d2f63fe 100644 --- a/tests/unit/test_rds_host_list_provider.py +++ b/tests/unit/test_rds_host_list_provider.py @@ -247,3 +247,24 @@ def test_force_monitoring_refresh_with_topology(mocker, mock_provider_service, p result = provider.force_monitoring_refresh(True, 5) assert result == expected_topology mock_monitor.force_refresh.assert_called_once_with(True, 5) + + +class _WriterQueryError(Exception): + pass + + +def test_get_writer_id_if_connected_query_error_raises( + mocker, mock_conn, mock_cursor, props, release_topology_utils_pool): + topology_utils = AuroraTopologyUtils(AuroraPgDialect(), props) + mock_cursor.execute.side_effect = _WriterQueryError("the connection is closed") + + with pytest.raises(_WriterQueryError): + topology_utils.get_writer_id_if_connected(mock_conn, mocker.MagicMock()) + + +def test_get_writer_id_if_connected_empty_result_returns_none( + mocker, mock_conn, mock_cursor, props, release_topology_utils_pool): + topology_utils = AuroraTopologyUtils(AuroraPgDialect(), props) + mock_cursor.fetchone.return_value = None + + assert topology_utils.get_writer_id_if_connected(mock_conn, mocker.MagicMock()) is None diff --git a/tests/unit/test_rds_test_utility.py b/tests/unit/test_rds_test_utility.py index 4bf6c960a..54a9046dc 100644 --- a/tests/unit/test_rds_test_utility.py +++ b/tests/unit/test_rds_test_utility.py @@ -16,11 +16,15 @@ import asyncio import datetime +import importlib import socket +import sys +from pathlib import Path import psycopg import psycopg.errors import pytest +from botocore.config import Config from botocore.exceptions import ClientError, EndpointConnectionError from mysql.connector.errors import \ ConnectionTimeoutError as MySQLConnectionTimeoutError @@ -31,13 +35,15 @@ FailoverFailedError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostRole +from aws_advanced_python_wrapper.utils.properties import WrapperProperties from tests.integration.container.utils.database_engine import DatabaseEngine from tests.integration.container.utils.database_engine_deployment import \ DatabaseEngineDeployment from tests.integration.container.utils.test_timings import ( FAILOVER_DEADLINE_SEC, FAILOVER_MAX_REISSUES, - INITIAL_WRITER_POLL_INTERVAL_SEC, INITIAL_WRITER_REVERT_WINDOW_SEC, - INSTANCE_STATUS_POLL_INTERVAL_SEC, INSTANCE_UP_TIMEOUT_SEC, + FAILOVER_REISSUE_MIN_REMAINING_SEC, INITIAL_WRITER_POLL_INTERVAL_SEC, + INITIAL_WRITER_REVERT_WINDOW_SEC, INSTANCE_STATUS_POLL_INTERVAL_SEC, + INSTANCE_UP_TIMEOUT_SEC, SLOW_FAILOVER_SEC, WRAPPER_FAILOVER_RESERVE_SEC, WRITER_CHANGE_TIMEOUT_SEC) _START_SEC = 1000.0 @@ -81,6 +87,65 @@ def utility(mocker, clock): return target, env +@pytest.fixture(autouse=True) +def attempt_without_timeout(): + rds_test_utility.AttemptState.reset(None) + yield + rds_test_utility.AttemptState.reset(None) + + +@pytest.fixture +def container_on_sys_path(monkeypatch): + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "integration")) + yield + for name in [name for name in sys.modules if name == "container" or name.startswith("container.")]: + del sys.modules[name] + + +@pytest.fixture +def isolated_aws_env(monkeypatch, tmp_path): + for name in ("AWS_RETRY_MODE", "AWS_MAX_ATTEMPTS", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("AWS_CONFIG_FILE", str(tmp_path / "missing-config")) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(tmp_path / "missing-credentials")) + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test-access-key-id") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-access-key") + monkeypatch.setattr(rds_test_utility.boto3, "DEFAULT_SESSION", None) + + +def _writer_after_each_failover(target, env, mocker, writer_ids): + def current_writer(cluster_id=None): + return writer_ids[target.failover_cluster.call_count] + + mocker.patch.object(target, "get_cluster_writer_instance_id", side_effect=current_writer) + env.get_instances.return_value = [ + mocker.MagicMock(**{"get_instance_id.return_value": instance_id}) + for instance_id in ("instance-1", "instance-2", "instance-3")] + env.get_database_info.return_value.get_instance.side_effect = lambda instance_id: instance_id + target._open_connection.side_effect = lambda instance_info: mocker.MagicMock(instance_id=instance_info) + target.query_host_role.side_effect = lambda conn, engine: ( + HostRole.WRITER if conn.instance_id == current_writer() else HostRole.READER) + rds_test_utility.socket.gethostbyname.side_effect = lambda host: f"address-of-{current_writer()}" + + +def _never_changes_writer(target, clock): + def _no_new_writer(initial_writer_id, cluster_id, timeout_sec): + clock[0] += timeout_sec + return False + + target.writer_changed.side_effect = _no_new_writer + target._open_connection.side_effect = ConnectionRefusedError("unreachable") + + +def _changes_writer_after(target, clock, seconds): + def _new_writer(initial_writer_id, cluster_id, timeout_sec): + clock[0] += seconds + return True + + target.writer_changed.side_effect = _new_writer + target.query_host_role.return_value = HostRole.READER + + def test_failover_waits_until_initial_writer_accepts_connections(utility, mocker): target, env = utility target._open_connection.side_effect = [ConnectionRefusedError("starting up"), mocker.MagicMock()] @@ -187,7 +252,7 @@ def _new_writer_after_reissue(initial_writer_id, cluster_id, timeout_sec): assert target.failover_cluster.call_count == 2 -def test_failover_near_deadline_not_reissued(utility, clock): +def test_failover_near_deadline_not_reissued_fails_as_outage(utility, clock): target, _ = utility def _slow_new_writer(initial_writer_id, cluster_id, timeout_sec): @@ -197,10 +262,30 @@ def _slow_new_writer(initial_writer_id, cluster_id, timeout_sec): target.writer_changed.side_effect = _slow_new_writer target.query_host_role.return_value = HostRole.WRITER - with pytest.raises(Exception, match="not successful"): + with pytest.raises(pytest.fail.Exception, match="kept the writer role") as excinfo: target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") assert target.failover_cluster.call_count == 1 + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_failover_dropped_request_without_time_to_reissue_fails_as_outage(utility, clock): + target, _ = utility + + def _no_new_writer(initial_writer_id, cluster_id, timeout_sec): + clock[0] += timeout_sec + return False + + target.writer_changed.side_effect = _no_new_writer + target.query_host_role.return_value = HostRole.WRITER + rds_test_utility.AttemptState.reset(_START_SEC + 600) + + with pytest.raises(pytest.fail.Exception, match="instance-1 kept the writer role") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + assert clock[0] - _START_SEC <= 600 - WRAPPER_FAILOVER_RESERVE_SEC + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True def test_failover_writer_window_bounded_by_deadline(utility, clock): @@ -252,6 +337,18 @@ def test_failover_reissues_at_most_max_times(utility): assert target.failover_cluster.call_count == 1 + FAILOVER_MAX_REISSUES +def test_failover_no_reissue_left_near_deadline_raises_not_successful(utility, clock): + target, _ = utility + target.query_host_role.return_value = HostRole.WRITER + rds_test_utility.AttemptState.reset(_START_SEC + 580) + + with pytest.raises(Exception, match="not successful"): + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert target.failover_cluster.call_count == 1 + FAILOVER_MAX_REISSUES + assert _START_SEC + 580 - WRAPPER_FAILOVER_RESERVE_SEC - clock[0] < FAILOVER_REISSUE_MIN_REMAINING_SEC + + def test_failover_initial_writer_reader_not_reissued(utility, clock): target, _ = utility @@ -402,6 +499,149 @@ def _writer_then_restarting(instance_info): assert target.failover_cluster.call_count == 1 +def test_failover_to_target_writer_elsewhere_is_reissued(utility, mocker): + target, env = utility + _writer_after_each_failover(target, env, mocker, ["instance-1", "instance-3", "instance-2"]) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster", "instance-2") + + assert target.failover_cluster.call_count == 2 + assert target.failover_cluster.call_args.args[1] == "instance-2" + target.make_sure_instances_up.assert_called_once_with(["instance-1", "instance-2"], mocker.ANY) + + +def test_failover_to_target_never_writer_fails_as_outage(utility, mocker): + target, env = utility + _writer_after_each_failover(target, env, mocker, ["instance-1", "instance-3", "instance-1", "instance-3"]) + + with pytest.raises(pytest.fail.Exception, match="did not finish within") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster", "instance-2") + + assert target.failover_cluster.call_count == 1 + FAILOVER_MAX_REISSUES + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=False) is True + + +def test_failover_to_target_answering_as_reader_fails_as_outage(utility, mocker): + target, env = utility + _writer_after_each_failover(target, env, mocker, ["instance-1", "instance-2"]) + target.query_host_role.side_effect = None + target.query_host_role.return_value = HostRole.READER + + with pytest.raises(pytest.fail.Exception, match="did not finish within") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster", "instance-2") + + assert target.failover_cluster.call_count == 1 + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_failover_to_target_writer_moved_while_waiting_is_reissued(utility, mocker): + target, env = utility + _writer_after_each_failover(target, env, mocker, ["instance-1", "instance-3", "instance-2"]) + target.get_cluster_writer_instance_id.side_effect = ["instance-2", "instance-3", "instance-2"] + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster", "instance-2") + + assert target.failover_cluster.call_count == 2 + assert target.failover_cluster.call_args.args[1] == "instance-2" + target.make_sure_instances_up.assert_called_once_with(["instance-1", "instance-2"], mocker.ANY) + + +def test_failover_to_target_writer_not_reissued(utility, mocker): + target, env = utility + _writer_after_each_failover(target, env, mocker, ["instance-1", "instance-2"]) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster", "instance-2") + + assert target.failover_cluster.call_count == 1 + + +def test_failover_to_target_after_stale_writer_read_not_reissued(utility, clock, mocker): + target, env = utility + _writer_after_each_failover(target, env, mocker, ["instance-1", "instance-2"]) + target.get_cluster_writer_instance_id.side_effect = ["instance-1", "instance-2"] + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster", "instance-2") + + assert target.failover_cluster.call_count == 1 + assert rds_test_utility.AttemptState.slow_failover_sec is None + assert clock[0] - _START_SEC < SLOW_FAILOVER_SEC + + +def test_failover_deadline_leaves_wrapper_failover_budget(utility, clock): + target, _ = utility + _never_changes_writer(target, clock) + rds_test_utility.AttemptState.reset(_START_SEC + 600) + + with pytest.raises(pytest.fail.Exception, match="did not finish within") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert clock[0] - _START_SEC <= 600 - WRAPPER_FAILOVER_RESERVE_SEC + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_failover_without_time_left_fails_as_outage(utility): + target, _ = utility + rds_test_utility.AttemptState.reset(_START_SEC + WRAPPER_FAILOVER_RESERVE_SEC - 10) + + with pytest.raises(pytest.fail.Exception, match="No time left for a failover") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + target.failover_cluster.assert_not_called() + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=False) is True + assert rds_test_utility.RdsTestUtility.is_cluster_outage(excinfo.value, after_failover=True) is True + + +def test_failover_long_timeout_keeps_full_deadline(utility, clock): + target, _ = utility + _never_changes_writer(target, clock) + rds_test_utility.AttemptState.reset(_START_SEC + 1800) + + with pytest.raises(pytest.fail.Exception, match="did not finish within"): + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert clock[0] - _START_SEC == FAILOVER_DEADLINE_SEC + + +def test_failover_without_attempt_deadline_keeps_full_deadline(utility, clock): + target, _ = utility + _never_changes_writer(target, clock) + + with pytest.raises(pytest.fail.Exception, match="did not finish within"): + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert clock[0] - _START_SEC == FAILOVER_DEADLINE_SEC + + +def test_wrapper_failover_reserve_covers_failover_timeout_default(): + assert WRAPPER_FAILOVER_RESERVE_SEC > WrapperProperties.FAILOVER_TIMEOUT_SEC.default_value + + +def test_attempt_state_is_shared_by_both_helper_copies(container_on_sys_path): + helper_copy = importlib.import_module("container.utils.rds_test_utility") + + assert helper_copy is not rds_test_utility + assert helper_copy.AttemptState is rds_test_utility.AttemptState + + +def test_failover_slow_marks_attempt_for_rerun(utility, clock): + target, _ = utility + _changes_writer_after(target, clock, SLOW_FAILOVER_SEC + 10) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert rds_test_utility.AttemptState.slow_failover_sec == SLOW_FAILOVER_SEC + 10 + + +def test_failover_normal_does_not_mark_attempt(utility, clock): + target, _ = utility + _changes_writer_after(target, clock, 30) + + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + + assert rds_test_utility.AttemptState.slow_failover_sec is None + + def test_get_recent_events_merges_sources_oldest_first(utility): target, _ = utility paginator = target._client.get_paginator.return_value @@ -565,6 +805,53 @@ def test_is_cluster_outage(error, after_failover, expected): assert rds_test_utility.RdsTestUtility.is_cluster_outage(error, after_failover) is expected +def test_rerun_after_slow_failover_for_any_failure(): + rds_test_utility.AttemptState.slow_failover_sec = SLOW_FAILOVER_SEC + 10 + + assert rds_test_utility.RdsTestUtility.is_rerun_cause(AssertionError("wrong writer"), True, False) is True + + +def test_rerun_without_slow_failover_needs_outage(): + assert rds_test_utility.RdsTestUtility.is_rerun_cause(AssertionError("wrong writer"), True, False) is False + + +def _deadline_failure(target, clock): + _never_changes_writer(target, clock) + with pytest.raises(pytest.fail.Exception, match="did not finish within") as excinfo: + target.failover_cluster_and_wait_until_writer_changed("instance-1", "cluster") + return excinfo.value + + +def test_rerun_without_slow_failover_for_outage(utility, clock): + target, _ = utility + error = _deadline_failure(target, clock) + + assert rds_test_utility.RdsTestUtility.is_rerun_cause(error, True, False) is True + + +def test_rerun_without_slow_failover_not_for_cut_connectivity(utility, clock): + target, _ = utility + error = _deadline_failure(target, clock) + + assert rds_test_utility.RdsTestUtility.is_rerun_cause(error, True, True) is False + + +def test_rerun_after_slow_failover_for_cut_connectivity(): + rds_test_utility.AttemptState.slow_failover_sec = SLOW_FAILOVER_SEC + 10 + + assert rds_test_utility.RdsTestUtility.is_rerun_cause(AssertionError(), True, True) is True + + +def test_attempt_state_reset_clears_slow_failover(): + rds_test_utility.AttemptState.deadline = _START_SEC + rds_test_utility.AttemptState.slow_failover_sec = SLOW_FAILOVER_SEC + 10 + + rds_test_utility.AttemptState.reset(None) + + assert rds_test_utility.AttemptState.slow_failover_sec is None + assert rds_test_utility.AttemptState.deadline is None + + def test_get_recent_events_stops_at_budget(utility, clock): target, _ = utility paginator = target._client.get_paginator.return_value @@ -735,3 +1022,29 @@ def test_make_sure_instances_up_retries_status_after_api_error(utility): assert target._client.describe_db_instances.call_count == 2 assert target._open_connection.call_count == 1 + + +def test_rds_client_with_api_retry_config_retries_throttling_adaptively(isolated_aws_env): + target = rds_test_utility.RdsTestUtility("us-east-2", config=rds_test_utility.RDS_API_RETRY_CONFIG) + + assert target._client.meta.config.retries == {"mode": "adaptive", "total_max_attempts": 13} + + +def test_rds_client_with_api_retry_config_times_out_each_attempt(isolated_aws_env): + target = rds_test_utility.RdsTestUtility("us-east-2", config=rds_test_utility.RDS_API_RETRY_CONFIG) + + assert target._client.meta.config.connect_timeout == 10 + assert target._client.meta.config.read_timeout == 10 + + +def test_rds_client_keeps_passed_retry_config(isolated_aws_env): + target = rds_test_utility.RdsTestUtility("us-east-2", config=Config(retries={"total_max_attempts": 1})) + + assert target._client.meta.config.retries["total_max_attempts"] == 1 + + +def test_rds_client_default_keeps_botocore_retry(isolated_aws_env): + target = rds_test_utility.RdsTestUtility("us-east-2") + + assert "total_max_attempts" not in target._client.meta.config.retries + assert target._client.meta.config.retries.get("mode") != "adaptive"