diff --git a/.github/workflows/blue_green_integration_tests.yml b/.github/workflows/blue_green_integration_tests.yml new file mode 100644 index 000000000..b8b0bc8d0 --- /dev/null +++ b/.github/workflows/blue_green_integration_tests.yml @@ -0,0 +1,77 @@ +name: Blue/Green Integration Tests + +on: + workflow_dispatch: + push: + branches: + - main + paths-ignore: + - '**/*.md' + - '**/*.jpg' + - '**/README.txt' + - '**/LICENSE.txt' + - 'docs/**' + - 'ISSUE_TEMPLATE/**' + - '**/remove-old-artifacts.yml' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +permissions: + id-token: write # This is required for requesting the JWT + contents: read # This is required for actions/checkout + +jobs: + blue-green-integration-tests: + name: Run Blue/Green Integration Tests + runs-on: ubuntu-latest + timeout-minutes: 120 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + task: [ "mysql-aurora-sync", "mysql-aurora-async", "pg-aurora-sync", "pg-aurora-async" ] + + steps: + - name: 'Clone repository' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + + - name: 'Set up JDK 8' + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 + with: + distribution: 'corretto' + java-version: 8 + + - name: Install poetry + shell: bash + run: | + pipx install poetry==1.8.2 + poetry config virtualenvs.prefer-active-python true + + - name: Install dependencies + run: poetry install + + - name: 'Configure AWS Credentials' + uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6 + with: + role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ secrets.AWS_DEPLOY_ROLE }} + role-session-name: python_bg_integration_tests + role-duration-seconds: 21600 + aws-region: ${{ secrets.AWS_DEFAULT_REGION }} + + - name: 'Run Blue/Green Integration Tests' + run: | + ./gradlew --no-parallel --no-daemon test-bgd-${{ matrix.task }} --info + env: + RDS_DB_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + MYSQL_VERSION: default + PG_VERSION: default + + - name: 'Archive Blue/Green results' + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: pytest-integration-report-bgd-${{ matrix.task }} + path: ./tests/integration/container/reports + retention-days: 5 diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index b1e53519a..7460cae37 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -961,7 +961,7 @@ async def _open_connection_task(self) -> None: ip_host_info = copy(host_info) ip_host_info.host = ip_address props_copy = copy(self._props) - WrapperProperties.IAM_HOST.set(props_copy, ip_host_info.host) + WrapperProperties.IAM_HOST.set(props_copy, host_info.host) logger.debug("BlueGreenStatusMonitor.OpeningConnectionWithIp", self._bg_role, ip_host_info.host) self._connection = await self._plugin_service.force_connect(ip_host_info, props_copy) diff --git a/aws_advanced_python_wrapper/blue_green_plugin.py b/aws_advanced_python_wrapper/blue_green_plugin.py index fb36b4aab..5fb8d7523 100644 --- a/aws_advanced_python_wrapper/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/blue_green_plugin.py @@ -953,7 +953,7 @@ def _open_connection_task(self): ip_host_info = copy(host_info) ip_host_info.host = ip_address props_copy = copy(self._props) - WrapperProperties.IAM_HOST.set(props_copy, ip_host_info.host) + WrapperProperties.IAM_HOST.set(props_copy, host_info.host) logger.debug( "BlueGreenStatusMonitor.OpeningConnectionWithIp", self._bg_role, ip_host_info.host) diff --git a/tests/integration/container/test_blue_green_deployment.py b/tests/integration/container/test_blue_green_deployment.py index aab38443b..96a307af8 100644 --- a/tests/integration/container/test_blue_green_deployment.py +++ b/tests/integration/container/test_blue_green_deployment.py @@ -14,7 +14,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Deque, Dict, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Deque, Dict, List, Optional, Set, Tuple import mysql.connector import psycopg @@ -31,6 +31,7 @@ import socket from collections import deque from dataclasses import dataclass, field +from logging import INFO, getLogger from threading import Event, Thread from time import perf_counter_ns, sleep @@ -38,10 +39,14 @@ from tabulate import tabulate # type: ignore[import-untyped] from aws_advanced_python_wrapper import AwsWrapperConnection -from aws_advanced_python_wrapper.blue_green_plugin import (BlueGreenPlugin, - BlueGreenRole) +from aws_advanced_python_wrapper.blue_green_plugin import (BlueGreenPhase, + BlueGreenPlugin, + BlueGreenRole, + BlueGreenStatus) from aws_advanced_python_wrapper.database_dialect import DialectCode from aws_advanced_python_wrapper.driver_info import DriverInfo +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.atomic import AtomicInt from aws_advanced_python_wrapper.utils.concurrent import (ConcurrentDict, CountDownLatch) @@ -49,13 +54,24 @@ from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils +from .utils.blue_green_checks import (PhaseObserver, ProbeResult, + SwitchoverRequest, settle_switchover, + suspended_call_failures, + wait_for_switchover) from .utils.conditions import enable_on_deployments, enable_on_features from .utils.database_engine import DatabaseEngine from .utils.database_engine_deployment import DatabaseEngineDeployment from .utils.driver_helper import DriverHelper 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 (BG_PLUGIN_STATUS_POLL_SEC, + BG_PROBE_CONNECT_ATTEMPTS, + BG_PROBE_CONNECT_TIMEOUT_SEC, + BG_PROBE_HOST_ROLE_WAIT_SEC, + BG_SWITCHOVER_PYTEST_TIMEOUT_SEC, + BG_THREAD_JOIN_SEC, BG_WAIT_STEP_SEC) @enable_on_deployments([DatabaseEngineDeployment.AURORA, DatabaseEngineDeployment.RDS_MULTI_AZ_INSTANCE]) @@ -75,6 +91,11 @@ class TestBlueGreenDeployment: PG_RDS_BG_STATUS_QUERY = \ (f"SELECT id, SPLIT_PART(endpoint, '.', 1) as hostId, endpoint, port, role, status, version " f"FROM rds_tools.show_topology('aws_advanced_python_wrapper-{DriverInfo.DRIVER_VERSION}')") + # The server's own host name or address, which the switchover's renames don't change. + MYSQL_SERVER_ID_QUERY = "SELECT @@hostname" + PG_SERVER_ID_QUERY = "SELECT pg_catalog.inet_server_addr()" + # The connect params set no bg_id, so the plugin keys its status by the default, normalized as the plugin does. + PLUGIN_BG_ID = str(WrapperProperties.BG_ID.default_value).strip().lower() results: ConcurrentDict[str, BlueGreenResults] = ConcurrentDict() unhandled_exceptions: Deque[Exception] = deque() mysql_dialect = MySQLDriverDialect(Properties()) @@ -88,6 +109,7 @@ def test_utility(self): def rds_utils(self): return RdsUtils() + @pytest.mark.timeout(BG_SWITCHOVER_PYTEST_TIMEOUT_SEC) def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: TestEnvironment, test_driver): self.results.clear() self.unhandled_exceptions.clear() @@ -109,6 +131,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: test_environment, test_utility, rds_utils, info.get_bg_deployment_id()) topology_instances_str = '\n'.join(topology_instances) self.logger.debug(f"topology_instances: \n{topology_instances_str}") + green_hosts: List[str] = [] for host in topology_instances: host_id = host[0:host.index(".")] @@ -119,6 +142,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: if rds_utils.is_not_green_or_old_instance(host): threads.append(Thread( + daemon=True, target=self.direct_topology_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -126,6 +150,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.direct_blue_connectivity_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -133,6 +158,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.direct_blue_idle_connectivity_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -140,6 +166,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_blue_idle_connectivity_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -147,6 +174,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_blue_executing_connectivity_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -154,6 +182,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_blue_new_connection_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -161,13 +190,17 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.blue_dns_monitor, args=(host_id, host, start_latch, stop, finish_latch, bg_results))) thread_count += 1 thread_finish_count += 1 if rds_utils.is_green_instance(host): + green_hosts.append(host) + threads.append(Thread( + daemon=True, target=self.direct_topology_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -175,6 +208,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_green_connectivity_monitor, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -182,6 +216,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.green_dns_monitor, args=(host_id, host, start_latch, stop, finish_latch, bg_results))) thread_count += 1 @@ -191,6 +226,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: rds_client = test_utility.get_rds_client() threads.append(Thread( + daemon=True, target=self.green_iam_connectivity_monitor, args=(test_driver, conn_utils, rds_client, host_id, "BlueHostToken", rds_utils.remove_green_instance_prefix(host), host, test_instance.get_port(), @@ -200,6 +236,7 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.green_iam_connectivity_monitor, args=(test_driver, conn_utils, rds_client, host_id, "GreenHostToken", host, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, @@ -208,44 +245,132 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: thread_count += 1 thread_finish_count += 1 - threads.append(Thread( + assert len(green_hosts) > 0, "Unable to find a green instance in the Blue/Green topology." + green_host = green_hosts[0] + + port = test_instance.get_port() + if test_environment.get_deployment() == DatabaseEngineDeployment.AURORA: + blue_endpoint = test_environment.get_database_info().get_cluster_endpoint() + else: + blue_endpoint = test_instance.get_host() + + # conftest released the services container and its lazy re-initialisation isn't locked: build it here, + # before the threads' first connects race on it. + services_container.get_monitor_service() + blue_server_ids = self.get_server_ids( + test_driver, conn_utils, [instance.get_host() for instance in test_environment.get_instances()], port, + db_name) + green_server_ids = self.get_server_ids(test_driver, conn_utils, green_hosts, port, db_name) + self.logger.debug(f"Blue servers: {blue_server_ids}, green servers: {green_server_ids}") + assert len(blue_server_ids) > 0 + assert len(green_server_ids) > 0 + assert blue_server_ids.isdisjoint(green_server_ids) + assert "None" not in blue_server_ids | green_server_ids + probe_host = self.get_probe_host(test_driver, conn_utils, blue_endpoint, test_instance.get_host(), port, db_name) + self.logger.debug(f"Probe host: {probe_host}") + + request = SwitchoverRequest() + trigger_thread = Thread( + daemon=True, + name="BlueGreenSwitchoverTrigger", target=self.bg_switchover_trigger, - args=(test_utility, info.get_bg_deployment_id(), start_latch, finish_latch, self.results))) + args=(test_utility, info.get_bg_deployment_id(), start_latch, finish_latch, self.results, stop, request)) + threads.append(trigger_thread) thread_count += 1 thread_finish_count += 1 + # The observer and the probes don't count down start_latch: each probe starts on the plugin phase it needs. + observer = PhaseObserver() + execute_probe = ProbeResult() + connect_probe = ProbeResult() + routing_probe = ProbeResult() + execute_thread = Thread( + daemon=True, + name="BlueGreenExecuteProbe", + target=self.wrapper_blue_suspended_execute_probe, + args=(test_driver, conn_utils, probe_host, port, db_name, observer, stop, finish_latch, execute_probe)) + connect_thread = Thread( + daemon=True, + name="BlueGreenConnectProbe", + target=self.wrapper_green_suspended_connect_probe, + args=(test_driver, conn_utils, green_host, port, db_name, observer, stop, finish_latch, connect_probe)) + routing_thread = Thread( + daemon=True, + name="BlueGreenRoutingProbe", + target=self.wrapper_blue_routing_probe, + args=(test_driver, conn_utils, probe_host, port, db_name, observer, stop, finish_latch, routing_probe)) + threads.append(Thread( + daemon=True, + name="BlueGreenPhaseObserver", + target=self.plugin_status_monitor, + args=(observer, stop, finish_latch))) + threads.extend([execute_thread, connect_thread, routing_thread]) + thread_finish_count += 4 + start_latch.set_count(thread_count) finish_latch.set_count(thread_finish_count) for result in self.results.values(): result.start_time_ns.set(start_time_ns) - for thread in threads: - thread.start() - - self.logger.debug("All threads started.") - - finish_latch.wait_sec(6 * 60) - self.logger.debug("All threads completed.") - - sleep(12 * 60) - - self.logger.debug("Stopping all threads...") - stop.set() - - for thread in threads: - thread.join(timeout=30) - if thread.is_alive(): - self.logger.debug("Timed out waiting for a thread to stop running...") - - self.logger.debug("Done waiting for threads to stop.") + # A suspended call logs at DEBUG on each pass of its wait. One that never returns floods the report until the + # harness can't keep up, so the plugin stays at INFO while any test thread is alive. + plugin_logger = getLogger(BlueGreenPlugin.__module__) + plugin_log_level = plugin_logger.level + plugin_logger.setLevel(INFO) + try: + threads_start_ns = perf_counter_ns() + for thread in threads: + thread.start() + + self.logger.debug("All threads started.") + wait_result = wait_for_switchover( + request, threads_start_ns, + [(execute_thread, execute_probe), (connect_thread, connect_probe), (routing_thread, routing_probe)], + lambda: observer.is_seen(BlueGreenPhase.COMPLETED) or self.is_switchover_completed_seen()) + self.logger.debug(f"Done waiting for the switchover: {wait_result}.") + finally: + api_status = settle_switchover(test_utility, info.get_bg_deployment_id(), trigger_thread, stop, request) + self.logger.debug("Stop set for all threads.") + finish_latch.wait_sec(BG_THREAD_JOIN_SEC) + alive_count = sum(1 for thread in threads if thread.is_alive()) + self.logger.debug(f"Done waiting for threads to stop, {alive_count} still running.") + if alive_count == 0: + plugin_logger.setLevel(plugin_log_level) + + self.logger.debug( + f"Blue/Green deployment status: {api_status}. Plugin phases first seen: {observer.first_seen_ns}. " + f"Execute probe: {execute_probe}. Connect probe to {green_host}: {connect_probe}. " + f"Routing probe to {probe_host}: {routing_probe}.") + + assert request.error is None, f"The switchover request failed: {request.error}" + assert api_status == "SWITCHOVER_COMPLETED", \ + f"The Blue/Green deployment status was {api_status} when the test stopped waiting: {wait_result}." for host_id, result in self.results.items(): assert result.bg_trigger_time_ns.get() > 0, \ f"bg_trigger_time for {host_id} was {result.bg_trigger_time_ns.get()}" self.logger.debug("Test is over.") + now_ns = perf_counter_ns() + failures: List[str] = [] + if observer.is_seen(BlueGreenPhase.IN_PROGRESS): + failures.extend(suspended_call_failures("execute", execute_probe, now_ns, check_held=True, check_cpu=True)) + failures.extend(suspended_call_failures("connect", connect_probe, now_ns, check_held=False, check_cpu=True)) + else: + failures.append("The plugin phase IN_PROGRESS was never seen, so the execute and connect probes didn't run.") + + if not observer.is_seen(BlueGreenPhase.POST): + failures.append("The plugin phase POST was never seen, so the routing probe didn't run.") + elif routing_probe.driver_host is None or routing_probe.server_id is None: + failures.append(f"No connection opened in POST to the blue endpoint succeeded ({routing_probe.error}).") + elif routing_probe.driver_host.lower() == probe_host.lower(): + failures.append(f"A connection opened in POST went to the dialled host, not a substitute ({probe_host}).") + elif routing_probe.server_id not in green_server_ids: + failures.append(f"A connection opened in POST reached a server that isn't green ({routing_probe.server_id}).") + self.print_metrics(rds_utils) + assert not failures, "\n".join(failures) if len(self.unhandled_exceptions) > 0: self.log_unhandled_exceptions() @@ -255,6 +380,62 @@ def test_switchover(self, conn_utils, test_utility, rds_utils, test_environment: self.logger.debug("Completed") + def is_switchover_completed_seen(self) -> bool: + return any(result.green_status_time.get("SWITCHOVER_COMPLETED", 0) for result in self.results.values()) + + def get_server_ids( + self, test_driver: TestDriver, conn_utils: ConnectionUtils, hosts: List[str], port: int, db: str) -> Set[str]: + server_ids = set() + for host in hosts: + conn = self.get_direct_connection_with_retry( + test_driver, **conn_utils.get_connect_params(host=host, port=port, dbname=db)) + try: + server_ids.add(self.query_server_id(conn)) + finally: + self.close_connection(conn) + return server_ids + + def query_server_id(self, conn: Connection) -> str: + if TestEnvironment.get_current().get_engine() == DatabaseEngine.MYSQL: + query = self.MYSQL_SERVER_ID_QUERY + else: + query = self.PG_SERVER_ID_QUERY + with conn.cursor() as cursor: + cursor.execute(query) + return str(cursor.fetchall()[0][0]) + + def get_driver_host(self, conn: AwsWrapperConnection) -> str: + """The host the target driver connected to: the dialled name, or the substitute the plugin chose.""" + target = conn.target_connection + if TestEnvironment.get_current().get_engine() == DatabaseEngine.MYSQL: + return str(target.server_host) + return str(target.info.host) + + def get_probe_host( + self, + test_driver: TestDriver, + conn_utils: ConnectionUtils, + blue_endpoint: str, + writer_host: str, + port: int, + db: str) -> str: + """The blue endpoint once the plugin gives it its SOURCE role, else the writer instance. + + The first wrapper connection starts the plugin's status monitors. It connects to the writer instance, as the + monitor threads' connections do. + """ + conn = self.get_wrapper_connection_with_retry( + test_driver, **self.get_wrapper_connect_params(conn_utils, writer_host, port, db)) + try: + has_source_role = retry_until( + lambda: self.get_plugin_role(blue_endpoint) == BlueGreenRole.SOURCE, + BG_PROBE_HOST_ROLE_WAIT_SEC, BG_WAIT_STEP_SEC) + finally: + self.close_connection(conn) + if has_source_role: + return blue_endpoint + return writer_host + def get_bg_endpoints( self, test_env: TestEnvironment, @@ -348,10 +529,12 @@ def direct_topology_monitor( else: pytest.fail(f"Unsupported database engine: {engine}") + # Each poll must read the status table as it is now: without autocommit, MySQL's REPEATABLE READ + # repeats the first read's snapshot (the plugin sets autocommit on its status connections for this reason). + connect_params = {**conn_utils.get_connect_params(host=host, port=port, dbname=db), "autocommit": True} + try: - conn = self.get_direct_connection_with_retry( - test_driver, - **conn_utils.get_connect_params(host=host, port=port, dbname=db)) + conn = self.get_direct_connection_with_retry(test_driver, **connect_params) self.logger.debug(f"[DirectTopology] @ {host_id}] Connection opened.") sleep(1) @@ -366,8 +549,7 @@ def direct_topology_monitor( end_time_ns = perf_counter_ns() + 15 * 60 * 1_000_000_000 # 15 minutes while not stop.is_set() and perf_counter_ns() < end_time_ns: if conn is None: - conn = self.get_direct_connection_with_retry( - test_driver, **conn_utils.get_connect_params(host=host, port=port, dbname=db)) + conn = self.get_direct_connection_with_retry(test_driver, **connect_params) self.logger.debug(f"[DirectTopology] @ {host_id}] Connection re-opened.") try: @@ -787,6 +969,167 @@ def wrapper_blue_new_connection_monitor( finish_latch.count_down() self.logger.debug(f"[WrapperBlueNewConnection @ {host_id}] Thread is completed.") + # Plugin status + # Records the first time each phase is published. The sync status storage is process-wide. + # Needs a stop signal to terminate + def plugin_status_monitor(self, observer: PhaseObserver, stop: Event, finish_latch: CountDownLatch) -> None: + try: + while not stop.is_set(): + observer.record(self.read_plugin_status()) + sleep(BG_PLUGIN_STATUS_POLL_SEC) + except Exception as e: + self.logger.debug(f"[PluginStatus] Thread unhandled exception: {e}") + self.unhandled_exceptions.append(e) + finally: + finish_latch.count_down() + self.logger.debug("[PluginStatus] Thread is completed.") + + def read_plugin_status(self) -> Optional[BlueGreenStatus]: + return services_container.get_storage_service().get( + BlueGreenStatus, self.PLUGIN_BG_ID, register_data_access=False) + + def read_plugin_phase(self) -> Optional[str]: + status = self.read_plugin_status() + if status is None: + return None + return status.phase.name + + def get_plugin_role(self, host: str) -> Optional[BlueGreenRole]: + status = self.read_plugin_status() + if status is None: + return None + return status.get_role(HostInfo(host=host)) + + # Blue host + # Check: an execute started in IN_PROGRESS on a connection opened before it + # Expect: the plugin holds the execute until the phase moves on, without a busy loop + # Can terminate for itself + def wrapper_blue_suspended_execute_probe( + self, + test_driver: TestDriver, + conn_utils: ConnectionUtils, + host: str, + port: int, + db: str, + observer: PhaseObserver, + stop: Event, + finish_latch: CountDownLatch, + result: ProbeResult) -> None: + conn = None + try: + conn = self.get_wrapper_connection_with_retry( + test_driver, **self.get_wrapper_connect_params(conn_utils, host, port, db)) + # cursor() goes through the plugin, so a cursor opened in IN_PROGRESS would be held as well. + with conn.cursor() as cursor: + if not observer.wait_for(BlueGreenPhase.IN_PROGRESS, stop): + return + + result.phase_at_start = self.read_plugin_phase() + error: Optional[Exception] = None + result.begin() + try: + cursor.execute("SELECT 1") + except Exception as e: + error = e + result.end(error, self.read_plugin_phase()) + if error is None: + cursor.fetchall() + except Exception as e: + self.logger.debug(f"[WrapperBlueSuspendedExecute @ {host}] Thread exception: {e}") + finally: + self.close_connection(conn) + finish_latch.count_down() + self.logger.debug(f"[WrapperBlueSuspendedExecute @ {host}] Thread is completed.") + + # Green host + # Check: a new connection opened in IN_PROGRESS + # Expect: the plugin holds the connect until the phase moves on, without a busy loop + # Can terminate for itself + def wrapper_green_suspended_connect_probe( + self, + test_driver: TestDriver, + conn_utils: ConnectionUtils, + host: str, + port: int, + db: str, + observer: PhaseObserver, + stop: Event, + finish_latch: CountDownLatch, + result: ProbeResult) -> None: + conn = None + try: + params = self.get_wrapper_connect_params(conn_utils, host, port, db) + params[WrapperProperties.CONNECT_TIMEOUT_SEC.name] = BG_PROBE_CONNECT_TIMEOUT_SEC + target_driver_connect = DriverHelper.get_connect_func(test_driver) + if not observer.wait_for(BlueGreenPhase.IN_PROGRESS, stop): + return + + result.phase_at_start = self.read_plugin_phase() + error: Optional[Exception] = None + result.begin() + try: + conn = AwsWrapperConnection.connect(target_driver_connect, **params) + except Exception as e: + error = e + result.end(error, self.read_plugin_phase()) + except Exception as e: + self.logger.debug(f"[WrapperGreenSuspendedConnect @ {host}] Thread exception: {e}") + finally: + self.close_connection(conn) + finish_latch.count_down() + self.logger.debug(f"[WrapperGreenSuspendedConnect @ {host}] Thread is completed.") + + # Blue host + # Check: a new connection opened in POST, the host the driver dialled and the server it reaches + # Expect: the plugin substitutes a green host, so the connection reaches a green server + # Can terminate for itself + def wrapper_blue_routing_probe( + self, + test_driver: TestDriver, + conn_utils: ConnectionUtils, + host: str, + port: int, + db: str, + observer: PhaseObserver, + stop: Event, + finish_latch: CountDownLatch, + result: ProbeResult) -> None: + try: + params = self.get_wrapper_connect_params(conn_utils, host, port, db) + params[WrapperProperties.CONNECT_TIMEOUT_SEC.name] = BG_PROBE_CONNECT_TIMEOUT_SEC + target_driver_connect = DriverHelper.get_connect_func(test_driver) + if not observer.wait_for(BlueGreenPhase.POST, stop): + return + + # The first attempt that connects decides. Retry a connect error only while the plugin is still in POST. + for _ in range(BG_PROBE_CONNECT_ATTEMPTS): + result.phase_at_start = self.read_plugin_phase() + if result.phase_at_start != BlueGreenPhase.POST.name: + return + + conn = None + try: + conn = AwsWrapperConnection.connect(target_driver_connect, **params) + result.driver_host = self.get_driver_host(conn) + result.server_id = self.query_server_id(conn) + return + except Exception as e: + result.error = e + self.logger.debug(f"[WrapperBlueRouting @ {host}] Connect exception: {e}") + finally: + self.close_connection(conn) + sleep(BG_WAIT_STEP_SEC) + except Exception as e: + self.logger.debug(f"[WrapperBlueRouting @ {host}] Thread exception: {e}") + finally: + finish_latch.count_down() + self.logger.debug(f"[WrapperBlueRouting @ {host}] Thread is completed.") + + def is_authentication_failure(self, exception: Exception) -> bool: + # MySQL rejects an IAM token with "Access denied", PostgreSQL with "PAM authentication failed". + error_message = str(exception).lower() + return "access denied" in error_message or "pam authentication failed" in error_message + def is_timeout_exception(self, exception: Exception) -> bool: error_message = str(exception).lower() timeout_keywords = [ @@ -1027,12 +1370,11 @@ def green_iam_connectivity_monitor( else: self.logger.debug(f"[DirectGreenIamIp{thread_prefix} @ {host_id}] Thread exception: {e}") result_queue.append(TimeHolder(start_ns, perf_counter_ns(), error=str(e))) - # TODO: confirm 'Access Denied' is the error message surfaced in Python. - if notify_on_first_error and "access denied" in str(e).lower(): + if notify_on_first_error and self.is_authentication_failure(e): results.green_node_changed_name_time_ns.compare_and_set(0, perf_counter_ns()) self.logger.debug( f"[DirectGreenIamIp{thread_prefix} @ {host_id}] " - f"Encountered first 'Access denied' exception. Exiting thread...") + f"Encountered the first authentication failure. Exiting thread...") return self.close_connection(conn) @@ -1055,7 +1397,9 @@ def bg_switchover_trigger( bg_id: str, start_latch: CountDownLatch, finish_latch: CountDownLatch, - results: Dict[str, BlueGreenResults]): + results: Dict[str, BlueGreenResults], + stop: Event, + request: SwitchoverRequest): try: start_latch.count_down() @@ -1067,7 +1411,17 @@ def bg_switchover_trigger( result.threads_sync_time.set(sync_time_ns) sleep(30) - test_utility.switchover_blue_green_deployment(bg_id) + # The main thread sets stop when it gives up waiting for the request, and then waits for the RDS API only + # if the request is marked, so the check and the mark stay together. + if stop.is_set(): + return + request.requested_ns = perf_counter_ns() + request.requested.set() + try: + test_utility.switchover_blue_green_deployment(bg_id) + except Exception as e: + request.error = e + raise bg_trigger_time_ns = perf_counter_ns() for result in results.values(): @@ -1207,19 +1561,21 @@ def print_node_status_times(self, node: str, results: BlueGreenResults, time_zer self.logger.debug(f"\n{node}:\n{tabulate(table, headers=headers)}") def print_duration_times(self, node: str, title: str, times: Deque[TimeHolder], time_zero_ns: int): + # A monitor thread that hasn't stopped yet can still append to the deque. + samples = list(times) table = [] headers = ["Connect at (ms)", "Connect time/duration (ms)", "Error"] - p99_ns = self.get_percentile([time.end_time_ns - time.start_time_ns for time in times], 99.0) + p99_ns = self.get_percentile([time.end_time_ns - time.start_time_ns for time in samples], 99.0) p99_ms = p99_ns // 1_000_000 table.append(["p99", p99_ms, ""]) - first_connect = times[0] + first_connect = samples[0] table.append([ (first_connect.start_time_ns - time_zero_ns) // 1_000_000, (first_connect.end_time_ns - first_connect.start_time_ns) // 1_000_000, self.get_formatted_error(first_connect.error) ]) - for time_holder in times: + for time_holder in samples: duration_ms = (time_holder.end_time_ns - time_holder.start_time_ns) // 1_000_000 if duration_ms > p99_ms: table.append([ @@ -1228,7 +1584,7 @@ def print_duration_times(self, node: str, title: str, times: Deque[TimeHolder], self.get_formatted_error(time_holder.error) ]) - last_connect = times[-1] + last_connect = samples[-1] table.append([ (last_connect.start_time_ns - time_zero_ns) // 1_000_000, (last_connect.end_time_ns - last_connect.start_time_ns) // 1_000_000, @@ -1276,8 +1632,6 @@ def assert_test(self): # Assertions assert switchover_complete_time_ms != 0, "BG switchover hasn't completed." - assert switchover_complete_time_ms >= max_green_node_changed_name_time_ms, \ - "Green node changed name after SWITCHOVER_COMPLETED." @dataclass diff --git a/tests/integration/container/test_blue_green_deployment_async.py b/tests/integration/container/test_blue_green_deployment_async.py index 6ec996d8d..38902efda 100644 --- a/tests/integration/container/test_blue_green_deployment_async.py +++ b/tests/integration/container/test_blue_green_deployment_async.py @@ -35,7 +35,7 @@ - ``conn.close()`` → ``await conn.close()``. - ``is_closed`` for psycopg AsyncConnection uses the sync ``.closed`` property; for aiomysql uses ``not .open``. See ``_is_conn_closed_async``. -- ``conn._unwrap(BlueGreenPlugin)`` → ``_unwrap_plugin_async(conn, BlueGreenPlugin)`` +- ``conn._unwrap(BlueGreenPlugin)`` → ``_unwrap_plugin_async(conn, AsyncBlueGreenPlugin)`` (searches ``conn._plugin_manager._plugins`` directly because ``AsyncAwsWrapperConnection`` does not expose ``_unwrap``). - ``DriverHelper.get_connect_func`` returns the async connect callable for @@ -43,8 +43,8 @@ - boto3 RDS Blue/Green switchover/wait calls stay synchronous. - ``sleep()`` calls inside threads remain synchronous (OS threads; no event loop blocked). -- Every thread teardown invokes ``cleanup_async()`` on its own loop so - wrapper background tasks are released cleanly. +- The main thread invokes ``cleanup_async()`` once, after the worker threads + stop, so no worker releases wrapper services the others still use. """ from __future__ import annotations @@ -54,6 +54,7 @@ import socket from collections import deque from dataclasses import dataclass, field +from logging import INFO, getLogger from threading import Event, Thread from time import perf_counter_ns, sleep from typing import (TYPE_CHECKING, Any, Callable, Deque, Dict, List, Optional, @@ -63,11 +64,17 @@ import pytest from tabulate import tabulate # type: ignore[import-untyped] -from aws_advanced_python_wrapper.aio.wrapper import AsyncAwsWrapperConnection -from aws_advanced_python_wrapper.blue_green_plugin import (BlueGreenPlugin, +from aws_advanced_python_wrapper.aio.blue_green_plugin import \ + AsyncBlueGreenPlugin +from aws_advanced_python_wrapper.aio.blue_green_plugin import \ + BlueGreenStatus as AsyncBlueGreenStatus +from aws_advanced_python_wrapper.aio.wrapper import (AsyncAwsWrapperConnection, + AsyncAwsWrapperCursor) +from aws_advanced_python_wrapper.blue_green_plugin import (BlueGreenPhase, BlueGreenRole) from aws_advanced_python_wrapper.database_dialect import DialectCode from aws_advanced_python_wrapper.driver_info import DriverInfo +from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.atomic import AtomicInt from aws_advanced_python_wrapper.utils.concurrent import (ConcurrentDict, CountDownLatch) @@ -76,6 +83,9 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from tests.integration.container.utils.async_connection_helpers import \ cleanup_async +from tests.integration.container.utils.blue_green_checks import ( + PhaseObserver, ProbeResult, SwitchoverRequest, settle_switchover, + suspended_call_failures, wait_for_switchover) from tests.integration.container.utils.conditions import ( enable_on_deployments, enable_on_features) from tests.integration.container.utils.database_engine import DatabaseEngine @@ -86,6 +96,10 @@ from tests.integration.container.utils.test_environment import TestEnvironment from tests.integration.container.utils.test_environment_features import \ TestEnvironmentFeatures +from tests.integration.container.utils.test_timings import ( + BG_ASYNC_EXECUTE_TIMEOUT_SEC, BG_ASYNC_PROBE_CONNECT_WAIT_SEC, + BG_PLUGIN_STATUS_POLL_SEC, BG_PROBE_CONNECT_ATTEMPTS, + BG_SWITCHOVER_PYTEST_TIMEOUT_SEC, BG_THREAD_JOIN_SEC) if TYPE_CHECKING: from tests.integration.container.utils.connection_utils import \ @@ -177,20 +191,14 @@ def _run_worker_with_loop( hangs. This helper encapsulates the correct shape: one loop per thread for - the thread's entire lifetime, with ``cleanup_async()`` always invoked - on that same loop in ``finally`` so wrapper background tasks are - released even if the body raises. + the thread's entire lifetime. It does not invoke ``cleanup_async()``: + that releases process-wide services, so the main thread invokes it + once, after every worker stopped. """ loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: - try: - body(loop) - finally: - try: - loop.run_until_complete(cleanup_async()) - except Exception: - pass + body(loop) finally: loop.close() @@ -261,6 +269,7 @@ def test_utility(self): def rds_utils(self): return RdsUtils() + @pytest.mark.timeout(BG_SWITCHOVER_PYTEST_TIMEOUT_SEC) def test_switchover_async( self, conn_utils: ConnectionUtils, test_utility: RdsTestUtility, rds_utils: RdsUtils, test_environment: TestEnvironment, @@ -295,6 +304,7 @@ def test_switchover_async( if rds_utils.is_not_green_or_old_instance(host): threads.append(Thread( + daemon=True, target=self.direct_topology_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -302,6 +312,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.direct_blue_connectivity_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -309,6 +320,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.direct_blue_idle_connectivity_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -316,6 +328,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_blue_idle_connectivity_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -323,6 +336,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_blue_executing_connectivity_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -330,6 +344,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_blue_new_connection_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -337,6 +352,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.blue_dns_monitor, args=(host_id, host, start_latch, stop, finish_latch, bg_results))) thread_count += 1 @@ -344,6 +360,7 @@ def test_switchover_async( if rds_utils.is_green_instance(host): threads.append(Thread( + daemon=True, target=self.direct_topology_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -351,6 +368,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.wrapper_green_connectivity_monitor_async, args=(test_driver, conn_utils, host_id, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, bg_results))) @@ -358,6 +376,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.green_dns_monitor, args=(host_id, host, start_latch, stop, finish_latch, bg_results))) thread_count += 1 @@ -367,6 +386,7 @@ def test_switchover_async( rds_client = test_utility.get_rds_client() threads.append(Thread( + daemon=True, target=self.green_iam_connectivity_monitor_async, args=(test_driver, conn_utils, rds_client, host_id, "BlueHostToken", rds_utils.remove_green_instance_prefix(host), host, test_instance.get_port(), @@ -376,6 +396,7 @@ def test_switchover_async( thread_finish_count += 1 threads.append(Thread( + daemon=True, target=self.green_iam_connectivity_monitor_async, args=(test_driver, conn_utils, rds_client, host_id, "GreenHostToken", host, host, test_instance.get_port(), db_name, start_latch, stop, finish_latch, @@ -384,52 +405,114 @@ def test_switchover_async( thread_count += 1 thread_finish_count += 1 - threads.append(Thread( + request = SwitchoverRequest() + trigger_thread = Thread( + daemon=True, + name="BlueGreenSwitchoverTrigger", target=self.bg_switchover_trigger, - args=(test_utility, info.get_bg_deployment_id(), start_latch, finish_latch, self.results))) + args=(test_utility, info.get_bg_deployment_id(), start_latch, finish_latch, self.results, stop, request)) + threads.append(trigger_thread) thread_count += 1 thread_finish_count += 1 + # Each AsyncAwsWrapperConnection keeps its own Blue/Green status store, so only the connection that owns the + # status provider sees the phases: the probe connects before the other threads start and is also the observer. + if test_environment.get_deployment() == DatabaseEngineDeployment.AURORA: + blue_endpoint = test_environment.get_database_info().get_cluster_endpoint() + else: + blue_endpoint = test_instance.get_host() + observer = PhaseObserver() + execute_probe = ProbeResult() + probe_connected = Event() + probe_thread = Thread( + daemon=True, + name="BlueGreenAsyncExecuteProbe", + target=self.wrapper_blue_suspended_execute_probe_async, + args=(test_driver, conn_utils, blue_endpoint, test_instance.get_port(), db_name, observer, stop, + finish_latch, probe_connected, execute_probe)) + thread_finish_count += 1 + start_latch.set_count(thread_count) finish_latch.set_count(thread_finish_count) for result in self.results.values(): result.start_time_ns.set(start_time_ns) - for thread in threads: - thread.start() + # A suspended call logs at DEBUG on each pass of its wait. One that never returns floods the report until the + # harness can't keep up, so the plugin stays at INFO while any test thread is alive. + plugin_logger = getLogger(AsyncBlueGreenPlugin.__module__) + plugin_log_level = plugin_logger.level + plugin_logger.setLevel(INFO) + # conftest released the services container and its lazy re-initialisation isn't locked: build it here, + # before the threads' first connects race on it. + services_container.get_monitor_service() + probe_thread.start() + if not probe_connected.wait(BG_ASYNC_PROBE_CONNECT_WAIT_SEC): + stop.set() + pytest.fail( + f"The async execute probe didn't connect to {blue_endpoint} within " + f"{BG_ASYNC_PROBE_CONNECT_WAIT_SEC:.0f} s.") - self.logger.debug("All threads started.") - - finish_latch.wait_sec(6 * 60) - self.logger.debug("All threads completed.") - - sleep(12 * 60) - - self.logger.debug("Stopping all threads...") - stop.set() - - for thread in threads: - thread.join(timeout=30) - if thread.is_alive(): - self.logger.debug("Timed out waiting for a thread to stop running...") + try: + threads_start_ns = perf_counter_ns() + for thread in threads: + thread.start() + + self.logger.debug("All threads started.") + wait_result = wait_for_switchover( + request, threads_start_ns, [(probe_thread, execute_probe)], + lambda: observer.is_seen(BlueGreenPhase.COMPLETED) or self.is_switchover_completed_seen()) + self.logger.debug(f"Done waiting for the switchover: {wait_result}.") + finally: + api_status = settle_switchover(test_utility, info.get_bg_deployment_id(), trigger_thread, stop, request) + self.logger.debug("Stop set for all threads.") + finish_latch.wait_sec(BG_THREAD_JOIN_SEC) + threads.append(probe_thread) + alive_count = sum(1 for thread in threads if thread.is_alive()) + self.logger.debug(f"Done waiting for threads to stop, {alive_count} still running.") + if alive_count == 0: + plugin_logger.setLevel(plugin_log_level) - self.logger.debug("Done waiting for threads to stop.") + try: + self.logger.debug( + f"Blue/Green deployment status: {api_status}. Plugin phases first seen: {observer.first_seen_ns}. " + f"Execute probe on {blue_endpoint}: {execute_probe}.") + + assert request.error is None, f"The switchover request failed: {request.error}" + assert api_status == "SWITCHOVER_COMPLETED", \ + f"The Blue/Green deployment status was {api_status} when the test stopped waiting: {wait_result}." + + for host_id, result in self.results.items(): + assert result.bg_trigger_time_ns.get() > 0, \ + f"bg_trigger_time for {host_id} was {result.bg_trigger_time_ns.get()}" + + self.logger.debug("Test is over.") + failures: List[str] = [] + if observer.is_seen(BlueGreenPhase.IN_PROGRESS): + failures.extend(suspended_call_failures( + "async execute", execute_probe, perf_counter_ns(), check_held=True, check_cpu=False)) + else: + failures.append("The plugin phase IN_PROGRESS was never seen, so the execute probe didn't run.") - for host_id, result in self.results.items(): - assert result.bg_trigger_time_ns.get() > 0, \ - f"bg_trigger_time for {host_id} was {result.bg_trigger_time_ns.get()}" + self.print_metrics(rds_utils) + assert not failures, "\n".join(failures) - self.logger.debug("Test is over.") - self.print_metrics(rds_utils) + if len(self.unhandled_exceptions) > 0: + self.log_unhandled_exceptions() + pytest.fail("There were unhandled exceptions.") - if len(self.unhandled_exceptions) > 0: - self.log_unhandled_exceptions() - pytest.fail("There were unhandled exceptions.") + self.assert_test() - self.assert_test() + self.logger.debug("Completed") + finally: + # Released once, after the workers stopped: a release in a worker stops the services the others still use. + try: + asyncio.run(cleanup_async()) + except Exception as e: + self.logger.debug(f"cleanup_async failed: {e}") - self.logger.debug("Completed") + def is_switchover_completed_seen(self) -> bool: + return any(result.green_status_time.get("SWITCHOVER_COMPLETED", 0) for result in self.results.values()) def get_bg_endpoints( self, @@ -595,6 +678,11 @@ def get_wrapper_connect_params( return params + def is_authentication_failure(self, exception: Exception) -> bool: + # MySQL rejects an IAM token with "Access denied", PostgreSQL with "PAM authentication failed". + error_message = str(exception).lower() + return "access denied" in error_message or "pam authentication failed" in error_message + def is_timeout_exception(self, exception: Exception) -> bool: error_message = str(exception).lower() timeout_keywords = [ @@ -668,11 +756,14 @@ def _log_and_return_time(_: Any) -> int: else: results.blue_status_time.compute_if_absent(status, _log_and_return_time) + # Each poll must read the status table as it is now: without autocommit, MySQL's REPEATABLE READ + # repeats the first read's snapshot (the plugin sets autocommit on its status connections for this reason). + connect_params = {**conn_utils.get_connect_params(host=host, port=port, dbname=db), "autocommit": True} + def _body(loop: asyncio.AbstractEventLoop) -> None: conn: Any = None try: - conn = loop.run_until_complete(_open_direct_conn_async( - test_driver, conn_utils.get_connect_params(host=host, port=port, dbname=db))) + conn = loop.run_until_complete(_open_direct_conn_async(test_driver, connect_params)) self.logger.debug(f"[AsyncDirectTopology @ {host_id}] Connection opened.") sleep(1) @@ -684,8 +775,7 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: while not stop.is_set() and perf_counter_ns() < end_time_ns: if conn is None: try: - conn = loop.run_until_complete(_open_direct_conn_async( - test_driver, conn_utils.get_connect_params(host=host, port=port, dbname=db))) + conn = loop.run_until_complete(_open_direct_conn_async(test_driver, connect_params)) self.logger.debug(f"[AsyncDirectTopology @ {host_id}] Connection re-opened.") except Exception: sleep(0.1) @@ -912,7 +1002,7 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: conn: Optional[AsyncAwsWrapperConnection] = None try: conn = loop.run_until_complete(_open()) - bg_plugin: Optional[BlueGreenPlugin] = _unwrap_plugin_async(conn, BlueGreenPlugin) + bg_plugin: Optional[AsyncBlueGreenPlugin] = _unwrap_plugin_async(conn, AsyncBlueGreenPlugin) assert bg_plugin is not None, \ f"Unable to find blue/green plugin in wrapper connection for {host}." self.logger.debug(f"[AsyncWrapperBlueExecute @ {host_id}] Connection opened.") @@ -982,7 +1072,7 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: try: conn = loop.run_until_complete(_open()) end_time_ns = perf_counter_ns() - bg_plugin: Optional[BlueGreenPlugin] = _unwrap_plugin_async(conn, BlueGreenPlugin) + bg_plugin: Optional[AsyncBlueGreenPlugin] = _unwrap_plugin_async(conn, AsyncBlueGreenPlugin) assert bg_plugin is not None, \ f"Unable to find blue/green plugin in wrapper connection for {host}." @@ -998,7 +1088,7 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: end_time_ns = perf_counter_ns() if conn is not None: - bg_plugin = _unwrap_plugin_async(conn, BlueGreenPlugin) + bg_plugin = _unwrap_plugin_async(conn, AsyncBlueGreenPlugin) assert bg_plugin is not None, \ f"Unable to find blue/green plugin in wrapper connection for {host}." results.blue_wrapper_connect_times.append( @@ -1025,6 +1115,82 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: finish_latch.count_down() self.logger.debug(f"[AsyncWrapperBlueNewConnection @ {host_id}] Thread is completed.") + # Blue host + # Check: an execute started in IN_PROGRESS on the connection that owns the status provider + # Expect: the plugin holds the execute until the phase moves on + # Needs a stop signal to terminate: the status provider's tasks run on this thread's loop until then + def wrapper_blue_suspended_execute_probe_async( + self, + test_driver: TestDriver, + conn_utils: ConnectionUtils, + host: str, + port: int, + db: str, + observer: PhaseObserver, + stop: Event, + finish_latch: CountDownLatch, + connected: Event, + result: ProbeResult) -> None: + connect_params = self.get_wrapper_connect_params(conn_utils, host, port, db) + + def _read_status(bg_plugin: AsyncBlueGreenPlugin) -> Optional[AsyncBlueGreenStatus]: + return bg_plugin._plugin_service.get_status(AsyncBlueGreenStatus, bg_plugin._bg_id) + + async def _open_with_retry() -> AsyncAwsWrapperConnection: + for _ in range(BG_PROBE_CONNECT_ATTEMPTS - 1): + try: + return await _open_wrapper_conn_async(test_driver, connect_params) + except Exception as e: + self.logger.debug(f"[AsyncWrapperBlueSuspendedExecute @ {host}] Connect exception: {e}") + return await _open_wrapper_conn_async(test_driver, connect_params) + + async def _execute_in_progress(cursor: AsyncAwsWrapperCursor, bg_plugin: AsyncBlueGreenPlugin) -> None: + result.phase_at_start = BlueGreenPhase.IN_PROGRESS.name + error: Optional[Exception] = None + result.begin() + try: + await asyncio.wait_for(cursor.execute("SELECT 1"), BG_ASYNC_EXECUTE_TIMEOUT_SEC) + except Exception as e: + error = e + result.end(error, observer.record(_read_status(bg_plugin))) + # The old blue may drop the connection at POST; the loop must keep running for the status provider. + try: + await cursor.fetchall() + except Exception as e: + self.logger.debug(f"[AsyncWrapperBlueSuspendedExecute @ {host}] Fetch exception: {e}") + + async def _main() -> None: + conn = await _open_with_retry() + bg_plugin: Optional[AsyncBlueGreenPlugin] = _unwrap_plugin_async(conn, AsyncBlueGreenPlugin) + try: + assert bg_plugin is not None, f"Unable to find blue/green plugin in wrapper connection for {host}." + # Entering the cursor creates the driver cursor through the plugin, before IN_PROGRESS. + async with conn.cursor() as cursor: + connected.set() + while not stop.is_set(): + phase = observer.record(_read_status(bg_plugin)) + if phase == BlueGreenPhase.IN_PROGRESS.name and result.start_ns == 0: + await _execute_in_progress(cursor, bg_plugin) + await asyncio.sleep(BG_PLUGIN_STATUS_POLL_SEC) + finally: + # Stop the status provider's tasks on the loop they run on. + if bg_plugin is not None: + provider = AsyncBlueGreenPlugin._status_providers.get(bg_plugin._bg_id) + if provider is not None: + await provider.stop() + await _close_conn_async(conn) + + def _body(loop: asyncio.AbstractEventLoop) -> None: + loop.run_until_complete(_main()) + + try: + _run_worker_with_loop(_body) + except Exception as e: + self.logger.debug(f"[AsyncWrapperBlueSuspendedExecute @ {host}] Thread exception: {e}") + finally: + finish_latch.count_down() + self.logger.debug(f"[AsyncWrapperBlueSuspendedExecute @ {host}] Thread is completed.") + # Blue / Green DNS monitors are purely sync (socket calls); reuse verbatim. def blue_dns_monitor( @@ -1092,7 +1258,7 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: conn = loop.run_until_complete(_open()) self.logger.debug(f"[AsyncWrapperGreenConnectivity @ {host_id}] Connection opened.") - bg_plugin: Optional[BlueGreenPlugin] = _unwrap_plugin_async(conn, BlueGreenPlugin) + bg_plugin: Optional[AsyncBlueGreenPlugin] = _unwrap_plugin_async(conn, AsyncBlueGreenPlugin) assert bg_plugin is not None, \ f"Unable to find blue/green plugin in wrapper connection for {host}." @@ -1240,12 +1406,12 @@ def _body(loop: asyncio.AbstractEventLoop) -> None: f"[AsyncDirectGreenIamIp{thread_prefix} @ {host_id}] " f"Thread exception: {e}") result_queue.append(TimeHolder(start_ns, perf_counter_ns(), error=str(e))) - if notify_on_first_error and "access denied" in str(e).lower(): + if notify_on_first_error and self.is_authentication_failure(e): results.green_node_changed_name_time_ns.compare_and_set( 0, perf_counter_ns()) self.logger.debug( f"[AsyncDirectGreenIamIp{thread_prefix} @ {host_id}] " - f"Encountered first 'Access denied' exception. Exiting thread...") + f"Encountered the first authentication failure. Exiting thread...") return self.close_connection_async(conn, loop) @@ -1273,7 +1439,9 @@ def bg_switchover_trigger( bg_id: str, start_latch: CountDownLatch, finish_latch: CountDownLatch, - results: Any) -> None: + results: Any, + stop: Event, + request: SwitchoverRequest) -> None: """Trigger BG switchover using RDS API (synchronous boto3 calls).""" try: start_latch.count_down() @@ -1284,7 +1452,17 @@ def bg_switchover_trigger( result.threads_sync_time.set(sync_time_ns) sleep(30) - test_utility.switchover_blue_green_deployment(bg_id) + # The main thread sets stop when it gives up waiting for the request, and then waits for the RDS API only + # if the request is marked, so the check and the mark stay together. + if stop.is_set(): + return + request.requested_ns = perf_counter_ns() + request.requested.set() + try: + test_utility.switchover_blue_green_deployment(bg_id) + except Exception as e: + request.error = e + raise bg_trigger_time_ns = perf_counter_ns() for result in results.values(): @@ -1430,19 +1608,21 @@ def print_node_status_times( def print_duration_times( self, node: str, title: str, times: Deque[TimeHolder], time_zero_ns: int) -> None: + # A monitor thread that hasn't stopped yet can still append to the deque. + samples = list(times) table = [] headers = ["Connect at (ms)", "Connect time/duration (ms)", "Error"] - p99_ns = self.get_percentile([time.end_time_ns - time.start_time_ns for time in times], 99.0) + p99_ns = self.get_percentile([time.end_time_ns - time.start_time_ns for time in samples], 99.0) p99_ms = p99_ns // 1_000_000 table.append(["p99", p99_ms, ""]) - first_connect = times[0] + first_connect = samples[0] table.append([ (first_connect.start_time_ns - time_zero_ns) // 1_000_000, (first_connect.end_time_ns - first_connect.start_time_ns) // 1_000_000, self.get_formatted_error(first_connect.error) ]) - for time_holder in times: + for time_holder in samples: duration_ms = (time_holder.end_time_ns - time_holder.start_time_ns) // 1_000_000 if duration_ms > p99_ms: table.append([ @@ -1451,7 +1631,7 @@ def print_duration_times( self.get_formatted_error(time_holder.error) ]) - last_connect = times[-1] + last_connect = samples[-1] table.append([ (last_connect.start_time_ns - time_zero_ns) // 1_000_000, (last_connect.end_time_ns - last_connect.start_time_ns) // 1_000_000, @@ -1497,5 +1677,3 @@ def assert_test(self) -> None: self.logger.debug(f"switchover_complete_time: {switchover_complete_time_ms} ms") assert switchover_complete_time_ms != 0, "BG switchover hasn't completed." - assert switchover_complete_time_ms >= max_green_node_changed_name_time_ms, \ - "Green node changed name after SWITCHOVER_COMPLETED." diff --git a/tests/integration/container/utils/blue_green_checks.py b/tests/integration/container/utils/blue_green_checks.py new file mode 100644 index 000000000..17de43a86 --- /dev/null +++ b/tests/integration/container/utils/blue_green_checks.py @@ -0,0 +1,219 @@ +# 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. + +"""Probe results and waits shared by the sync and async Blue/Green switchover tests.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from threading import Condition, Event +from time import perf_counter_ns, sleep, thread_time +from typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional, + Sequence, Tuple) + +from aws_advanced_python_wrapper.blue_green_plugin import BlueGreenPhase +from .test_timings import (BG_API_STATUS_WAIT_SEC, + BG_SUSPENDED_CALL_MAX_CPU_SEC, + BG_SUSPENDED_CALL_MAX_SEC, + BG_SWITCHOVER_REQUEST_WAIT_SEC, + BG_SWITCHOVER_WAIT_SEC, BG_TRIGGER_JOIN_SEC, + BG_WAIT_STEP_SEC) + +if TYPE_CHECKING: + from threading import Thread + + from .rds_test_utility import RdsTestUtility + +_NS_PER_SEC = 1_000_000_000 +_PHASES_PAST_IN_PROGRESS = (BlueGreenPhase.POST.name, BlueGreenPhase.COMPLETED.name) + + +@dataclass +class ProbeResult: + """What one probe saw. A phase is the name of the plugin's phase, read from its status store.""" + phase_at_start: Optional[str] = None + phase_at_end: Optional[str] = None + start_ns: int = 0 + end_ns: int = 0 + cpu_sec: float = 0.0 + error: Optional[Exception] = None + driver_host: Optional[str] = None + server_id: Optional[str] = None + _cpu_start_sec: float = field(default=0.0, repr=False) + + def begin(self) -> None: + """Call on the probe's own thread right before the call.""" + self._cpu_start_sec = thread_time() + self.start_ns = perf_counter_ns() + + def end(self, error: Optional[Exception], phase_at_end: Optional[str]) -> None: + """Call on the probe's own thread right after the call.""" + self.cpu_sec = thread_time() - self._cpu_start_sec + self.error = error + self.phase_at_end = phase_at_end + self.end_ns = perf_counter_ns() + + def is_in_flight(self) -> bool: + return self.start_ns > 0 and self.end_ns == 0 + + def duration_sec(self, now_ns: int) -> float: + """How long the call took, or has taken so far while it is in flight.""" + if self.start_ns == 0: + return 0.0 + if self.end_ns == 0: + return (now_ns - self.start_ns) / _NS_PER_SEC + return (self.end_ns - self.start_ns) / _NS_PER_SEC + + def is_stuck(self, now_ns: int) -> bool: + return self.is_in_flight() and self.duration_sec(now_ns) > BG_SUSPENDED_CALL_MAX_SEC + + +def suspended_call_failures( + label: str, probe: ProbeResult, now_ns: int, check_held: bool, check_cpu: bool) -> List[str]: + """Judge a call that a probe started in IN_PROGRESS. It gets at most one failure line. + + :param label: names the call in the line, for example "execute". + :param probe: the probe's result. + :param now_ns: when the test stopped waiting, from perf_counter_ns(). + :param check_held: whether the plugin must hold the call until the phase moves on. + :param check_cpu: whether the call must stay within BG_SUSPENDED_CALL_MAX_CPU_SEC of its thread's CPU. + :return: the failure line, or no line when the call passed. + """ + if probe.phase_at_start != BlueGreenPhase.IN_PROGRESS.name: + return [f"The {label} probe didn't start in IN_PROGRESS (phase {probe.phase_at_start})."] + if probe.duration_sec(now_ns) > BG_SUSPENDED_CALL_MAX_SEC: + return [f"The {label} started in IN_PROGRESS didn't return within {BG_SUSPENDED_CALL_MAX_SEC:.0f} s."] + if check_held and isinstance(probe.error, TimeoutError): + return [f"bg_connect_timeout_ms released the {label} while the plugin phase was still IN_PROGRESS."] + if check_held and probe.phase_at_end not in _PHASES_PAST_IN_PROGRESS: + return [f"The {label} returned in plugin phase {probe.phase_at_end}, so the plugin didn't hold it."] + if check_cpu and probe.cpu_sec > BG_SUSPENDED_CALL_MAX_CPU_SEC: + return [f"The suspended {label} used more than {BG_SUSPENDED_CALL_MAX_CPU_SEC} s of its thread's CPU."] + return [] + + +class PhaseObserver: + """The first time a test thread saw each phase the plugin published.""" + + def __init__(self) -> None: + self.first_seen_ns: Dict[str, int] = {} + self._latest_phase_value = 0 + self._changed = Condition() + + def record(self, status: Any) -> Optional[str]: + """Record a status read from the plugin. Works for the sync and the aio status classes. + + :param status: the status, or None when the plugin has published none. + :return: the name of the status's phase, or None when there is no status. + """ + if status is None: + return None + phase = status.phase + with self._changed: + if phase.name not in self.first_seen_ns: + self.first_seen_ns[phase.name] = perf_counter_ns() + self._latest_phase_value = max(self._latest_phase_value, phase.phase_value) + self._changed.notify_all() + return phase.name + + def is_seen(self, phase: BlueGreenPhase) -> bool: + return phase.name in self.first_seen_ns + + def wait_for(self, phase: BlueGreenPhase, stop: Event) -> bool: + """Wait until the phase is seen. + + :param phase: the phase to wait for. + :param stop: ends the wait when set. + :return: True when the phase was seen; False on stop, or when a later phase was seen without it. + """ + with self._changed: + while not stop.is_set(): + if phase.name in self.first_seen_ns: + return True + if self._latest_phase_value > phase.phase_value: + return False + self._changed.wait(BG_WAIT_STEP_SEC) + return False + + +@dataclass +class SwitchoverRequest: + """Filled by the trigger thread. requested_ns is set before requested, and error only after it.""" + requested: Event = field(default_factory=Event) + requested_ns: int = 0 + error: Optional[Exception] = None + + +def _is_settled(thread: Thread, result: ProbeResult, now_ns: int) -> bool: + return not thread.is_alive() or result.end_ns > 0 or result.is_stuck(now_ns) + + +def wait_for_switchover( + request: SwitchoverRequest, + threads_start_ns: int, + probes: Sequence[Tuple[Thread, ProbeResult]], + is_completed: Callable[[], bool]) -> str: + """Wait until the switchover completed and every probe ended, or a probe is stuck, within the bounds. + + :param request: the trigger thread's switchover request. + :param threads_start_ns: when the test threads started, from perf_counter_ns(). + :param probes: each probe's thread and result. + :param is_completed: tells whether a test thread saw the switchover complete. + :return: why the wait ended. + """ + request_deadline_ns = threads_start_ns + int(BG_SWITCHOVER_REQUEST_WAIT_SEC * _NS_PER_SEC) + switchover_wait_ns = int(BG_SWITCHOVER_WAIT_SEC * _NS_PER_SEC) + while request.error is None: + now_ns = perf_counter_ns() + if not request.requested.is_set(): + if now_ns > request_deadline_ns: + return f"no switchover request within {BG_SWITCHOVER_REQUEST_WAIT_SEC:.0f} s of thread start" + elif now_ns > request.requested_ns + switchover_wait_ns: + return f"the switchover did not finish within {BG_SWITCHOVER_WAIT_SEC:.0f} s of the request" + elif all(_is_settled(thread, result, now_ns) for thread, result in probes): + if is_completed(): + return "the switchover completed" + if any(result.is_stuck(now_ns) for _, result in probes): + return "a probe is stuck" + sleep(BG_WAIT_STEP_SEC) + return "the switchover request failed" + + +def settle_switchover( + test_utility: RdsTestUtility, + bg_id: str, + trigger_thread: Thread, + stop: Event, + request: SwitchoverRequest) -> Optional[str]: + """Stop the trigger if it has not requested the switchover, else wait for the RDS API to finish it. Always sets stop. + + :param test_utility: reads the deployment from the RDS API. + :param bg_id: the Blue/Green deployment ID. + :param trigger_thread: the thread that requests the switchover. + :param stop: the stop signal of every test thread. + :param request: the trigger thread's switchover request. + :return: the deployment status the RDS API reported last. None when no switchover request succeeded, or when no + read found the deployment. + """ + try: + if not request.requested.is_set(): + stop.set() + trigger_thread.join(BG_TRIGGER_JOIN_SEC) + if not request.requested.is_set() or request.error is not None: + return None + remaining_sec = BG_API_STATUS_WAIT_SEC - (perf_counter_ns() - request.requested_ns) / _NS_PER_SEC + return test_utility.wait_until_blue_green_deployment_has_desired_status( + bg_id, remaining_sec, "SWITCHOVER_COMPLETED", "SWITCHOVER_FAILED") + finally: + stop.set() diff --git a/tests/integration/container/utils/rds_test_utility.py b/tests/integration/container/utils/rds_test_utility.py index e42ed3736..e80590fd2 100644 --- a/tests/integration/container/utils/rds_test_utility.py +++ b/tests/integration/container/utils/rds_test_utility.py @@ -49,7 +49,8 @@ from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from tests.integration.container.utils.test_timings import ( - CLUSTER_STATUS_TIMEOUT_SEC, FAILOVER_DEADLINE_SEC, FAILOVER_MAX_REISSUES, + BG_API_STATUS_POLL_INTERVAL_SEC, 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, @@ -838,6 +839,28 @@ def get_blue_green_deployment(self, bg_id: str) -> Optional[Any]: except self._client.exceptions.BlueGreenDeploymentNotFoundFault: return None + def wait_until_blue_green_deployment_has_desired_status( + self, bg_id: str, timeout_sec: float, *desired_statuses: str) -> Optional[str]: + """Wait until the Blue/Green deployment reaches one of the statuses, or the timeout passes. + + :param bg_id: the Blue/Green deployment ID. + :param timeout_sec: how long to wait, in seconds. + :param desired_statuses: the RDS API statuses to wait for, for example ``SWITCHOVER_COMPLETED``. + :return: the last status read, or None when no read found the deployment. + """ + stop_time = timeit.default_timer() + timeout_sec + status = None + while True: + try: + deployment = self.get_blue_green_deployment(bg_id) + if deployment is not None: + status = deployment.get("Status") + except Exception as e: + self.logger.debug(f"Blue/Green deployment {bg_id} status read failed: {e}") + if status in desired_statuses or timeit.default_timer() > stop_time: + return status + sleep(BG_API_STATUS_POLL_INTERVAL_SEC) + def switchover_blue_green_deployment(self, bg_id: str): try: self._client.switchover_blue_green_deployment(BlueGreenDeploymentIdentifier=bg_id) diff --git a/tests/integration/container/utils/test_timings.py b/tests/integration/container/utils/test_timings.py index 26d342859..ef184856b 100644 --- a/tests/integration/container/utils/test_timings.py +++ b/tests/integration/container/utils/test_timings.py @@ -122,3 +122,52 @@ # with extra topology-refresh polling, so 900 s is a sensible ceiling # that catches genuine hangs without hiding real timeouts. FAILOVER_WITHIN_TRANSACTION_PYTEST_TIMEOUT_SEC: int = 900 + +# ───── Blue/Green switchover tests ───────────────────────────────────── +# The plugin holds a call it suspends in IN_PROGRESS for at most +# ``bg_connect_timeout_ms`` (30 s by default) per pass, so a correct call +# returns within two of those. +BG_SUSPENDED_CALL_MAX_SEC: float = 60 +# A suspended call waits on the plugin's status in 50 ms steps, which uses +# far less of its thread's CPU than this. +BG_SUSPENDED_CALL_MAX_CPU_SEC: float = 1.0 +# The plugin publishes each phase for at least 1.7 s, so the test's status +# observer sees every phase at this poll rate. +BG_PLUGIN_STATUS_POLL_SEC: float = 0.02 +# How long a test thread sleeps between two checks of what it waits for. +BG_WAIT_STEP_SEC: float = 0.5 +# How long the sync test waits for the plugin to give the blue cluster +# endpoint its SOURCE role before it chooses the probes' host. +BG_PROBE_HOST_ROLE_WAIT_SEC: float = 20 +# Connect attempts, and the connect timeout of each, for a probe connection. +# POST lasts 23 to 26 s. +BG_PROBE_CONNECT_ATTEMPTS: int = 3 +BG_PROBE_CONNECT_TIMEOUT_SEC: int = 10 +# How long the async test waits for its probe to connect. That connection +# owns the status provider, so the other threads start after it. +BG_ASYNC_PROBE_CONNECT_WAIT_SEC: float = 30 +# Ends an async probe execute that never returns, past +# BG_SUSPENDED_CALL_MAX_SEC, so the probe's loop can stop the status provider. +BG_ASYNC_EXECUTE_TIMEOUT_SEC: float = 75 +# From thread start: the trigger waits for the other threads to be ready, +# then 30 s, before it requests the switchover. +BG_SWITCHOVER_REQUEST_WAIT_SEC: float = 150 +# From the request: the plugin published COMPLETED 41 to 45 s after it. +BG_SWITCHOVER_WAIT_SEC: float = 240 +# From the request: the RDS API reported SWITCHOVER_COMPLETED 68 to 73 s +# after it. +BG_API_STATUS_WAIT_SEC: float = 300 +BG_API_STATUS_POLL_INTERVAL_SEC: float = 5 +# How long the main thread waits for the trigger thread after it stopped +# waiting for the request. +BG_TRIGGER_JOIN_SEC: float = 5 +# One deadline for every test thread to stop. +BG_THREAD_JOIN_SEC: float = 20 +# The switchover tests' marker overrides the harness's 600 s ``--timeout``. +# pytest-timeout's thread method counts the setup hook as well. Worst case: +# setup + 30 s (async probe connect; the sync role wait is 20 s) + 150 s +# (latest request) + 300 s (RDS API wait from the request) + 20 s (thread +# stop) = setup + 500 s, so a run fits when setup takes under 400 s. Setup +# takes about a minute on a healthy cluster; its own waits allow up to +# 1500 s (cluster status 600 s, instances 300 s and 300 s, DNS 300 s). +BG_SWITCHOVER_PYTEST_TIMEOUT_SEC: int = 900 diff --git a/tests/integration/host/build.gradle.kts b/tests/integration/host/build.gradle.kts index c84e90f8e..1c77f68c4 100644 --- a/tests/integration/host/build.gradle.kts +++ b/tests/integration/host/build.gradle.kts @@ -544,6 +544,112 @@ tasks.register("test-bgd-pg-aurora") { } } +// One environment and one Blue/Green deployment each: a deployment switches over once. + +tasks.register("test-bgd-mysql-aurora-sync") { + group = "verification" + filter.includeTestsMatching("integration.host.TestRunner.runTests") + environment("FILTER", "test_switchover and not test_switchover_async") + doFirst { + systemProperty("exclude-docker", "true") + systemProperty("exclude-performance", "true") + systemProperty("exclude-pg-driver", "true") + systemProperty("exclude-pg-engine", "true") + systemProperty("exclude-multi-az-instance", "true") + systemProperty("exclude-failover", "true") + systemProperty("exclude-secrets-manager", "true") + systemProperty("exclude-instances-1", "true") + systemProperty("exclude-instances-3", "true") + systemProperty("exclude-instances-5", "true") + systemProperty("exclude-multi-az-cluster", "true") + systemProperty("exclude-python-3-10", "true") + systemProperty("exclude-python-3-11", "true") + systemProperty("exclude-python-3-13", "true") + systemProperty("exclude-python-3-14", "true") + systemProperty("exclude-traces-telemetry", "true") + systemProperty("exclude-metrics-telemetry", "true") + systemProperty("exclude-async-drivers", "true") + systemProperty("test-bg-only", "true") + } +} + +tasks.register("test-bgd-mysql-aurora-async") { + group = "verification" + filter.includeTestsMatching("integration.host.TestRunner.runTests") + environment("FILTER", "test_switchover_async") + doFirst { + systemProperty("exclude-docker", "true") + systemProperty("exclude-performance", "true") + systemProperty("exclude-pg-driver", "true") + systemProperty("exclude-pg-engine", "true") + systemProperty("exclude-multi-az-instance", "true") + systemProperty("exclude-failover", "true") + systemProperty("exclude-secrets-manager", "true") + systemProperty("exclude-instances-1", "true") + systemProperty("exclude-instances-3", "true") + systemProperty("exclude-instances-5", "true") + systemProperty("exclude-multi-az-cluster", "true") + systemProperty("exclude-python-3-10", "true") + systemProperty("exclude-python-3-11", "true") + systemProperty("exclude-python-3-13", "true") + systemProperty("exclude-python-3-14", "true") + systemProperty("exclude-traces-telemetry", "true") + systemProperty("exclude-metrics-telemetry", "true") + systemProperty("exclude-sync-drivers", "true") + systemProperty("test-bg-only", "true") + } +} + +tasks.register("test-bgd-pg-aurora-sync") { + group = "verification" + filter.includeTestsMatching("integration.host.TestRunner.runTests") + environment("FILTER", "test_switchover and not test_switchover_async") + doFirst { + systemProperty("exclude-docker", "true") + systemProperty("exclude-performance", "true") + systemProperty("exclude-mysql-driver", "true") + systemProperty("exclude-mysql-engine", "true") + systemProperty("exclude-multi-az-instance", "true") + systemProperty("exclude-failover", "true") + systemProperty("exclude-secrets-manager", "true") + systemProperty("exclude-instances-1", "true") + systemProperty("exclude-instances-3", "true") + systemProperty("exclude-instances-5", "true") + systemProperty("exclude-multi-az-cluster", "true") + systemProperty("exclude-python-3-10", "true") + systemProperty("exclude-python-3-11", "true") + systemProperty("exclude-python-3-13", "true") + systemProperty("exclude-python-3-14", "true") + systemProperty("exclude-async-drivers", "true") + systemProperty("test-bg-only", "true") + } +} + +tasks.register("test-bgd-pg-aurora-async") { + group = "verification" + filter.includeTestsMatching("integration.host.TestRunner.runTests") + environment("FILTER", "test_switchover_async") + doFirst { + systemProperty("exclude-docker", "true") + systemProperty("exclude-performance", "true") + systemProperty("exclude-mysql-driver", "true") + systemProperty("exclude-mysql-engine", "true") + systemProperty("exclude-multi-az-instance", "true") + systemProperty("exclude-failover", "true") + systemProperty("exclude-secrets-manager", "true") + systemProperty("exclude-instances-1", "true") + systemProperty("exclude-instances-3", "true") + systemProperty("exclude-instances-5", "true") + systemProperty("exclude-multi-az-cluster", "true") + systemProperty("exclude-python-3-10", "true") + systemProperty("exclude-python-3-11", "true") + systemProperty("exclude-python-3-13", "true") + systemProperty("exclude-python-3-14", "true") + systemProperty("exclude-sync-drivers", "true") + systemProperty("test-bg-only", "true") + } +} + // Debug tasks.register("debug-all-environments") { diff --git a/tests/integration/host/src/test/java/integration/host/TestEnvironment.java b/tests/integration/host/src/test/java/integration/host/TestEnvironment.java index fcd32a3a7..313b4321f 100644 --- a/tests/integration/host/src/test/java/integration/host/TestEnvironment.java +++ b/tests/integration/host/src/test/java/integration/host/TestEnvironment.java @@ -1355,6 +1355,14 @@ private void deleteBlueGreenDeployment() throws InterruptedException { return; } + // Let an in-flight switchover settle first: the status read below picks the cluster to delete. + auroraUtil.waitUntilBlueGreenDeploymentSettled(this.info.getBlueGreenDeploymentId()); + final BlueGreenDeployment settledDeployment = + auroraUtil.getBlueGreenDeployment(this.info.getBlueGreenDeploymentId()); + if (settledDeployment != null) { + blueGreenDeployment = settledDeployment; + } + auroraUtil.deleteBlueGreenDeployment(this.info.getBlueGreenDeploymentId(), true); // Remove extra DB cluster diff --git a/tests/integration/host/src/test/java/integration/util/AuroraTestUtility.java b/tests/integration/host/src/test/java/integration/util/AuroraTestUtility.java index 1b8684ed9..dce86f4c0 100644 --- a/tests/integration/host/src/test/java/integration/util/AuroraTestUtility.java +++ b/tests/integration/host/src/test/java/integration/util/AuroraTestUtility.java @@ -912,9 +912,17 @@ public DatabaseEngine getRdsInstanceEngine(final DBInstance instance) { } public String getAuroraParameterGroupFamily(String engine, String engineVersion) { + final String family = queryParameterGroupFamily(engine, engineVersion); + if (!StringUtils.isNullOrEmpty(family)) { + return family; + } switch (engine) { case "aurora-postgresql": - return "aurora-postgresql16"; + if (StringUtils.isNullOrEmpty(engineVersion)) { + return "aurora-postgresql16"; + } + // The PostgreSQL families are named after the major version, for example "aurora-postgresql17". + return "aurora-postgresql" + engineVersion.split("\\.")[0]; case "aurora-mysql": if (StringUtils.isNullOrEmpty(engineVersion) || engineVersion.contains("8.0")) { return "aurora-mysql8.0"; @@ -925,6 +933,29 @@ public String getAuroraParameterGroupFamily(String engine, String engineVersion) } } + /** + * Asks RDS for the parameter group family of an engine version, or returns null when the version is + * empty or the family cannot be determined. + */ + private @Nullable String queryParameterGroupFamily(String engine, String engineVersion) { + if (StringUtils.isNullOrEmpty(engineVersion)) { + return null; + } + try { + final DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions( + DescribeDbEngineVersionsRequest.builder().engine(engine).engineVersion(engineVersion).build()); + return response.dbEngineVersions().stream() + .map(DBEngineVersion::dbParameterGroupFamily) + .filter(family -> !StringUtils.isNullOrEmpty(family)) + .findFirst() + .orElse(null); + } catch (Exception ex) { + LOGGER.finest(String.format( + "Could not query the parameter group family of %s %s: %s", engine, engineVersion, ex.getMessage())); + return null; + } + } + public List getTestInstancesInfo(final String clusterId) { List dbInstances = getDBInstances(clusterId); List instancesInfo = new ArrayList<>(); @@ -1177,9 +1208,20 @@ public String createBlueGreenDeployment(String name, String sourceArn) { return blueGreenId; } + /** Waits until a switchover in flight has settled, so the deployment can be deleted. */ + public void waitUntilBlueGreenDeploymentSettled(String blueGreenId) { + waitUntilBlueGreenDeploymentHasRightState( + blueGreenId, "available", "switchover_completed", "switchover_failed", "invalid_configuration"); + } + public void waitUntilBlueGreenDeploymentHasRightState(String blueGreenId, String... allowedStatuses) { - String status = getBlueGreenDeployment(blueGreenId).status(); + BlueGreenDeployment deployment = getBlueGreenDeployment(blueGreenId); + if (deployment == null) { + LOGGER.finest("BGD " + blueGreenId + " not found."); + return; + } + String status = deployment.status(); LOGGER.finest("BGD status: " + status + ", waiting for status: " + String.join(", ", allowedStatuses)); final Set allowedStatusSet = Arrays.stream(allowedStatuses) .map(String::toLowerCase) @@ -1191,7 +1233,12 @@ public void waitUntilBlueGreenDeploymentHasRightState(String blueGreenId, String } catch (InterruptedException ex) { throw new RuntimeException(ex); } - String tmpStatus = getBlueGreenDeployment(blueGreenId).status(); + deployment = getBlueGreenDeployment(blueGreenId); + if (deployment == null) { + LOGGER.finest("BGD " + blueGreenId + " not found."); + return; + } + String tmpStatus = deployment.status(); if (!tmpStatus.equalsIgnoreCase(status)) { LOGGER.finest("BGD status (waiting): " + tmpStatus); } @@ -1247,7 +1294,7 @@ public void deleteBlueGreenDeployment(String blueGreenId, boolean waitForComplet return; } - waitUntilBlueGreenDeploymentHasRightState(blueGreenId, "available", "switchover_completed"); + waitUntilBlueGreenDeploymentSettled(blueGreenId); DeleteBlueGreenDeploymentResponse response = rdsClient.deleteBlueGreenDeployment( DeleteBlueGreenDeploymentRequest.builder() diff --git a/tests/unit/test_aio_blue_green_monitor.py b/tests/unit/test_aio_blue_green_monitor.py index 47d23865d..748619282 100644 --- a/tests/unit/test_aio_blue_green_monitor.py +++ b/tests/unit/test_aio_blue_green_monitor.py @@ -42,11 +42,14 @@ from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict -from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.iam_utils import IamAuthUtils +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) from aws_advanced_python_wrapper.utils.value_container import ValueContainer # Realistic RDS endpoints so RdsUtils DNS heuristics fire as they would in prod. BLUE_WRITER = "bg-blue.cluster-abc123.us-east-2.rds.amazonaws.com" +BLUE_WRITER_IP = "10.0.1.10" BLUE_READER_CLUSTER = "bg-blue.cluster-ro-abc123.us-east-2.rds.amazonaws.com" GREEN_WRITER = "bg-green.cluster-abc123.us-east-2.rds.amazonaws.com" @@ -726,6 +729,22 @@ async def _body(): assert monitor.is_running() is False +def test_monitor_reconnect_by_ip_sets_iam_host_to_host_name() -> None: + svc = _mock_plugin_service() + monitor = AsyncBlueGreenStatusMonitor( + BlueGreenRole.SOURCE, "bg", HostInfo(BLUE_WRITER, 5432), svc, Properties(), {}, None) + monitor._connection_host_info = HostInfo(BLUE_WRITER, 5432) + monitor._connected_ip_address = BLUE_WRITER_IP + monitor.use_ip_address = True + + _run(monitor._open_connection_task()) + + host_info, props = svc.force_connect.call_args.args + assert host_info.host == BLUE_WRITER_IP + assert WrapperProperties.IAM_HOST.get(props) == BLUE_WRITER + assert IamAuthUtils.get_iam_host(props, host_info) == BLUE_WRITER + + def test_monitor_poll_hands_interim_to_processor(monkeypatch) -> None: published: List[BlueGreenInterimStatus] = [] diff --git a/tests/unit/test_blue_green_plugin.py b/tests/unit/test_blue_green_plugin.py index 3f8b1eeea..df4247aa1 100644 --- a/tests/unit/test_blue_green_plugin.py +++ b/tests/unit/test_blue_green_plugin.py @@ -18,12 +18,14 @@ import pytest from aws_advanced_python_wrapper.blue_green_plugin import ( - BlueGreenPhase, BlueGreenRole, BlueGreenStatus, SubstituteConnectRouting, - SuspendUntilCorrespondingHostFoundConnectRouting) + BlueGreenPhase, BlueGreenRole, BlueGreenStatus, BlueGreenStatusMonitor, + SubstituteConnectRouting, SuspendUntilCorrespondingHostFoundConnectRouting) +from aws_advanced_python_wrapper.database_dialect import BlueGreenDialect from aws_advanced_python_wrapper.federated_plugin import FederatedAuthPlugin from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.okta_plugin import OktaAuthPlugin from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict +from aws_advanced_python_wrapper.utils.iam_utils import IamAuthUtils from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.properties import (Properties, WrapperProperties) @@ -31,6 +33,7 @@ BG_ID = "1" PORT = 3306 BLUE_HOST = "database-1.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +BLUE_IP = "10.0.1.10" GREEN_HOST = "database-1-green-abc123.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" GREEN_IP = "10.0.1.20" @@ -62,6 +65,23 @@ def test_substitute_connect_routing_to_an_ip_sets_the_iam_host_for_federated_and assert WrapperProperties.IAM_HOST.get(rerouted_props) == GREEN_HOST +def test_status_monitor_reconnect_by_ip_sets_iam_host_to_host_name(): + plugin_service = MagicMock() + plugin_service.database_dialect = MagicMock(spec=BlueGreenDialect) + monitor = BlueGreenStatusMonitor( + BlueGreenRole.SOURCE, BG_ID, HostInfo(BLUE_HOST, PORT), plugin_service, Properties(), {}) + monitor._connection_host_info = HostInfo(BLUE_HOST, PORT) + monitor._connected_ip_address = BLUE_IP + monitor.use_ip_address.set() + + monitor._open_connection_task() + + host_info, props = plugin_service.force_connect.call_args.args + assert host_info.host == BLUE_IP + assert WrapperProperties.IAM_HOST.get(props) == BLUE_HOST + assert IamAuthUtils.get_iam_host(props, host_info) == BLUE_HOST + + def _corresponding_hosts() -> ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]]: corresponding_hosts: ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]] = ConcurrentDict() corresponding_hosts.put_all({BLUE_HOST: (HostInfo(BLUE_HOST, PORT), HostInfo(GREEN_HOST, PORT))})