Skip to content

Commit 0d3cd0f

Browse files
committed
feat: fastest response strategy plugin
1 parent 8ba0909 commit 0d3cd0f

8 files changed

+404
-5
lines changed

aws_advanced_python_wrapper/driver_dialect.py

+10
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,13 @@ def unwrap_connection(self, conn_obj: object) -> Any:
152152

153153
def transfer_session_state(self, from_conn: Connection, to_conn: Connection):
154154
return
155+
156+
def ping(self, conn: Connection) -> bool:
157+
try:
158+
with conn.cursor() as cursor:
159+
query = "SELECT 1"
160+
self.execute("Cursor.execute", lambda: cursor.execute(query), query, exec_timeout=10)
161+
cursor.fetchone()
162+
return True
163+
except Exception:
164+
return False
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,330 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License").
4+
# You may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from abc import abstractmethod
18+
from concurrent.futures import Executor, ThreadPoolExecutor
19+
from copy import copy
20+
from dataclasses import dataclass
21+
from datetime import datetime
22+
from logging import Logger
23+
from threading import Event, Lock
24+
from time import sleep, time
25+
from typing import (TYPE_CHECKING, Callable, ClassVar, Dict, Optional, Set,
26+
Tuple)
27+
28+
from aws_advanced_python_wrapper.errors import AwsWrapperError
29+
from aws_advanced_python_wrapper.hostselector import RandomHostSelector
30+
from aws_advanced_python_wrapper.plugin import Plugin
31+
from aws_advanced_python_wrapper.utils.cache_map import CacheMap
32+
from aws_advanced_python_wrapper.utils.messages import Messages
33+
from aws_advanced_python_wrapper.utils.properties import (Properties,
34+
WrapperProperties)
35+
from aws_advanced_python_wrapper.utils.sliding_expiration_cache import \
36+
SlidingExpirationCacheWithCleanupThread
37+
38+
if TYPE_CHECKING:
39+
from aws_advanced_python_wrapper.driver_dialect import DriverDialect
40+
from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole
41+
from aws_advanced_python_wrapper.pep249 import Connection
42+
from aws_advanced_python_wrapper.plugin_service import PluginService
43+
from aws_advanced_python_wrapper.utils.notifications import HostEvent
44+
45+
logger = Logger(__name__)
46+
47+
48+
class FastestResponseStrategyPlugin(Plugin):
49+
_FASTEST_RESPONSE_STRATEGY_NAME = "fastest_response"
50+
_SUBSCRIBED_METHODS: Set[str] = {"accepts_strategy",
51+
"get_host_info_by_strategy",
52+
"notify_host_list_changed"}
53+
54+
def __init__(self, plugin_service: PluginService, props: Properties, host_response_time_service: Optional[HostResponseTimeService] = None):
55+
self._plugin_service = plugin_service
56+
self._properties = props
57+
self._host_response_time_service: Optional[HostResponseTimeService] = host_response_time_service
58+
self._cache_expiration_millis = WrapperProperties.RESPONSE_MEASUREMENT_INTERVAL_MILLIS.get_int(props)
59+
self._cached_fastest_response_host_by_role: CacheMap[str, HostInfo] = CacheMap()
60+
self._random_host_selector = RandomHostSelector()
61+
self._hosts: Tuple[HostInfo, ...] = ()
62+
63+
@property
64+
def subscribed_methods(self) -> Set[str]:
65+
return self._SUBSCRIBED_METHODS
66+
67+
def connect(
68+
self,
69+
target_driver_func: Callable,
70+
driver_dialect: DriverDialect,
71+
host_info: HostInfo,
72+
props: Properties,
73+
is_initial_connection: bool,
74+
connect_func: Callable) -> Connection:
75+
return self._connect(host_info, props, is_initial_connection, connect_func)
76+
77+
def force_connect(
78+
self,
79+
target_driver_func: Callable,
80+
driver_dialect: DriverDialect,
81+
host_info: HostInfo,
82+
props: Properties,
83+
is_initial_connection: bool,
84+
force_connect_func: Callable) -> Connection:
85+
return self._connect(host_info, props, is_initial_connection, force_connect_func)
86+
87+
def _connect(
88+
self,
89+
host: HostInfo,
90+
properties: Properties,
91+
is_initial_connection: bool,
92+
connect_func: Callable) -> Connection:
93+
conn = connect_func()
94+
95+
if is_initial_connection:
96+
self._plugin_service.refresh_host_list(conn)
97+
98+
return conn
99+
100+
def accepts_strategy(self, role: HostRole, strategy: str) -> bool:
101+
return strategy == FastestResponseStrategyPlugin._FASTEST_RESPONSE_STRATEGY_NAME
102+
103+
def get_host_info_by_strategy(self, role: HostRole, strategy: str) -> HostInfo:
104+
if not self.accepts_strategy(role, strategy):
105+
raise AwsWrapperError(Messages.get_formatted("DriverConnectionProvider.UnsupportedStrategy", strategy))
106+
107+
fastest_response_host: Optional[HostInfo] = self._cached_fastest_response_host_by_role.get(role.name)
108+
if fastest_response_host is not None:
109+
110+
# Found a fastest host. Let's find it in the the latest topology.
111+
for host in self._plugin_service.hosts:
112+
if host == fastest_response_host:
113+
# found the fastest host in the topology
114+
return host
115+
# It seems that the fastest cached host isn't in the latest topology.
116+
# Let's ignore cached results and find the fastest host.
117+
118+
# Cached result isn't available. Need to find the fastest response time host.
119+
host_dict = {}
120+
for host in self._plugin_service.hosts:
121+
if role == host.role and self._host_response_time_service is not None:
122+
response_time_tuple = FastestResponseStrategyPlugin.ResponseTimeTuple(host,
123+
self._host_response_time_service.get_response_time(host))
124+
host_dict[response_time_tuple.host_info] = response_time_tuple.response_time
125+
# sort by response time then retrieve the first host
126+
sorted_host_dict = dict(sorted(host_dict.items(), key=lambda item: item[1]))
127+
calculated_fastest_response_host: HostInfo = next(iter(sorted_host_dict.keys()))
128+
if calculated_fastest_response_host is None:
129+
return self._random_host_selector.get_host(self._plugin_service.hosts, role, self._properties)
130+
131+
self._cached_fastest_response_host_by_role.put(role.name, calculated_fastest_response_host, self._cache_expiration_millis)
132+
133+
return calculated_fastest_response_host
134+
135+
def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]):
136+
self._hosts = self._plugin_service.hosts
137+
if self._host_response_time_service:
138+
self._host_response_time_service.set_hosts(self._hosts)
139+
140+
@dataclass
141+
class ResponseTimeTuple:
142+
host_info: HostInfo
143+
response_time: int
144+
145+
146+
class FastestResponseStrategyPluginFactory:
147+
148+
def get_instance(self, plugin_service: PluginService, props: Properties) -> Plugin:
149+
return FastestResponseStrategyPlugin(plugin_service, props)
150+
151+
152+
class HostResponseTimeMonitor:
153+
154+
_MONITORING_PROPERTY_PREFIX: str = "frt-"
155+
_NUM_OF_MEASURES: int = 5
156+
157+
def __init__(self, plugin_service: PluginService, host_info: HostInfo, props: Properties, interval_ms: int):
158+
self._plugin_service = plugin_service
159+
self._host_info = host_info
160+
self._properties = props
161+
self._interval_ms = interval_ms
162+
163+
self._response_time: int = 0
164+
self._check_timestamp = datetime.now()
165+
self._lock: Lock = Lock()
166+
self._monitoring_conn: Optional[Connection] = None
167+
self._is_stopped: Event = Event()
168+
169+
self._host_id: Optional[str] = self._host_info.host_id
170+
if self._host_id is None or self._host_id == "":
171+
self._host_id = self._host_info.host
172+
173+
self._executor: Executor = ThreadPoolExecutor(thread_name_prefix="HostResponseTimeMonitorExecutor")
174+
175+
@property
176+
def response_time(self):
177+
return self._response_time
178+
179+
@response_time.setter
180+
def response_time(self, response_time: int):
181+
self._response_time = response_time
182+
183+
@property
184+
def check_timestamp(self):
185+
return self._check_timestamp
186+
187+
@check_timestamp.setter
188+
def check_timestamp(self, check_timestamp: datetime):
189+
self._check_timestamp = check_timestamp
190+
191+
@property
192+
def host_info(self):
193+
return self._host_info
194+
195+
@property
196+
def is_stopped(self):
197+
return self._is_stopped.is_set()
198+
199+
def close(self):
200+
self._is_stopped.set()
201+
202+
self._executor.shutdown(wait=True)
203+
logger.debug("HostResponseTimeMonitor.Stopped", self._host_info.host)
204+
205+
def _get_current_time(self):
206+
return time()
207+
208+
def run(self):
209+
try:
210+
while not self.is_stopped:
211+
try:
212+
self._open_connection()
213+
214+
if self._monitoring_conn is not None:
215+
216+
response_time_sum = 0
217+
count = 0
218+
for i in range(self._NUM_OF_MEASURES):
219+
if self._is_stopped:
220+
break
221+
start_time = self._get_current_time()
222+
if self._plugin_service.driver_dialect.ping(self._monitoring_conn):
223+
calculated_response_time = self._get_current_time() - start_time
224+
response_time_sum = response_time_sum + calculated_response_time
225+
count = count + 1
226+
227+
if count > 0:
228+
self.response_time = response_time_sum / count / 1000
229+
else:
230+
self.response_time = 2 ^ 31
231+
self.check_timestamp = self._get_current_time()
232+
logger.debug("HostResponseTimeMonitor.ResponseTime", self._host_info.host, self._response_time)
233+
234+
sleep(self._interval_ms/1000)
235+
236+
except InterruptedError:
237+
# exit thread
238+
logger.debug("HostResponseTimeMonitor.InterruptedExceptionDuringMonitoring", self._host_info.host)
239+
except Exception as e:
240+
# this should not be reached; log and exit thread
241+
logger.debug("HostResponseTimeMonitor.ExceptionDuringMonitoringStop",
242+
self._host_info.host,
243+
e) # print full trace stack of the exception.
244+
finally:
245+
self._is_stopped.set()
246+
if self._monitoring_conn is not None:
247+
try:
248+
self._monitoring_conn.close()
249+
except Exception:
250+
# Do nothing
251+
pass
252+
253+
def _open_connection(self):
254+
try:
255+
driver_dialect = self._plugin_service.driver_dialect
256+
if self._monitoring_conn is None or driver_dialect.is_closed(self._monitoring_conn):
257+
monitoring_conn_properties: Properties = copy(self._properties)
258+
for key, value in self._properties.items():
259+
if key.startswith(self._MONITORING_PROPERTY_PREFIX):
260+
monitoring_conn_properties[key[len(self._MONITORING_PROPERTY_PREFIX):len(key)]] = value
261+
monitoring_conn_properties.pop(key, None)
262+
263+
logger.debug("HostResponseTimeMonitor.OpeningConnection", self._host_info.url)
264+
self._monitoring_conn = self._plugin_service.force_connect(self._host_info, monitoring_conn_properties, None)
265+
logger.debug("HostResponseTimeMonitor.OpenedConnection", self._host_info.url)
266+
267+
except Exception:
268+
if self._monitoring_conn is not None:
269+
try:
270+
self._monitoring_conn.close()
271+
except Exception:
272+
pass # ignore
273+
274+
self._monitoring_conn = None
275+
276+
277+
class HostResponseTimeService:
278+
279+
@abstractmethod
280+
def get_response_time(self, host_info: HostInfo) -> int:
281+
"""
282+
Return a response time in milliseconds to the host.
283+
Return 2 ^ 31 if response time is not available.
284+
285+
@param hostSpec the host details
286+
@return response time in milliseconds for a desired host. It should return 2 ^ 31
287+
if response time couldn't be measured.
288+
"""
289+
...
290+
291+
@abstractmethod
292+
def set_hosts(self, hosts: Tuple[HostInfo, ...]) -> None:
293+
...
294+
295+
296+
class HostResponseTimeServiceImpl(HostResponseTimeService):
297+
_CACHE_EXPIRATION_MILLIS: int = 6 * 10 ^ 5
298+
_CACHE_CLEANUP_NANO: int = 6 * 10 ^ 4
299+
_lock: Lock = Lock()
300+
_monitoring_nodes: ClassVar[SlidingExpirationCacheWithCleanupThread[str, HostResponseTimeMonitor]] = \
301+
SlidingExpirationCacheWithCleanupThread(_CACHE_CLEANUP_NANO,
302+
should_dispose_func=lambda monitor: True,
303+
item_disposal_func=lambda monitor: monitor.close())
304+
305+
def __init__(self, plugin_service: PluginService, props: Properties, interval_ms: int):
306+
self._plugin_service = plugin_service
307+
self._properties = props
308+
self._interval_ms = interval_ms
309+
self._hosts: Tuple[HostInfo, ...] = ()
310+
311+
def get_response_time(self, host_info: HostInfo) -> int:
312+
monitor: Optional[HostResponseTimeMonitor] = HostResponseTimeServiceImpl._monitoring_nodes.get(host_info.url)
313+
if monitor is None:
314+
return 2 ^ 31
315+
return monitor.response_time
316+
317+
def set_hosts(self, hosts: Tuple[HostInfo, ...]) -> None:
318+
old_hosts_dict = {x.url: x for x in hosts}
319+
self._hosts = hosts
320+
321+
for host in self._hosts:
322+
new_host = host if host.url not in old_hosts_dict else None
323+
if new_host:
324+
with self._lock:
325+
self._monitoring_nodes.compute_if_absent(host.url,
326+
lambda _: HostResponseTimeMonitor(
327+
self._plugin_service,
328+
new_host,
329+
self._properties,
330+
self._interval_ms), self._CACHE_EXPIRATION_MILLIS)

aws_advanced_python_wrapper/mysql_driver_dialect.py

+3
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,9 @@ def transfer_session_state(self, from_conn: Connection, to_conn: Connection):
148148
isinstance(to_conn, CMySQLConnection) or isinstance(to_conn, MySQLConnection)):
149149
to_conn.autocommit = from_conn.autocommit
150150

151+
def ping(self, conn: Connection) -> bool:
152+
return not self.is_closed(conn)
153+
151154
def prepare_connect_info(self, host_info: HostInfo, original_props: Properties) -> Properties:
152155
driver_props: Properties = Properties(original_props.copy())
153156
PropertiesUtils.remove_wrapper_props(driver_props)

aws_advanced_python_wrapper/plugin_service.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
from typing import TYPE_CHECKING, ClassVar, List, Type
1818

19+
from aws_advanced_python_wrapper.fastest_response_strategy_plugin import \
20+
FastestResponseStrategyPluginFactory
1921
from aws_advanced_python_wrapper.federated_plugin import \
2022
FederatedAuthPluginFactory
2123

@@ -571,6 +573,7 @@ class PluginManager(CanReleaseResources):
571573
"host_monitoring": HostMonitoringPluginFactory,
572574
"failover": FailoverPluginFactory,
573575
"read_write_splitting": ReadWriteSplittingPluginFactory,
576+
"fastest_response_strategy": FastestResponseStrategyPluginFactory,
574577
"stale_dns": StaleDnsPluginFactory,
575578
"connect_time": ConnectTimePluginFactory,
576579
"execute_time": ExecuteTimePluginFactory,
@@ -589,8 +592,9 @@ class PluginManager(CanReleaseResources):
589592
ReadWriteSplittingPluginFactory: 300,
590593
FailoverPluginFactory: 400,
591594
HostMonitoringPluginFactory: 500,
592-
IamAuthPluginFactory: 600,
593-
AwsSecretsManagerPluginFactory: 700,
595+
FastestResponseStrategyPluginFactory: 600,
596+
IamAuthPluginFactory: 700,
597+
AwsSecretsManagerPluginFactory: 800,
594598
ConnectTimePluginFactory: WEIGHT_RELATIVE_TO_PRIOR_PLUGIN,
595599
ExecuteTimePluginFactory: WEIGHT_RELATIVE_TO_PRIOR_PLUGIN,
596600
DeveloperPluginFactory: WEIGHT_RELATIVE_TO_PRIOR_PLUGIN,

0 commit comments

Comments
 (0)