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