Skip to content

Commit 024ffe5

Browse files
committed
feat: fastest response strategy plugin
1 parent f6c5331 commit 024ffe5

10 files changed

+697
-5
lines changed

aws_advanced_python_wrapper/driver_dialect.py

Lines changed: 10 additions & 0 deletions
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
Lines changed: 346 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,346 @@
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 copy import copy
18+
from dataclasses import dataclass
19+
from datetime import datetime
20+
from logging import Logger
21+
from threading import Event, Lock, Thread
22+
from time import sleep, time
23+
from typing import (TYPE_CHECKING, Callable, ClassVar, Dict, List, Optional,
24+
Set, Tuple)
25+
26+
from aws_advanced_python_wrapper.errors import AwsWrapperError
27+
from aws_advanced_python_wrapper.hostselector import RandomHostSelector
28+
from aws_advanced_python_wrapper.plugin import Plugin
29+
from aws_advanced_python_wrapper.utils.cache_map import CacheMap
30+
from aws_advanced_python_wrapper.utils.messages import Messages
31+
from aws_advanced_python_wrapper.utils.properties import (Properties,
32+
WrapperProperties)
33+
from aws_advanced_python_wrapper.utils.sliding_expiration_cache import \
34+
SlidingExpirationCacheWithCleanupThread
35+
from aws_advanced_python_wrapper.utils.telemetry.telemetry import (
36+
TelemetryContext, TelemetryFactory, TelemetryGauge, TelemetryTraceLevel)
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+
MAX_VALUE = 2147483647
48+
49+
50+
class FastestResponseStrategyPlugin(Plugin):
51+
_FASTEST_RESPONSE_STRATEGY_NAME = "fastest_response_strategy"
52+
_SUBSCRIBED_METHODS: Set[str] = {"accepts_strategy",
53+
"get_host_info_by_strategy",
54+
"notify_host_list_changed"}
55+
56+
def __init__(self, plugin_service: PluginService, props: Properties):
57+
self._plugin_service = plugin_service
58+
self._properties = props
59+
self._host_response_time_service: Optional[HostResponseTimeService] = \
60+
HostResponseTimeService(plugin_service, props, WrapperProperties.RESPONSE_MEASUREMENT_INTERVAL_MILLIS.get_int(props))
61+
self._cache_expiration_millis = WrapperProperties.RESPONSE_MEASUREMENT_INTERVAL_MILLIS.get_int(props)
62+
self._random_host_selector = RandomHostSelector()
63+
self._cached_fastest_response_host_by_role: CacheMap[str, HostInfo] = CacheMap()
64+
self._hosts: Tuple[HostInfo, ...] = ()
65+
66+
@property
67+
def subscribed_methods(self) -> Set[str]:
68+
return self._SUBSCRIBED_METHODS
69+
70+
def connect(
71+
self,
72+
target_driver_func: Callable,
73+
driver_dialect: DriverDialect,
74+
host_info: HostInfo,
75+
props: Properties,
76+
is_initial_connection: bool,
77+
connect_func: Callable) -> Connection:
78+
return self._connect(host_info, props, is_initial_connection, connect_func)
79+
80+
def force_connect(
81+
self,
82+
target_driver_func: Callable,
83+
driver_dialect: DriverDialect,
84+
host_info: HostInfo,
85+
props: Properties,
86+
is_initial_connection: bool,
87+
force_connect_func: Callable) -> Connection:
88+
return self._connect(host_info, props, is_initial_connection, force_connect_func)
89+
90+
def _connect(
91+
self,
92+
host: HostInfo,
93+
properties: Properties,
94+
is_initial_connection: bool,
95+
connect_func: Callable) -> Connection:
96+
conn = connect_func()
97+
98+
if is_initial_connection:
99+
self._plugin_service.refresh_host_list(conn)
100+
101+
return conn
102+
103+
def accepts_strategy(self, role: HostRole, strategy: str) -> bool:
104+
return strategy == FastestResponseStrategyPlugin._FASTEST_RESPONSE_STRATEGY_NAME
105+
106+
def get_host_info_by_strategy(self, role: HostRole, strategy: str) -> HostInfo:
107+
if not self.accepts_strategy(role, strategy):
108+
raise AwsWrapperError(Messages.get_formatted("DriverConnectionProvider.UnsupportedStrategy", strategy))
109+
110+
fastest_response_host: Optional[HostInfo] = self._cached_fastest_response_host_by_role.get(role.name)
111+
if fastest_response_host is not None:
112+
113+
# Found a fastest host. Let's find it in the the latest topology.
114+
for host in self._plugin_service.hosts:
115+
if host == fastest_response_host:
116+
# found the fastest host in the topology
117+
return host
118+
# It seems that the fastest cached host isn't in the latest topology.
119+
# Let's ignore cached results and find the fastest host.
120+
121+
# Cached result isn't available. Need to find the fastest response time host.
122+
eligible_hosts: List[FastestResponseStrategyPlugin.ResponseTimeTuple] = []
123+
for host in self._plugin_service.hosts:
124+
if role == host.role:
125+
response_time_tuple = FastestResponseStrategyPlugin.ResponseTimeTuple(host,
126+
self._host_response_time_service.get_response_time(host))
127+
print(host.host, self._host_response_time_service.get_response_time(host))
128+
eligible_hosts.append(response_time_tuple)
129+
# Sort by response time then retrieve the first host
130+
sorted_eligible_hosts: List[FastestResponseStrategyPlugin.ResponseTimeTuple] = \
131+
sorted(eligible_hosts, key=lambda x: x.response_time, reverse=True)
132+
calculated_fastest_response_host = sorted_eligible_hosts[0].host_info
133+
if calculated_fastest_response_host is None:
134+
logger.debug("FastestResponseStrategy.RandomHostSelected")
135+
return self._random_host_selector.get_host(self._plugin_service.hosts, role, self._properties)
136+
137+
self._cached_fastest_response_host_by_role.put(role.name,
138+
calculated_fastest_response_host,
139+
self._cache_expiration_millis)
140+
141+
return calculated_fastest_response_host
142+
143+
def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]):
144+
self._hosts = self._plugin_service.hosts
145+
if self._host_response_time_service:
146+
self._host_response_time_service.set_hosts(self._hosts)
147+
148+
@dataclass
149+
class ResponseTimeTuple:
150+
host_info: HostInfo
151+
response_time: int
152+
153+
154+
class FastestResponseStrategyPluginFactory:
155+
156+
def get_instance(self, plugin_service: PluginService, props: Properties) -> Plugin:
157+
return FastestResponseStrategyPlugin(plugin_service, props)
158+
159+
160+
class HostResponseTimeMonitor:
161+
162+
_MONITORING_PROPERTY_PREFIX: str = "frt-"
163+
_NUM_OF_MEASURES: int = 5
164+
165+
def __init__(self, plugin_service: PluginService, host_info: HostInfo, props: Properties, interval_ms: int):
166+
self._plugin_service = plugin_service
167+
self._host_info = host_info
168+
self._properties = props
169+
self._interval_ms = interval_ms
170+
171+
self._telemetry_factory: TelemetryFactory = self._plugin_service.get_telemetry_factory()
172+
self._response_time: int = MAX_VALUE
173+
self._check_timestamp = datetime.now()
174+
self._lock: Lock = Lock()
175+
self._monitoring_conn: Optional[Connection] = None
176+
self._is_stopped: Event = Event()
177+
178+
self._host_id: Optional[str] = self._host_info.host_id
179+
if self._host_id is None or self._host_id == "":
180+
self._host_id = self._host_info.host
181+
182+
self._daemon_thread: Thread = Thread(daemon=True, target=self.run)
183+
184+
# Report current response time (in milliseconds) to telemetry engine.
185+
# Report -1 if response time couldn't be measured.
186+
self._response_time_gauge: TelemetryGauge = \
187+
self._telemetry_factory.create_gauge("frt.response.time." + self._host_id,
188+
lambda: self._response_time if self._response_time != MAX_VALUE else -1)
189+
self._daemon_thread.start()
190+
191+
@property
192+
def response_time(self):
193+
return self._response_time
194+
195+
@response_time.setter
196+
def response_time(self, response_time: int):
197+
self._response_time = response_time
198+
199+
@property
200+
def check_timestamp(self):
201+
return self._check_timestamp
202+
203+
@check_timestamp.setter
204+
def check_timestamp(self, check_timestamp: datetime):
205+
self._check_timestamp = check_timestamp
206+
207+
@property
208+
def host_info(self):
209+
return self._host_info
210+
211+
@property
212+
def is_stopped(self):
213+
return self._is_stopped.is_set()
214+
215+
def close(self):
216+
self._is_stopped.set()
217+
self._daemon_thread.join()
218+
logger.debug("HostResponseTimeMonitor.Stopped", self._host_info.host)
219+
220+
def _get_current_time(self):
221+
return time()
222+
223+
def run(self):
224+
context: TelemetryContext = self._telemetry_factory.open_telemetry_context(
225+
"node response time thread", TelemetryTraceLevel.TOP_LEVEL)
226+
context.set_attribute("url", self._host_info.url)
227+
try:
228+
while not self.is_stopped:
229+
self._open_connection()
230+
231+
if self._monitoring_conn is not None:
232+
233+
response_time_sum = 0
234+
count = 0
235+
for i in range(self._NUM_OF_MEASURES):
236+
if self.is_stopped:
237+
break
238+
start_time = self._get_current_time()
239+
if self._plugin_service.driver_dialect.ping(self._monitoring_conn):
240+
calculated_response_time = self._get_current_time() - start_time
241+
response_time_sum = response_time_sum + calculated_response_time
242+
count = count + 1
243+
244+
if count > 0:
245+
self.response_time = response_time_sum / count / 1000
246+
else:
247+
self.response_time = MAX_VALUE
248+
self.check_timestamp = self._get_current_time()
249+
logger.debug("HostResponseTimeMonitor.ResponseTime", self._host_info.host, self._response_time)
250+
251+
sleep(self._interval_ms/1000)
252+
253+
except InterruptedError:
254+
# exit thread
255+
logger.debug("HostResponseTimeMonitor.InterruptedExceptionDuringMonitoring", self._host_info.host)
256+
except Exception as e:
257+
# this should not be reached; log and exit thread
258+
logger.debug("HostResponseTimeMonitor.ExceptionDuringMonitoringStop",
259+
self._host_info.host,
260+
e) # print full trace stack of the exception.
261+
finally:
262+
self._is_stopped.set()
263+
if self._monitoring_conn is not None:
264+
try:
265+
self._monitoring_conn.close()
266+
except Exception:
267+
# Do nothing
268+
pass
269+
if context is not None:
270+
context.close_context()
271+
272+
def _open_connection(self):
273+
try:
274+
driver_dialect = self._plugin_service.driver_dialect
275+
if self._monitoring_conn is None or driver_dialect.is_closed(self._monitoring_conn):
276+
monitoring_conn_properties: Properties = copy(self._properties)
277+
for key, value in self._properties.items():
278+
if key.startswith(self._MONITORING_PROPERTY_PREFIX):
279+
monitoring_conn_properties[key[len(self._MONITORING_PROPERTY_PREFIX):len(key)]] = value
280+
monitoring_conn_properties.pop(key, None)
281+
282+
logger.debug("HostResponseTimeMonitor.OpeningConnection", self._host_info.url)
283+
self._monitoring_conn = self._plugin_service.force_connect(self._host_info, monitoring_conn_properties, None)
284+
logger.debug("HostResponseTimeMonitor.OpenedConnection", self._host_info.url)
285+
286+
except Exception:
287+
if self._monitoring_conn is not None:
288+
try:
289+
self._monitoring_conn.close()
290+
except Exception:
291+
pass # ignore
292+
293+
self._monitoring_conn = None
294+
295+
296+
class 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: HostResponseTimeService._monitor_close(monitor))
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+
self._telemetry_factory: TelemetryFactory = self._plugin_service.get_telemetry_factory()
311+
self._host_count_gauge: TelemetryGauge = self._telemetry_factory.create_gauge("frt.nodes.count", lambda: len(self._monitoring_nodes))
312+
313+
@property
314+
def hosts(self) -> Tuple[HostInfo, ...]:
315+
return self._hosts
316+
317+
@hosts.setter
318+
def hosts(self, new_hosts: Tuple[HostInfo, ...]):
319+
self._hosts = new_hosts
320+
321+
@staticmethod
322+
def _monitor_close(monitor: HostResponseTimeMonitor):
323+
try:
324+
monitor.close()
325+
except Exception:
326+
pass
327+
328+
def get_response_time(self, host_info: HostInfo) -> int:
329+
monitor: Optional[HostResponseTimeMonitor] = HostResponseTimeService._monitoring_nodes.get(host_info.url)
330+
if monitor is None:
331+
return MAX_VALUE
332+
return monitor.response_time
333+
334+
def set_hosts(self, new_hosts: Tuple[HostInfo, ...]) -> None:
335+
old_hosts_dict = {x.url: x for x in self.hosts}
336+
self.hosts = new_hosts
337+
338+
for host in self.hosts:
339+
if host.url not in old_hosts_dict:
340+
with self._lock:
341+
self._monitoring_nodes.compute_if_absent(host.url,
342+
lambda _: HostResponseTimeMonitor(
343+
self._plugin_service,
344+
host,
345+
self._properties,
346+
self._interval_ms), self._CACHE_EXPIRATION_MILLIS)

aws_advanced_python_wrapper/mysql_driver_dialect.py

Lines changed: 3 additions & 0 deletions
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

Lines changed: 6 additions & 2 deletions
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)