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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions aws_advanced_python_wrapper/aio/blue_green_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
# Plugin codes (see aio/plugin_factory.py) whose presence implies IAM token
# authentication is active, gating the SubstituteConnectRouting IAM-host
# rerouting. Approximation of sync's plugin_service.is_plugin_in_use.
_IAM_PLUGIN_CODES: frozenset = frozenset({"iam"})
_AUTH_PLUGIN_CODES: frozenset = frozenset({"iam", "federated_auth", "okta"})


# ---- Enums -----------------------------------------------------------
Expand Down Expand Up @@ -318,7 +318,7 @@ def is_match(self, host_info: Optional[HostInfo], bg_role: BlueGreenRole) -> boo
if host_info is None:
return False

return self._endpoint == host_info.url.lower() and (self._bg_role is None or self._bg_role == bg_role)
return self._endpoint == host_info.get_host_and_port().lower() and (self._bg_role is None or self._bg_role == bg_role)

def __str__(self) -> str:
endpoint_str = "None" if self._endpoint is None else f"'{self._endpoint}'"
Expand Down Expand Up @@ -501,7 +501,7 @@ async def apply(
SuspendUntilCorrespondingHostFoundConnectRouting._TELEMETRY_SWITCHOVER, TelemetryTraceLevel.NESTED)

bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower())

timeout_ms = WrapperProperties.BG_CONNECT_TIMEOUT_MS.get_int(props)
loop = asyncio.get_running_loop()
Expand All @@ -517,7 +517,7 @@ async def apply(
await self.delay(
SuspendUntilCorrespondingHostFoundConnectRouting._SLEEP_TIME_MS, bg_status, plugin_service, self._bg_id)
bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower())

if bg_status is None or bg_status.phase == BlueGreenPhase.COMPLETED:
logger.debug(
Expand Down Expand Up @@ -616,7 +616,7 @@ def _is_iam_in_use(props: Properties) -> bool:
if not plugins:
return False
codes = {code.strip() for code in str(plugins).split(",")}
return bool(codes & _IAM_PLUGIN_CODES)
return bool(codes & _AUTH_PLUGIN_CODES)


# ---- Plugin ----------------------------------------------------------
Expand Down
29 changes: 21 additions & 8 deletions aws_advanced_python_wrapper/blue_green_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@

from aws_advanced_python_wrapper.errors import (AwsWrapperError,
UnsupportedOperationError)
from aws_advanced_python_wrapper.federated_plugin import FederatedAuthPlugin
from aws_advanced_python_wrapper.host_availability import HostAvailability
from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole
from aws_advanced_python_wrapper.iam_plugin import IamAuthPlugin
from aws_advanced_python_wrapper.okta_plugin import OktaAuthPlugin
from aws_advanced_python_wrapper.pep249_methods import DbApiMethod
from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory
from aws_advanced_python_wrapper.utils import services_container
Expand Down Expand Up @@ -315,7 +317,7 @@ def is_match(self, host_info: Optional[HostInfo], bg_role: BlueGreenRole) -> boo
if host_info is None:
return False

return self._endpoint == host_info.url.lower() and (self._bg_role is None or self._bg_role == bg_role)
return self._endpoint == host_info.get_host_and_port().lower() and (self._bg_role is None or self._bg_role == bg_role)

def __str__(self):
endpoint_str = "None" if self._endpoint is None else f"'{self._endpoint}'"
Expand Down Expand Up @@ -390,7 +392,7 @@ def apply(
if not SubstituteConnectRouting._rds_utils.is_ip(self._substitute_host_info.host):
return plugin_service.connect(self._substitute_host_info, props, plugin)

is_iam_in_use = plugin_service.is_plugin_in_use(IamAuthPlugin)
is_iam_in_use = any(plugin_service.is_plugin_in_use(p) for p in (IamAuthPlugin, FederatedAuthPlugin, OktaAuthPlugin))
if not is_iam_in_use:
return plugin_service.connect(self._substitute_host_info, props, plugin)

Expand Down Expand Up @@ -507,7 +509,7 @@ def apply(
SuspendUntilCorrespondingHostFoundConnectRouting._TELEMETRY_SWITCHOVER, TelemetryTraceLevel.NESTED)

bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower())

timeout_ms = WrapperProperties.BG_CONNECT_TIMEOUT_MS.get_int(props)
start_time_sec = time.time()
Expand All @@ -522,7 +524,7 @@ def apply(
self.delay(
SuspendUntilCorrespondingHostFoundConnectRouting._SLEEP_TIME_MS, bg_status, plugin_service, self._bg_id)
bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host)
corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower())

if bg_status is None or bg_status.phase == BlueGreenPhase.COMPLETED:
logger.debug(
Expand Down Expand Up @@ -684,13 +686,21 @@ def connect(
if conn is not None:
break

# Re-select against the LATEST published status: a suspend/wait
# routing returns None once switchover moves past its phase, so
# the current routing table (not the stale captured one) decides
# what happens next. Falls through to connect_func when the
# latest status no longer matches.
latest_status = self._plugin_service.get_status(BlueGreenStatus, self._bg_id)
if latest_status is None:
self._end_time_ns.set(perf_counter_ns())
return self._open_direct_connection(connect_func, is_initial_connection)

routing = \
next((r for r in self._bg_status.connect_routings if r.is_match(host_info, bg_role)), None)
self._bg_status = latest_status
bg_role = latest_status.get_role(host_info)
if bg_role is None:
break
routing = next((r for r in latest_status.connect_routings if r.is_match(host_info, bg_role)), None)

self._end_time_ns.set(perf_counter_ns())
if conn is None:
Expand Down Expand Up @@ -761,8 +771,11 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args:
self._end_time_ns.set(perf_counter_ns())
return execute_func()

routing = \
next((r for r in self._bg_status.execute_routings if r.is_match(host_info, bg_role)), None)
self._bg_status = latest_status
bg_role = None if host_info is None else latest_status.get_role(host_info)
if bg_role is None:
break
routing = next((r for r in latest_status.execute_routings if r.is_match(host_info, bg_role)), None)

self._end_time_ns.set(perf_counter_ns())
if result_container.is_present():
Expand Down
66 changes: 59 additions & 7 deletions tests/unit/test_aio_blue_green_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,24 @@
from __future__ import annotations

import asyncio
from typing import Any, Optional
from unittest.mock import AsyncMock, MagicMock
from typing import Any, Optional, Tuple
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from aws_advanced_python_wrapper.aio.blue_green_plugin import (
AsyncBlueGreenPlugin, AsyncBlueGreenStatusProvider, BlueGreenPhase,
BlueGreenRole, BlueGreenStatus, ConnectRouting, PassThroughConnectRouting,
RejectConnectRouting, SubstituteConnectRouting)
RejectConnectRouting, SubstituteConnectRouting,
SuspendUntilCorrespondingHostFoundConnectRouting)
from aws_advanced_python_wrapper.aio.plugin_factory import PLUGIN_FACTORIES
from aws_advanced_python_wrapper.database_dialect import BlueGreenDialect
from aws_advanced_python_wrapper.errors import AwsWrapperError
from aws_advanced_python_wrapper.hostinfo import HostInfo
from aws_advanced_python_wrapper.pep249_methods import DbApiMethod
from aws_advanced_python_wrapper.utils.properties import Properties
from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict
from aws_advanced_python_wrapper.utils.properties import (Properties,
WrapperProperties)


@pytest.fixture(autouse=True)
Expand Down Expand Up @@ -299,14 +302,63 @@ def test_execute_passes_through_when_host_not_in_bg():
execute_func.assert_awaited_once()


def test_substitute_connect_routing_is_match_by_url():
"""Endpoint matching mirrors sync BaseRouting.is_match (host_info.url)."""
def test_substitute_connect_routing_is_match_by_host_and_port():
"""An endpoint of host and port matches the host with that name and port, and not another host."""
routing = SubstituteConnectRouting(
HostInfo("10.0.0.1", 5432), "h:5432/", BlueGreenRole.SOURCE)
HostInfo("10.0.0.1", 5432), "h:5432", BlueGreenRole.SOURCE)
assert routing.is_match(HostInfo("h", 5432), BlueGreenRole.SOURCE) is True
assert routing.is_match(HostInfo("other", 5432), BlueGreenRole.SOURCE) is False


@pytest.mark.parametrize("plugin_code", ["federated_auth", "okta"])
def test_substitute_connect_routing_to_an_ip_sets_the_iam_host_for_federated_and_okta_auth(plugin_code):
"""The ADFS and Okta plugins get an IAM token for the host they connect to and reject an IP, so a connect
substituted by an IP sets the IAM host for them as it does for the IAM plugin."""
plugin = MagicMock()
plugin.plugin_service.connect = AsyncMock()
routing = SubstituteConnectRouting(
HostInfo("10.0.0.1", 5432), "h:5432", BlueGreenRole.SOURCE, (HostInfo("h-green", 5432),))

_run(routing.apply(
plugin, HostInfo("h", 5432), Properties({"plugins": f"bg,{plugin_code}"}), True, AsyncMock()))

rerouted_props = plugin.plugin_service.connect.call_args.args[1]
assert WrapperProperties.IAM_HOST.get(rerouted_props) == "h-green"


def _corresponding_hosts() -> ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]]:
corresponding_hosts: ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]] = ConcurrentDict()
corresponding_hosts.put_all({"h": (HostInfo("h", 5432), HostInfo("h-green", 5432))})
return corresponding_hosts


def test_suspend_until_corresponding_host_found_does_not_wait_for_a_known_host_given_in_upper_case():
"""The corresponding hosts are keyed by lower-case host name, so a host given in upper case whose
corresponding host is already known continues at once."""
plugin = MagicMock()
plugin.plugin_service.get_status.return_value = BlueGreenStatus(
"1", BlueGreenPhase.POST, corresponding_hosts=_corresponding_hosts())
props = Properties({WrapperProperties.BG_CONNECT_TIMEOUT_MS.name: 500})
routing = SuspendUntilCorrespondingHostFoundConnectRouting("h:5432", BlueGreenRole.SOURCE, "1")

with patch.object(routing, "delay", wraps=routing.delay) as delay:
assert _run(routing.apply(plugin, HostInfo("H", 5432), props, True, AsyncMock())) is None
delay.assert_not_called()


def test_suspend_until_corresponding_host_found_continues_when_a_host_given_in_upper_case_is_found():
"""A host given in upper case continues once a later status has its corresponding host, instead of waiting
out bg_connect_timeout_ms."""
found = BlueGreenStatus("1", BlueGreenPhase.POST, corresponding_hosts=_corresponding_hosts())
statuses = iter([BlueGreenStatus("1", BlueGreenPhase.POST)])
plugin = MagicMock()
plugin.plugin_service.get_status.side_effect = lambda *args: next(statuses, found)
props = Properties({WrapperProperties.BG_CONNECT_TIMEOUT_MS.name: 500})
routing = SuspendUntilCorrespondingHostFoundConnectRouting("h:5432", BlueGreenRole.SOURCE, "1")

assert _run(routing.apply(plugin, HostInfo("H", 5432), props, True, AsyncMock())) is None


def test_factory_produces_async_blue_green_plugin():
factory = PLUGIN_FACTORIES["bg"]
svc = _mock_service()
Expand Down
129 changes: 129 additions & 0 deletions tests/unit/test_aio_blue_green_routing_match.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# 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.

"""Endpoint matching of the async Blue/Green routings (issue #1352).

The status provider gives a routing an endpoint of the form ``host``,
``host:port``, ``ip`` or ``ip:port``. These tests build the routings with
those endpoints and check that they match the host they name, and that a
connection to that host is then routed by them.
"""

from __future__ import annotations

import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock

import pytest

from aws_advanced_python_wrapper.aio.blue_green_plugin import (
AsyncBlueGreenPlugin, BlueGreenPhase, BlueGreenRole, BlueGreenStatus,
RejectConnectRouting, SubstituteConnectRouting, SuspendConnectRouting,
SuspendExecuteRouting, SuspendUntilCorrespondingHostFoundConnectRouting)
from aws_advanced_python_wrapper.hostinfo import HostInfo
from aws_advanced_python_wrapper.utils.properties import Properties

BG_ID = "1"
PORT = 3306
BLUE_HOST = "database-1.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com"
GREEN_HOST = "database-1-green-abc123.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com"
BLUE_IP = "10.0.1.10"
GREEN_IP = "10.0.1.20"


@pytest.fixture(autouse=True)
def no_status_monitors(monkeypatch):
# A real status provider starts monitor tasks that query the database; these tests publish the status
# themselves.
monkeypatch.setattr(AsyncBlueGreenPlugin, "_init_status_provider", lambda self, initial_host_info: None)
yield
AsyncBlueGreenPlugin._reset_for_tests()


def test_async_routings_match_the_endpoints_the_status_provider_builds():
"""Each async routing built with an endpoint of the form the status provider uses matches a host with that
name and port, so the routing applies to connections and calls on that host."""
blue = HostInfo(BLUE_HOST, PORT)
blue_ip = HostInfo(BLUE_IP, PORT)
cases = [
(SubstituteConnectRouting(blue_ip, BLUE_HOST, BlueGreenRole.SOURCE, (blue,)), HostInfo(BLUE_HOST)),
(SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (blue,)), blue),
# A host name given in upper case still has a role, since the role lookup ignores case.
(SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (blue,)),
HostInfo(BLUE_HOST.upper(), PORT)),
(SuspendUntilCorrespondingHostFoundConnectRouting(BLUE_HOST, BlueGreenRole.SOURCE, BG_ID), HostInfo(BLUE_HOST)),
(SuspendUntilCorrespondingHostFoundConnectRouting(f"{BLUE_HOST}:{PORT}", None, BG_ID), blue),
(SuspendConnectRouting(BLUE_IP, None, BG_ID), HostInfo(BLUE_IP)),
(SuspendConnectRouting(f"{BLUE_IP}:{PORT}", None, BG_ID), blue_ip),
(SuspendExecuteRouting(BLUE_IP, None, BG_ID), HostInfo(BLUE_IP)),
(SuspendExecuteRouting(f"{BLUE_IP}:{PORT}", None, BG_ID), blue_ip),
]

misses = [f"{type(routing).__name__} for {host_info.get_host_and_port()}"
for routing, host_info in cases if not routing.is_match(host_info, BlueGreenRole.SOURCE)]
assert misses == [], f"C6: {len(misses)} of {len(cases)} routings did not match the host they name: {misses}"


def test_async_routings_do_not_match_another_host_port_or_role():
"""An async routing with an endpoint doesn't match another host, the same host on another port, a host in the
other role, or no host; a routing without an endpoint doesn't match the other role."""
routing = SubstituteConnectRouting(
HostInfo(GREEN_IP, PORT), f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (HostInfo(BLUE_HOST, PORT),))

assert routing.is_match(HostInfo(GREEN_HOST, PORT), BlueGreenRole.SOURCE) is False
assert routing.is_match(HostInfo(BLUE_HOST, PORT + 1), BlueGreenRole.SOURCE) is False
assert routing.is_match(HostInfo(BLUE_HOST, PORT), BlueGreenRole.TARGET) is False
assert routing.is_match(None, BlueGreenRole.SOURCE) is False
assert SuspendConnectRouting(BLUE_IP, None, BG_ID).is_match(HostInfo(GREEN_IP), BlueGreenRole.SOURCE) is False
assert SuspendExecuteRouting(None, BlueGreenRole.SOURCE, BG_ID).is_match(
HostInfo(GREEN_HOST, PORT), BlueGreenRole.TARGET) is False


# If a routing returns no connection, the connect loop tries again for as long as the status stays the same,
# which here is for ever; the timeout ends such a call.
@pytest.mark.timeout(20)
def test_async_connect_during_post_goes_to_the_green_ip():
"""During POST, a new async connection to the blue host and port is opened to the green host's IP address that
the substitute routing names, instead of to the blue name, which DNS may still resolve to blue."""
green_ip = HostInfo(GREEN_IP, PORT)
iam_hosts = (HostInfo(GREEN_HOST, PORT), HostInfo(BLUE_HOST, PORT))
status = BlueGreenStatus(
BG_ID,
BlueGreenPhase.POST,
connect_routings=[
SubstituteConnectRouting(green_ip, BLUE_HOST, BlueGreenRole.SOURCE, iam_hosts),
SubstituteConnectRouting(green_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, iam_hosts),
RejectConnectRouting(None, BlueGreenRole.TARGET),
],
role_by_host={BLUE_HOST: BlueGreenRole.SOURCE, GREEN_HOST: BlueGreenRole.TARGET})
plugin_service = MagicMock()
plugin_service.network_bound_methods = set()
plugin_service.get_status.return_value = status
# Each fake connection remembers the host it was opened to: a routing opens the host it is given through the
# plugin service, and connect_func opens the host the caller asked for.
plugin_service.connect = AsyncMock(
side_effect=lambda target_host, props, plugin_to_skip=None: SimpleNamespace(host=target_host.host))
plugin = AsyncBlueGreenPlugin(plugin_service, Properties())

conn = asyncio.run(plugin.connect(
target_driver_func=MagicMock(),
driver_dialect=MagicMock(),
host_info=HostInfo(BLUE_HOST, PORT),
props=Properties(),
is_initial_connection=True,
connect_func=AsyncMock(return_value=SimpleNamespace(host=BLUE_HOST))))

assert conn.host == GREEN_IP, \
f"C6: async connect() during POST opened '{conn.host}' instead of the green IP '{GREEN_IP}'"
Loading
Loading