generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathdatabase_dialect.py
More file actions
855 lines (692 loc) · 35.2 KB
/
database_dialect.py
File metadata and controls
855 lines (692 loc) · 35.2 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
# 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 typing import (TYPE_CHECKING, Callable, ClassVar, Dict, Optional,
Protocol, Tuple, runtime_checkable)
from aws_advanced_python_wrapper.driver_info import DriverInfo
from aws_advanced_python_wrapper.failover_v2_plugin import FailoverV2Plugin
from aws_advanced_python_wrapper.host_list_provider import (
AuroraTopologyUtils, MonitoringRdsHostListProvider, MultiAzTopologyUtils)
from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType
if TYPE_CHECKING:
from aws_advanced_python_wrapper.pep249 import Connection
from .driver_dialect import DriverDialect
from .exception_handling import ExceptionHandler
from aws_advanced_python_wrapper.plugin_service import PluginService
from abc import ABC, abstractmethod
from concurrent.futures import TimeoutError
from contextlib import closing
from enum import Enum, auto
from aws_advanced_python_wrapper.errors import (AwsWrapperError,
QueryTimeoutError)
from aws_advanced_python_wrapper.host_list_provider import (
ConnectionStringHostListProvider, RdsHostListProvider)
from aws_advanced_python_wrapper.hostinfo import HostInfo
from aws_advanced_python_wrapper.thread_pool_container import \
ThreadPoolContainer
from aws_advanced_python_wrapper.utils.decorators import \
preserve_transaction_status_with_timeout
from aws_advanced_python_wrapper.utils.log import Logger
from aws_advanced_python_wrapper.utils.properties import (Properties,
PropertiesUtils,
WrapperProperties)
from aws_advanced_python_wrapper.utils.rdsutils import RdsUtils
from .driver_dialect_codes import DriverDialectCodes
from .utils.cache_map import CacheMap
from .utils.messages import Messages
from .utils.utils import Utils
logger = Logger(__name__)
class DialectCode(Enum):
# https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/multi-az-db-clusters-concepts.html
MULTI_AZ_CLUSTER_MYSQL = "multi-az-mysql"
AURORA_MYSQL = "aurora-mysql"
RDS_MYSQL = "rds-mysql"
MYSQL = "mysql"
MULTI_AZ_CLUSTER_PG = "multi-az-pg"
AURORA_PG = "aurora-pg"
RDS_PG = "rds-pg"
PG = "pg"
CUSTOM = "custom"
UNKNOWN = "unknown"
@staticmethod
def from_string(value: str) -> DialectCode:
try:
return DialectCode(value)
except ValueError as e:
raise AwsWrapperError(Messages.get_formatted("DialectCode.InvalidStringValue", value), e) from e
class TargetDriverType(Enum):
MYSQL = auto()
POSTGRES = auto()
CUSTOM = auto()
@runtime_checkable
class TopologyAwareDatabaseDialect(Protocol):
_TOPOLOGY_QUERY: str
_HOST_ID_QUERY: str
_IS_READER_QUERY: str
_WRITER_HOST_QUERY: str
@property
def topology_query(self) -> str:
return self._TOPOLOGY_QUERY
@property
def host_id_query(self) -> str:
return self._HOST_ID_QUERY
@property
def is_reader_query(self) -> str:
return self._IS_READER_QUERY
@property
def writer_id_query(self) -> str:
return self._WRITER_HOST_QUERY
@runtime_checkable
class AuroraLimitlessDialect(Protocol):
_LIMITLESS_ROUTER_ENDPOINT_QUERY: str
@property
def limitless_router_endpoint_query(self) -> str:
return self._LIMITLESS_ROUTER_ENDPOINT_QUERY
class DatabaseDialect(Protocol):
"""
Database dialects help the AWS Advanced Python Driver determine what kind of underlying database is being used,
and configure details unique to specific databases.
"""
@property
@abstractmethod
def default_port(self) -> int:
...
@property
@abstractmethod
def host_alias_query(self) -> str:
...
@property
@abstractmethod
def server_version_query(self) -> str:
...
@property
@abstractmethod
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
...
@property
@abstractmethod
def exception_handler(self) -> Optional[ExceptionHandler]:
...
@abstractmethod
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
...
@abstractmethod
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
...
@abstractmethod
def prepare_conn_props(self, props: Properties):
...
class DatabaseDialectProvider(Protocol):
def get_dialect(self, driver_dialect: str, props: Properties) -> Optional[DatabaseDialect]:
"""
Returns the dialect identified by analyzing the AwsWrapperProperties.DIALECT property (if set) or the target
driver method
"""
...
def query_for_dialect(self, url: str, host_info: Optional[HostInfo], conn: Connection,
driver_dialect: DriverDialect) -> Optional[DatabaseDialect]:
"""Returns the dialect identified by querying the database to identify the engine type"""
...
class MysqlDatabaseDialect(DatabaseDialect):
_DIALECT_UPDATE_CANDIDATES: Tuple[DialectCode, ...] = (
DialectCode.AURORA_MYSQL, DialectCode.MULTI_AZ_CLUSTER_MYSQL, DialectCode.RDS_MYSQL)
_exception_handler: Optional[ExceptionHandler] = None
@property
def default_port(self) -> int:
return 3306
@property
def host_alias_query(self) -> str:
return "SELECT CONCAT(@@hostname, ':', @@port)"
@property
def server_version_query(self) -> str:
return "SHOW VARIABLES LIKE 'version_comment'"
@property
def exception_handler(self) -> Optional[ExceptionHandler]:
if MysqlDatabaseDialect._exception_handler is None:
MysqlDatabaseDialect._exception_handler = Utils.initialize_class(
"aws_advanced_python_wrapper.utils.mysql_exception_handler.MySQLExceptionHandler")
return MysqlDatabaseDialect._exception_handler
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return MysqlDatabaseDialect._DIALECT_UPDATE_CANDIDATES
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute(self.server_version_query)
for record in cursor:
if len(record) < 2:
return False
if "mysql" in record[1].lower():
return True
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
return lambda provider_service, props: ConnectionStringHostListProvider(provider_service, props)
def prepare_conn_props(self, props: Properties):
pass
class PgDatabaseDialect(DatabaseDialect):
_DIALECT_UPDATE_CANDIDATES: Tuple[DialectCode, ...] = (
DialectCode.AURORA_PG, DialectCode.MULTI_AZ_CLUSTER_PG, DialectCode.RDS_PG)
_exception_handler: Optional[ExceptionHandler] = None
@property
def default_port(self) -> int:
return 5432
@property
def host_alias_query(self) -> str:
return "SELECT pg_catalog.CONCAT(pg_catalog.inet_server_addr(), ':', pg_catalog.inet_server_port())"
@property
def server_version_query(self) -> str:
return "SELECT 'version', pg_catalog.VERSION()"
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return PgDatabaseDialect._DIALECT_UPDATE_CANDIDATES
@property
def exception_handler(self) -> Optional[ExceptionHandler]:
if PgDatabaseDialect._exception_handler is None:
PgDatabaseDialect._exception_handler = Utils.initialize_class(
"aws_advanced_python_wrapper.utils.pg_exception_handler.SingleAzPgExceptionHandler")
return PgDatabaseDialect._exception_handler
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute('SELECT 1 FROM pg_catalog.pg_proc LIMIT 1')
if cursor.fetchone() is not None:
return True
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
return lambda provider_service, props: ConnectionStringHostListProvider(provider_service, props)
def prepare_conn_props(self, props: Properties):
pass
class BlueGreenDialect(ABC):
@property
@abstractmethod
def blue_green_status_query(self) -> str:
...
@abstractmethod
def is_blue_green_status_available(self, conn: Connection) -> bool:
...
class RdsMysqlDialect(MysqlDatabaseDialect, BlueGreenDialect):
_DIALECT_UPDATE_CANDIDATES = (DialectCode.AURORA_MYSQL, DialectCode.MULTI_AZ_CLUSTER_MYSQL)
_BG_STATUS_QUERY = "SELECT version, endpoint, port, role, status FROM mysql.rds_topology"
_BG_STATUS_EXISTS_QUERY = \
"SELECT 1 AS tmp FROM information_schema.tables WHERE table_schema = 'mysql' AND table_name = 'rds_topology'"
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute(self.server_version_query)
record = cursor.fetchone()
if record is None or len(record) < 2:
return False
if "source distribution" != record[1].lower():
return False
with closing(conn.cursor()) as cursor:
cursor.execute("SHOW VARIABLES LIKE 'report_host'")
record = cursor.fetchone()
if record is None or len(record) < 2:
return False
report_host = record[1]
return report_host is not None and report_host != ""
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return RdsMysqlDialect._DIALECT_UPDATE_CANDIDATES
@property
def blue_green_status_query(self) -> str:
return RdsMysqlDialect._BG_STATUS_QUERY
def is_blue_green_status_available(self, conn: Connection) -> bool:
try:
with closing(conn.cursor()) as cursor:
cursor.execute(RdsMysqlDialect._BG_STATUS_EXISTS_QUERY)
return cursor.fetchone() is not None
except Exception:
return False
class RdsPgDialect(PgDatabaseDialect, BlueGreenDialect):
_EXTENSIONS_QUERY = ("SELECT (setting LIKE '%rds_tools%') AS rds_tools, "
"(setting LIKE '%aurora_stat_utils%') AS aurora_stat_utils "
"FROM pg_catalog.pg_settings "
"WHERE name OPERATOR(pg_catalog.=) 'rds.extensions'")
_DIALECT_UPDATE_CANDIDATES = (DialectCode.AURORA_PG, DialectCode.MULTI_AZ_CLUSTER_PG)
_BG_STATUS_QUERY = (f"SELECT version, endpoint, port, role, status "
f"FROM rds_tools.show_topology('aws_advanced_python_wrapper-{DriverInfo.DRIVER_VERSION}')")
_BG_STATUS_EXISTS_QUERY = "SELECT 'rds_tools.show_topology'::regproc"
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
if not super().is_dialect(conn, driver_dialect):
return False
try:
with closing(conn.cursor()) as cursor:
cursor.execute(RdsPgDialect._EXTENSIONS_QUERY)
for row in cursor:
rds_tools = bool(row[0])
aurora_utils = bool(row[1])
logger.debug(
"RdsPgDialect.RdsToolsAuroraUtils", str(rds_tools), str(aurora_utils))
if rds_tools and not aurora_utils:
return True
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return RdsPgDialect._DIALECT_UPDATE_CANDIDATES
@property
def blue_green_status_query(self) -> str:
return RdsPgDialect._BG_STATUS_QUERY
def is_blue_green_status_available(self, conn: Connection) -> bool:
try:
with closing(conn.cursor()) as cursor:
cursor.execute(RdsPgDialect._BG_STATUS_EXISTS_QUERY)
return cursor.fetchone() is not None
except Exception:
return False
class AuroraMysqlDialect(MysqlDatabaseDialect, TopologyAwareDatabaseDialect, BlueGreenDialect):
_DIALECT_UPDATE_CANDIDATES = (DialectCode.MULTI_AZ_CLUSTER_MYSQL,)
_TOPOLOGY_QUERY = ("SELECT SERVER_ID, CASE WHEN SESSION_ID = 'MASTER_SESSION_ID' THEN TRUE ELSE FALSE END, "
"CPU, REPLICA_LAG_IN_MILLISECONDS, LAST_UPDATE_TIMESTAMP "
"FROM information_schema.replica_host_status "
"WHERE time_to_sec(timediff(now(), LAST_UPDATE_TIMESTAMP)) <= 300 "
"OR SESSION_ID = 'MASTER_SESSION_ID' ")
_HOST_ID_QUERY = "SELECT @@aurora_server_id"
_IS_READER_QUERY = "SELECT @@innodb_read_only"
_WRITER_HOST_QUERY = \
("SELECT SERVER_ID FROM information_schema.replica_host_status "
"WHERE SESSION_ID = 'MASTER_SESSION_ID' AND SERVER_ID = @@aurora_server_id")
_BG_STATUS_QUERY = "SELECT version, endpoint, port, role, status FROM mysql.rds_topology"
_BG_STATUS_EXISTS_QUERY = \
"SELECT 1 AS tmp FROM information_schema.tables WHERE table_schema = 'mysql' AND table_name = 'rds_topology'"
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return AuroraMysqlDialect._DIALECT_UPDATE_CANDIDATES
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute("SHOW VARIABLES LIKE 'aurora_version'")
# If variable with such a name is presented then it means it's an Aurora cluster
if cursor.fetchone() is not None:
return True
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
if plugin_service.is_plugin_in_use(FailoverV2Plugin):
return lambda provider_service, props: MonitoringRdsHostListProvider(
provider_service,
props, AuroraTopologyUtils(self, props),
plugin_service)
return lambda provider_service, props: RdsHostListProvider(provider_service, props, AuroraTopologyUtils(self, props))
@property
def blue_green_status_query(self) -> str:
return AuroraMysqlDialect._BG_STATUS_QUERY
def is_blue_green_status_available(self, conn: Connection) -> bool:
try:
with closing(conn.cursor()) as cursor:
cursor.execute(AuroraMysqlDialect._BG_STATUS_EXISTS_QUERY)
return cursor.fetchone() is not None
except Exception:
return False
class AuroraPgDialect(PgDatabaseDialect, TopologyAwareDatabaseDialect, AuroraLimitlessDialect, BlueGreenDialect):
_DIALECT_UPDATE_CANDIDATES: Tuple[DialectCode, ...] = (DialectCode.MULTI_AZ_CLUSTER_PG,)
_EXTENSIONS_QUERY = "SELECT (setting LIKE '%aurora_stat_utils%') AS aurora_stat_utils " \
"FROM pg_catalog.pg_settings WHERE name OPERATOR(pg_catalog.=) 'rds.extensions'"
_HAS_TOPOLOGY_QUERY = "SELECT 1 FROM pg_catalog.aurora_replica_status() LIMIT 1"
_TOPOLOGY_QUERY = \
("SELECT SERVER_ID, CASE WHEN SESSION_ID OPERATOR(pg_catalog.=) 'MASTER_SESSION_ID' THEN TRUE ELSE FALSE END, "
"CPU, COALESCE(REPLICA_LAG_IN_MSEC, 0), LAST_UPDATE_TIMESTAMP "
"FROM pg_catalog.aurora_replica_status() "
"WHERE EXTRACT(EPOCH FROM(pg_catalog.NOW() OPERATOR(pg_catalog.-) LAST_UPDATE_TIMESTAMP)) OPERATOR(pg_catalog.<=) 300 "
"OR SESSION_ID OPERATOR(pg_catalog.=) 'MASTER_SESSION_ID' "
"OR LAST_UPDATE_TIMESTAMP IS NULL")
_HOST_ID_QUERY = "SELECT pg_catalog.aurora_db_instance_identifier()"
_IS_READER_QUERY = "SELECT pg_catalog.pg_is_in_recovery()"
_LIMITLESS_ROUTER_ENDPOINT_QUERY = "SELECT router_endpoint, load FROM pg_catalog.aurora_limitless_router_endpoints()"
_BG_STATUS_QUERY = (f"SELECT version, endpoint, port, role, status "
f"FROM pg_catalog.get_blue_green_fast_switchover_metadata('aws_advanced_python_wrapper-{DriverInfo.DRIVER_VERSION}')")
_BG_STATUS_EXISTS_QUERY = "SELECT 'pg_catalog.get_blue_green_fast_switchover_metadata'::regproc"
_WRITER_HOST_QUERY = \
("SELECT SERVER_ID FROM pg_catalog.aurora_replica_status() "
"WHERE SESSION_ID OPERATOR(pg_catalog.=) 'MASTER_SESSION_ID' "
"AND SERVER_ID OPERATOR(pg_catalog.=) pg_catalog.aurora_db_instance_identifier()")
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return AuroraPgDialect._DIALECT_UPDATE_CANDIDATES
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
if not super().is_dialect(conn, driver_dialect):
return False
has_extensions: bool = False
has_topology: bool = False
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute(self._EXTENSIONS_QUERY)
row = cursor.fetchone()
if row and bool(row[0]):
logger.debug("AuroraPgDialect.HasExtensionsTrue")
has_extensions = True
with closing(conn.cursor()) as cursor:
cursor.execute(self._HAS_TOPOLOGY_QUERY)
if cursor.fetchone() is not None:
logger.debug("AuroraPgDialect.HasTopologyTrue")
has_topology = True
return has_extensions and has_topology
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
if plugin_service.is_plugin_in_use(FailoverV2Plugin):
return lambda provider_service, props: MonitoringRdsHostListProvider(
provider_service,
props,
AuroraTopologyUtils(self, props), plugin_service)
return lambda provider_service, props: RdsHostListProvider(provider_service, props, AuroraTopologyUtils(self, props))
@property
def blue_green_status_query(self) -> str:
return AuroraPgDialect._BG_STATUS_QUERY
def is_blue_green_status_available(self, conn: Connection) -> bool:
try:
with closing(conn.cursor()) as cursor:
cursor.execute(AuroraPgDialect._BG_STATUS_EXISTS_QUERY)
return cursor.fetchone() is not None
except Exception:
return False
class MultiAzClusterMysqlDialect(MysqlDatabaseDialect, TopologyAwareDatabaseDialect):
_TOPOLOGY_QUERY = "SELECT id, endpoint, port FROM mysql.rds_topology"
_WRITER_HOST_QUERY = "SHOW REPLICA STATUS"
_WRITER_HOST_COLUMN_INDEX = 39
_HOST_ID_QUERY = "SELECT @@server_id"
_IS_READER_QUERY = "SELECT @@read_only"
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return None
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute(MultiAzClusterMysqlDialect._TOPOLOGY_QUERY)
records = cursor.fetchall()
if not records:
return False
with closing(conn.cursor()) as cursor:
cursor.execute("SHOW VARIABLES LIKE 'report_host'")
record = cursor.fetchone()
if record is None or len(record) < 2:
return False
report_host = record[1]
return report_host is not None and report_host != ""
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
if plugin_service.is_plugin_in_use(FailoverV2Plugin):
return lambda provider_service, props: MonitoringRdsHostListProvider(
provider_service, props,
MultiAzTopologyUtils(self, props, self._WRITER_HOST_QUERY, self._WRITER_HOST_COLUMN_INDEX), plugin_service)
return lambda provider_service, props: RdsHostListProvider(
provider_service,
props,
MultiAzTopologyUtils(self, props, self._WRITER_HOST_QUERY, self._WRITER_HOST_COLUMN_INDEX))
def prepare_conn_props(self, props: Properties):
# These props are added for RDS metrics purposes, they are not required for functional correctness.
# The "conn_attrs" property value is specified as a dict.
extra_conn_attrs = {
"python_wrapper_name": "aws_python_driver",
"python_wrapper_version": DriverInfo.DRIVER_VERSION}
conn_attrs = props.get("conn_attrs")
if conn_attrs is None:
props["conn_attrs"] = extra_conn_attrs
else:
props["conn_attrs"].update(extra_conn_attrs)
class MultiAzClusterPgDialect(PgDatabaseDialect, TopologyAwareDatabaseDialect):
# The driver name passed to show_topology is used for RDS metrics purposes.
# It is not required for functional correctness.
_TOPOLOGY_QUERY = \
f"SELECT id, endpoint, port FROM rds_tools.show_topology('aws_python_driver-{DriverInfo.DRIVER_VERSION}')"
_WRITER_HOST_QUERY = \
"SELECT multi_az_db_cluster_source_dbi_resource_id FROM rds_tools.multi_az_db_cluster_source_dbi_resource_id()"
_HOST_ID_QUERY = "SELECT dbi_resource_id FROM rds_tools.dbi_resource_id()"
_IS_READER_QUERY = "SELECT pg_catalog.pg_is_in_recovery()"
_exception_handler: Optional[ExceptionHandler] = None
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return None
@property
def exception_handler(self) -> Optional[ExceptionHandler]:
if MultiAzClusterPgDialect._exception_handler is None:
MultiAzClusterPgDialect._exception_handler = Utils.initialize_class(
"aws_advanced_python_wrapper.utils.pg_exception_handler.MultiAzPgExceptionHandler")
return MultiAzClusterPgDialect._exception_handler
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
initial_transaction_status: bool = driver_dialect.is_in_transaction(conn)
try:
with closing(conn.cursor()) as cursor:
cursor.execute(MultiAzClusterPgDialect._WRITER_HOST_QUERY)
record = cursor.fetchone()
if record is not None and len(record) > 0 and bool(record[0]):
return True
except Exception:
if not initial_transaction_status and driver_dialect.is_in_transaction(conn):
conn.rollback()
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
if plugin_service.is_plugin_in_use(FailoverV2Plugin):
return lambda provider_service, props: MonitoringRdsHostListProvider(
provider_service, props,
MultiAzTopologyUtils(self, props, self._WRITER_HOST_QUERY), plugin_service)
return lambda provider_service, props: RdsHostListProvider(
provider_service,
props,
MultiAzTopologyUtils(self, props, self._WRITER_HOST_QUERY))
class UnknownDatabaseDialect(DatabaseDialect):
_DIALECT_UPDATE_CANDIDATES: Optional[Tuple[DialectCode, ...]] = \
(DialectCode.MYSQL,
DialectCode.PG,
DialectCode.RDS_MYSQL,
DialectCode.RDS_PG,
DialectCode.AURORA_MYSQL,
DialectCode.AURORA_PG,
DialectCode.MULTI_AZ_CLUSTER_MYSQL,
DialectCode.MULTI_AZ_CLUSTER_PG)
@property
def default_port(self) -> int:
return HostInfo.NO_PORT
@property
def host_alias_query(self) -> str:
return ""
@property
def server_version_query(self) -> str:
return ""
@property
def dialect_update_candidates(self) -> Optional[Tuple[DialectCode, ...]]:
return UnknownDatabaseDialect._DIALECT_UPDATE_CANDIDATES
@property
def exception_handler(self) -> Optional[ExceptionHandler]:
return None
def is_dialect(self, conn: Connection, driver_dialect: DriverDialect) -> bool:
return False
def get_host_list_provider_supplier(self, plugin_service: PluginService) -> Callable:
return lambda provider_service, props: ConnectionStringHostListProvider(provider_service, props)
def prepare_conn_props(self, props: Properties):
pass
class DatabaseDialectManager(DatabaseDialectProvider):
_ENDPOINT_CACHE_EXPIRATION_NS = 30 * 60_000_000_000 # 30 minutes
_known_endpoint_dialects: CacheMap[str, DialectCode] = CacheMap()
_custom_dialect: Optional[DatabaseDialect] = None
_executor_name: ClassVar[str] = "DatabaseDialectManagerExecutor"
_known_dialects_by_code: Dict[DialectCode, DatabaseDialect] = {
DialectCode.MYSQL: MysqlDatabaseDialect(),
DialectCode.RDS_MYSQL: RdsMysqlDialect(),
DialectCode.AURORA_MYSQL: AuroraMysqlDialect(),
DialectCode.MULTI_AZ_CLUSTER_MYSQL: MultiAzClusterMysqlDialect(),
DialectCode.PG: PgDatabaseDialect(),
DialectCode.RDS_PG: RdsPgDialect(),
DialectCode.AURORA_PG: AuroraPgDialect(),
DialectCode.MULTI_AZ_CLUSTER_PG: MultiAzClusterPgDialect(),
DialectCode.UNKNOWN: UnknownDatabaseDialect()
}
def __init__(self, props: Properties, rds_helper: Optional[RdsUtils] = None):
self._props: Properties = props
self._rds_helper: RdsUtils = rds_helper if rds_helper else RdsUtils()
self._can_update: bool = False
self._dialect: DatabaseDialect = UnknownDatabaseDialect()
self._dialect_code: DialectCode = DialectCode.UNKNOWN
self._thread_pool = ThreadPoolContainer.get_thread_pool(self._executor_name)
@staticmethod
def get_custom_dialect():
return DatabaseDialectManager._custom_dialect
@staticmethod
def set_custom_dialect(dialect: DatabaseDialect):
DatabaseDialectManager._custom_dialect = dialect
@staticmethod
def reset_custom_dialect():
DatabaseDialectManager._custom_dialect = None
def reset_endpoint_cache(self):
DatabaseDialectManager._known_endpoint_dialects.clear()
def get_dialect(self, driver_dialect: str, props: Properties) -> DatabaseDialect:
self._can_update = False
if self._custom_dialect is not None:
self._dialect_code = DialectCode.CUSTOM
self._dialect = self._custom_dialect
self._log_current_dialect()
return self._dialect
user_dialect_setting: Optional[str] = WrapperProperties.DIALECT.get(props)
url = PropertiesUtils.get_url(props)
if user_dialect_setting is None:
dialect_code = DatabaseDialectManager._known_endpoint_dialects.get(url)
else:
dialect_code = DialectCode.from_string(user_dialect_setting)
if dialect_code is not None:
dialect: Optional[DatabaseDialect] = DatabaseDialectManager._known_dialects_by_code.get(dialect_code)
if dialect:
self._dialect_code = dialect_code
self._dialect = dialect
self._log_current_dialect()
return dialect
else:
raise AwsWrapperError(
Messages.get_formatted("DatabaseDialectManager.UnknownDialectCode", str(dialect_code)))
host: str = props["host"]
target_driver_type: TargetDriverType = self._get_target_driver_type(driver_dialect)
if target_driver_type is TargetDriverType.MYSQL:
rds_type = self._rds_helper.identify_rds_type(host)
if rds_type.is_rds_cluster:
self._can_update = True
self._dialect_code = DialectCode.AURORA_MYSQL
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.AURORA_MYSQL]
return self._dialect
if rds_type.is_rds:
self._can_update = True
self._dialect_code = DialectCode.RDS_MYSQL
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.RDS_MYSQL]
self._log_current_dialect()
return self._dialect
self._can_update = True
self._dialect_code = DialectCode.MYSQL
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.MYSQL]
self._log_current_dialect()
return self._dialect
if target_driver_type is TargetDriverType.POSTGRES:
rds_type = self._rds_helper.identify_rds_type(host)
if rds_type == RdsUrlType.RDS_AURORA_LIMITLESS_DB_SHARD_GROUP:
self._can_update = False
self._dialect_code = DialectCode.AURORA_PG
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.AURORA_PG]
return self._dialect
if rds_type.is_rds_cluster:
self._can_update = True
self._dialect_code = DialectCode.AURORA_PG
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.AURORA_PG]
return self._dialect
if rds_type.is_rds:
self._can_update = True
self._dialect_code = DialectCode.RDS_PG
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.RDS_PG]
self._log_current_dialect()
return self._dialect
self._can_update = True
self._dialect_code = DialectCode.PG
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.PG]
self._log_current_dialect()
return self._dialect
self._can_update = True
self._dialect_code = DialectCode.UNKNOWN
self._dialect = DatabaseDialectManager._known_dialects_by_code[DialectCode.UNKNOWN]
self._log_current_dialect()
return self._dialect
def _get_target_driver_type(self, driver_dialect: str) -> TargetDriverType:
if driver_dialect == DriverDialectCodes.PSYCOPG:
return TargetDriverType.POSTGRES
if driver_dialect == DriverDialectCodes.MYSQL_CONNECTOR_PYTHON:
return TargetDriverType.MYSQL
return TargetDriverType.CUSTOM
def query_for_dialect(self, url: str, host_info: Optional[HostInfo], conn: Connection,
driver_dialect: DriverDialect) -> DatabaseDialect:
if not self._can_update:
self._log_current_dialect()
return self._dialect
dialect_candidates = self._dialect.dialect_update_candidates if self._dialect is not None else None
if dialect_candidates is not None:
for dialect_code in dialect_candidates:
dialect_candidate = DatabaseDialectManager._known_dialects_by_code.get(dialect_code)
if dialect_candidate is None:
raise AwsWrapperError(Messages.get_formatted("DatabaseDialectManager.UnknownDialectCode", dialect_code))
timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get(self._props)
try:
cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout(
self._thread_pool,
timeout_sec,
driver_dialect,
conn)(dialect_candidate.is_dialect)
is_dialect = cursor_execute_func_with_timeout(conn, driver_dialect)
except TimeoutError as e:
raise QueryTimeoutError("DatabaseDialectManager.QueryForDialectTimeout") from e
if not is_dialect:
continue
self._can_update = False
self._dialect_code = dialect_code
self._dialect = dialect_candidate
DatabaseDialectManager._known_endpoint_dialects.put(url, dialect_code,
DatabaseDialectManager._ENDPOINT_CACHE_EXPIRATION_NS)
if host_info is not None:
DatabaseDialectManager._known_endpoint_dialects.put(
host_info.url, dialect_code, DatabaseDialectManager._ENDPOINT_CACHE_EXPIRATION_NS)
self._log_current_dialect()
return self._dialect
if self._dialect_code is None or self._dialect_code == DialectCode.UNKNOWN:
raise AwsWrapperError(Messages.get("DatabaseDialectManager.UnknownDialect"))
self._can_update = False
DatabaseDialectManager._known_endpoint_dialects.put(url, self._dialect_code,
DatabaseDialectManager._ENDPOINT_CACHE_EXPIRATION_NS)
if host_info is not None:
DatabaseDialectManager._known_endpoint_dialects.put(
host_info.url, self._dialect_code, DatabaseDialectManager._ENDPOINT_CACHE_EXPIRATION_NS)
self._log_current_dialect()
return self._dialect
def _log_current_dialect(self):
dialect_class = "<null>" if self._dialect is None else type(self._dialect).__name__
logger.debug("DatabaseDialectManager.CurrentDialectCanUpdate", self._dialect_code, dialect_class, self._can_update)