aws-advanced-jdbc-wrapper.git / summary / log / commit / refs

commit    ccb3caedef4345a05f8256ae18efbdbdb8f2efe4
Author:   Karen <64801825+karenc-bq@users.noreply.github.com>
Commit:   GitHub <noreply@github.com>
Date:     Fri Jul 28 02:42:19 2023 +0000

    chore: set initial host list provider according to the dialect (#567)


CHANGELOG.md | 8 +++ docs/development-guide/LoadablePlugins.md | 2 +- docs/development-guide/Pipelines.md | 6 +- docs/using-the-jdbc-driver/UsingTheJdbcDriver.md | 5 +- .../software/amazon/jdbc/PluginServiceImpl.java | 21 ++++--- .../amazon/jdbc/dialect/AuroraMysqlDialect.java | 39 ++++++------ .../amazon/jdbc/dialect/AuroraPgDialect.java | 44 +++++++------- .../java/software/amazon/jdbc/dialect/Dialect.java | 2 + .../jdbc/dialect/HostListProviderSupplier.java | 30 ++++++++++ .../amazon/jdbc/dialect/MariaDbDialect.java | 4 ++ .../software/amazon/jdbc/dialect/MysqlDialect.java | 5 ++ .../software/amazon/jdbc/dialect/PgDialect.java | 6 ++ .../jdbc/dialect/TopologyAwareDatabaseCluster.java | 42 ------------- .../amazon/jdbc/dialect/UnknownDialect.java | 9 +++ .../hostlistprovider/AuroraHostListProvider.java | 63 ++++++++----------- .../plugin/AuroraHostListConnectionPlugin.java | 7 ++- .../plugin/failover/FailoverConnectionPlugin.java | 26 ++++---- .../jdbc/plugin/staledns/AuroraStaleDnsHelper.java | 31 +--------- .../amazon/jdbc/wrapper/ConnectionWrapper.java | 10 +++- wrapper/src/main/resources/messages.properties | 5 +- .../aurora/TestAuroraHostListProvider.java | 3 +- .../container/tests/DataSourceTests.java | 1 + .../amazon/jdbc/PluginServiceImplTests.java | 4 +- .../AuroraHostListProviderTest.java | 70 +++++++++------------- .../plugin/AuroraConnectionTrackerPluginTest.java | 4 +- .../AwsSecretsManagerConnectionPluginTest.java | 3 +- .../failover/FailoverConnectionPluginTest.java | 60 ++++++++++--------- 27 files changed, 248 insertions(+), 262 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ac08654..0e0c9593 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/#semantic-versioning-200). +## [2.2.x] - ??? +### :crab: Changed +- Dynamically sets the default host list provider based on the dialect used. User applications no longer need to manually set the AuroraHostListProvider when connecting to Aurora Postgres or Aurora MySQL databases. +- Deprecated AuroraHostListConnectionPlugin. + - As an enhancement, the wrapper is now able to automatically set the Aurora host list provider for connections to Aurora MySQL and Aurora PostgreSQL databases. + Aurora Host List Connection Plugin is deprecated. If you were using the `AuroraHostListConnectionPlugin`, you can simply remove the plugin from the `wrapperPlugins` parameter. + However, if you choose to, you can ensure the provider is used by specifying a topology-aware dialect, for more information, see [Database Dialects](docs/using-the-jdbc-driver/DatabaseDialects.md). + ## [2.2.3] - 2023-07-28 ### :magic_wand: Added - Developer plugin to help test various scenarios including events like network outages and database cluster failover. This plugin is NOT intended to be used in production environments and is only for testing ([PR #531](https://github.com/awslabs/aws-advanced-jdbc-wrapper/pull/531)). diff --git a/docs/development-guide/LoadablePlugins.md b/docs/development-guide/LoadablePlugins.md index 31952091..3fd31f67 100644 --- a/docs/development-guide/LoadablePlugins.md +++ b/docs/development-guide/LoadablePlugins.md @@ -39,7 +39,7 @@ See the following classes for examples: - [ExecutionTimeConnectionPlugin](/wrapper/src/main/java/software/amazon/jdbc/plugin/ExecutionTimeConnectionPlugin.java) - The `ExecutionTimeConnectionPlugin` only overrides the `execute` method because it is only concerned with elapsed time during execution, it does not establish new connections or set up any host list provider. -A `ConnectionPluginFactory` implementation is also required for the new custom plugin. This factory class is used to register and initialize custom plugins. See [AuroraHostListConnectionPluginFactory](/wrapper/src/main/java/software/amazon/jdbc/plugin/AuroraHostListConnectionPluginFactory.java) for a simple implementation example. +A `ConnectionPluginFactory` implementation is also required for the new custom plugin. This factory class is used to register and initialize custom plugins. See [ExecutionTimeConnectionPluginFactory](/wrapper/src/main/java/software/amazon/jdbc/plugin/ExecutionTimeConnectionPluginFactory.java) for a simple implementation example. ### Subscribed Methods diff --git a/docs/development-guide/Pipelines.md b/docs/development-guide/Pipelines.md index 19557b7d..9d856915 100644 --- a/docs/development-guide/Pipelines.md +++ b/docs/development-guide/Pipelines.md @@ -67,7 +67,9 @@ it does not perform any additional work. For cases where keeping updated information on existing and available replicas is necessary, such as during the failover procedure, it is important to have a host list provider that can re-fetch information once in a while, -like the [Aurora host list provider](/wrapper/src/main/java/software/amazon/jdbc/plugin/AuroraHostListConnectionPlugin.java). +like the Aurora host list provider. +The Aurora host list provider should be automatically used by the wrapper when the application is connecting to Aurora databases. +However, you can ensure that the provider is used by specifying a topology-aware dialect, for more information, see [Database Dialects](../using-the-jdbc-driver/DatabaseDialects.md). ## Connection Changed Notification Pipeline @@ -87,7 +89,7 @@ will be called whenever changes in the current node list are detected. Plugins should subscribe to this pipeline and the getHostSpecByStrategy pipeline if they implement a host selection strategy via the `getHostSpecByStrategy` method. In this case, plugins should override the `acceptsStrategy` and `getHostSpecByStrategy` methods to implement any desired logic. The `acceptsStrategy` method should return true for each selection strategy that the plugin supports. -## getHostSpecByStrategy pipeline +## Get HostSpec by Strategy pipeline Plugins should subscribe to this pipeline and the acceptsStrategy pipeline if they implement a host selection strategy. In this case, plugins should override both the `acceptsStrategy` method and the `getHostSpecByStrategy` method. The `acceptsStrategy` method should return true for each strategy that can be processed by the plugin in `getHostSpecByStrategy`. The `getHostSpecByStrategy` method should implement the desired logic for selecting a host using any plugin-accepted strategies. Host selection via a "random" strategy is supported by default. diff --git a/docs/using-the-jdbc-driver/UsingTheJdbcDriver.md b/docs/using-the-jdbc-driver/UsingTheJdbcDriver.md index e06dfa7e..6f758583 100644 --- a/docs/using-the-jdbc-driver/UsingTheJdbcDriver.md +++ b/docs/using-the-jdbc-driver/UsingTheJdbcDriver.md @@ -108,7 +108,6 @@ The AWS JDBC Driver has several built-in plugins that are available to use. Plea |------------------------------------------------------------------------------------------------|---------------------------|------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [Failover Connection Plugin](./using-plugins/UsingTheFailoverPlugin.md) | `failover` | Aurora | Enables the failover functionality supported by Amazon Aurora clusters. Prevents opening a wrong connection to an old writer node dues to stale DNS after failover event. This plugin is enabled by default. | | [Host Monitoring Connection Plugin](./using-plugins/UsingTheHostMonitoringPlugin.md) | `efm` | Aurora | Enables enhanced host connection failure monitoring, allowing faster failure detection rates. This plugin is enabled by default. | -| Aurora Host List Connection Plugin | `auroraHostList` | Aurora | Retrieves Amazon Aurora clusters information. <br><br>**:warning:Note:** this plugin does not need to be explicitly loaded if the failover connection plugin is loaded. | | Data Cache Connection Plugin | `dataCache` | Any database | Caches results from SQL queries matching the regular expression specified in the `dataCacheTriggerCondition` configuration parameter. | | Execution Time Connection Plugin | `executionTime` | Any database | Logs the time taken to execute any JDBC method. | | Log Query Connection Plugin | `logQuery` | Any database | Tracks and logs the SQL statements to be executed. Sometimes SQL statements are not passed directly to the JDBC method as a parameter, such as [executeBatch()](https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#executeBatch--). Users can set `enhancedLogQueryEnabled` to `true`, allowing the JDBC Wrapper to obtain SQL statements via Java Reflection. <br><br> :warning:**Note:** Enabling Java Reflection may cause a performance degradation. | @@ -120,6 +119,10 @@ The AWS JDBC Driver has several built-in plugins that are available to use. Plea | [Read Write Splitting Plugin](./using-plugins/UsingTheReadWriteSplittingPlugin.md) | `readWriteSplitting` | Aurora | Enables read write splitting functionality where users can switch between database reader and writer instances. | | [Developer Plugin](./using-plugins/UsingTheDeveloperPlugin.md) | `dev` | Any database | Helps developers test various everyday scenarios including rare events like network outages and database cluster failover. The plugin allows injecting and raising an expected exception, then verifying how applications handle it. | +:exclamation: **NOTE**: As an enhancement, the wrapper is now able to automatically set the Aurora host list provider for connections to Aurora MySQL and Aurora PostgreSQL databases. +Aurora Host List Connection Plugin is deprecated. If you were using the Aurora Host List Connection Plugin, you can simply remove the plugin from the `wrapperPlugins` parameter. +However, if you choose to, you can ensure the provider is used by specifying a topology-aware dialect, for more information, see [Database Dialects](../using-the-jdbc-driver/DatabaseDialects.md). + :exclamation:**NOTE**: To see information logged by plugins such as `DataCacheConnectionPlugin` and `LogQueryConnectionPlugin`, > see the [Logging](#logging) section. diff --git a/wrapper/src/main/java/software/amazon/jdbc/PluginServiceImpl.java b/wrapper/src/main/java/software/amazon/jdbc/PluginServiceImpl.java index ef6ba5f9..185eacae 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/PluginServiceImpl.java +++ b/wrapper/src/main/java/software/amazon/jdbc/PluginServiceImpl.java @@ -38,7 +38,7 @@ import software.amazon.jdbc.cleanup.CanReleaseResources; import software.amazon.jdbc.dialect.Dialect; import software.amazon.jdbc.dialect.DialectManager; import software.amazon.jdbc.dialect.DialectProvider; -import software.amazon.jdbc.dialect.TopologyAwareDatabaseCluster; +import software.amazon.jdbc.dialect.HostListProviderSupplier; import software.amazon.jdbc.exceptions.ExceptionManager; import software.amazon.jdbc.hostlistprovider.StaticHostListProvider; import software.amazon.jdbc.util.CacheMap; @@ -372,7 +372,7 @@ public class PluginServiceImpl implements PluginService, CanReleaseResources, } void setNodeList(@Nullable final List<HostSpec> oldHosts, - @Nullable final List<HostSpec> newHosts) { + @Nullable final List<HostSpec> newHosts) { final Map<String, HostSpec> oldHostMap = oldHosts == null ? new HashMap<>() @@ -487,19 +487,22 @@ public class PluginServiceImpl implements PluginService, CanReleaseResources, } public void updateDialect(final @NonNull Connection connection) throws SQLException { + final Dialect originalDialect = this.dialect; this.dialect = this.dialectProvider.getDialect( this.originalUrl, this.initialConnectionHostSpec, connection); + if (originalDialect == this.dialect) { + return; + } + + final HostListProviderSupplier supplier = this.dialect.getHostListProvider(); + this.setHostListProvider(supplier.getProvider(props, this.originalUrl, this)); } @Override public HostSpec identifyConnection(Connection connection) throws SQLException { - if (!(this.getDialect() instanceof TopologyAwareDatabaseCluster)) { - return null; - } - - return this.hostListProvider.identifyConnection(connection); + return this.getHostListProvider().identifyConnection(connection); } @Override @@ -509,7 +512,7 @@ public class PluginServiceImpl implements PluginService, CanReleaseResources, } if (!hostSpec.getAliases().isEmpty()) { - LOGGER.finest(() -> Messages.get("PluginServiceImpl.nonEmptyAliases", new Object[] {hostSpec.getAliases()})); + LOGGER.finest(() -> Messages.get("PluginServiceImpl.nonEmptyAliases", new Object[]{hostSpec.getAliases()})); return; } @@ -530,7 +533,7 @@ public class PluginServiceImpl implements PluginService, CanReleaseResources, // Add the instance endpoint if the current connection is associated with a topology aware database cluster. final HostSpec host = this.identifyConnection(connection); if (host != null) { - hostSpec.addAlias(host.asAliases().toArray(new String[] {})); + hostSpec.addAlias(host.asAliases().toArray(new String[]{})); } } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraMysqlDialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraMysqlDialect.java index a6d4e1c1..9b2c7174 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraMysqlDialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraMysqlDialect.java @@ -21,27 +21,19 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; +import software.amazon.jdbc.hostlistprovider.AuroraHostListProvider; -public class AuroraMysqlDialect extends MysqlDialect implements TopologyAwareDatabaseCluster { +public class AuroraMysqlDialect extends MysqlDialect { - @Override - public String getTopologyQuery() { - return "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 " - // filter out nodes that haven't been updated in the last 5 minutes - + "WHERE time_to_sec(timediff(now(), LAST_UPDATE_TIMESTAMP)) <= 300 OR SESSION_ID = 'MASTER_SESSION_ID' "; - } - - @Override - public String getNodeIdQuery() { - return "SELECT @@aurora_server_id"; - } + private static final String 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 " + // filter out nodes that haven't been updated in the last 5 minutes + + "WHERE time_to_sec(timediff(now(), LAST_UPDATE_TIMESTAMP)) <= 300 OR SESSION_ID = 'MASTER_SESSION_ID' "; - @Override - public String getIsReaderQuery() { - return "SELECT @@innodb_read_only"; - } + private static final String NODE_ID_QUERY = "SELECT @@aurora_server_id"; + private static final String IS_READER_QUERY = "SELECT @@innodb_read_only"; @Override public boolean isDialect(final Connection connection) { @@ -61,4 +53,15 @@ public class AuroraMysqlDialect extends MysqlDialect implements TopologyAwareDat public List</* dialect code */ String> getDialectUpdateCandidates() { return null; } + + @Override + public HostListProviderSupplier getHostListProvider() { + return (properties, initialUrl, hostListProviderService) -> new AuroraHostListProvider( + properties, + initialUrl, + hostListProviderService, + TOPOLOGY_QUERY, + NODE_ID_QUERY, + IS_READER_QUERY); + } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraPgDialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraPgDialect.java index 8c7d5dd3..0947e103 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraPgDialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/AuroraPgDialect.java @@ -21,13 +21,13 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Logger; +import software.amazon.jdbc.hostlistprovider.AuroraHostListProvider; /** * Suitable for the following AWS PG configurations. * - Regional Cluster */ -public class AuroraPgDialect extends PgDialect implements TopologyAwareDatabaseCluster { - +public class AuroraPgDialect extends PgDialect { private static final Logger LOGGER = Logger.getLogger(AuroraPgDialect.class.getName()); private static final String extensionsSql = @@ -37,24 +37,15 @@ public class AuroraPgDialect extends PgDialect implements TopologyAwareDatabaseC private static final String topologySql = "SELECT 1 FROM aurora_replica_status() LIMIT 1"; - @Override - public String getTopologyQuery() { - return "SELECT SERVER_ID, CASE WHEN SESSION_ID = 'MASTER_SESSION_ID' THEN TRUE ELSE FALSE END, " - + "CPU, COALESCE(REPLICA_LAG_IN_MSEC, 0), LAST_UPDATE_TIMESTAMP " - + "FROM aurora_replica_status() " - // filter out nodes that haven't been updated in the last 5 minutes - + "WHERE EXTRACT(EPOCH FROM(NOW() - LAST_UPDATE_TIMESTAMP)) <= 300 OR SESSION_ID = 'MASTER_SESSION_ID' "; - } + private static final String TOPOLOGY_QUERY = + "SELECT SERVER_ID, CASE WHEN SESSION_ID = 'MASTER_SESSION_ID' THEN TRUE ELSE FALSE END, " + + "CPU, COALESCE(REPLICA_LAG_IN_MSEC, 0), LAST_UPDATE_TIMESTAMP " + + "FROM aurora_replica_status() " + // filter out nodes that haven't been updated in the last 5 minutes + + "WHERE EXTRACT(EPOCH FROM(NOW() - LAST_UPDATE_TIMESTAMP)) <= 300 OR SESSION_ID = 'MASTER_SESSION_ID' "; - @Override - public String getNodeIdQuery() { - return "SELECT aurora_db_instance_identifier()"; - } - - @Override - public String getIsReaderQuery() { - return "SELECT pg_is_in_recovery()"; - } + private static final String NODE_ID_QUERY = "SELECT aurora_db_instance_identifier()"; + private static final String IS_READER_QUERY = "SELECT pg_is_in_recovery()"; @Override public boolean isDialect(final Connection connection) { @@ -66,7 +57,7 @@ public class AuroraPgDialect extends PgDialect implements TopologyAwareDatabaseC boolean hasTopology = false; try { try (final Statement stmt = connection.createStatement(); - final ResultSet rs = stmt.executeQuery(extensionsSql)) { + final ResultSet rs = stmt.executeQuery(extensionsSql)) { if (rs.next()) { final boolean auroraUtils = rs.getBoolean("aurora_stat_utils"); LOGGER.finest(() -> String.format("auroraUtils: %b", auroraUtils)); @@ -77,7 +68,7 @@ public class AuroraPgDialect extends PgDialect implements TopologyAwareDatabaseC } try (final Statement stmt = connection.createStatement(); - final ResultSet rs = stmt.executeQuery(topologySql)) { + final ResultSet rs = stmt.executeQuery(topologySql)) { if (rs.next()) { LOGGER.finest(() -> "hasTopology: true"); hasTopology = true; @@ -91,4 +82,15 @@ public class AuroraPgDialect extends PgDialect implements TopologyAwareDatabaseC } return false; } + + @Override + public HostListProviderSupplier getHostListProvider() { + return (properties, initialUrl, hostListProviderService) -> new AuroraHostListProvider( + properties, + initialUrl, + hostListProviderService, + TOPOLOGY_QUERY, + NODE_ID_QUERY, + IS_READER_QUERY); + } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/Dialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/Dialect.java index 1f65b248..b81e6cb6 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/Dialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/Dialect.java @@ -32,4 +32,6 @@ public interface Dialect { boolean isDialect(Connection connection); List</* dialect code */ String> getDialectUpdateCandidates(); + + HostListProviderSupplier getHostListProvider(); } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/HostListProviderSupplier.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/HostListProviderSupplier.java new file mode 100644 index 00000000..b5b409eb --- /dev/null +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/HostListProviderSupplier.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package software.amazon.jdbc.dialect; + +import java.util.Properties; +import org.checkerframework.checker.nullness.qual.NonNull; +import software.amazon.jdbc.HostListProvider; +import software.amazon.jdbc.HostListProviderService; + +@FunctionalInterface +public interface HostListProviderSupplier { + @NonNull HostListProvider getProvider( + final @NonNull Properties properties, + final String initialUrl, + final @NonNull HostListProviderService hostListProviderService); +} diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/MariaDbDialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/MariaDbDialect.java index 02164531..03dce010 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/MariaDbDialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/MariaDbDialect.java @@ -23,6 +23,7 @@ import java.sql.Statement; import java.util.List; import software.amazon.jdbc.exceptions.ExceptionHandler; import software.amazon.jdbc.exceptions.MariaDBExceptionHandler; +import software.amazon.jdbc.hostlistprovider.ConnectionStringHostListProvider; public class MariaDbDialect implements Dialect { @@ -72,4 +73,7 @@ public class MariaDbDialect implements Dialect { return null; } + public HostListProviderSupplier getHostListProvider() { + return ConnectionStringHostListProvider::new; + } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/MysqlDialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/MysqlDialect.java index 62478729..80910000 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/MysqlDialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/MysqlDialect.java @@ -24,6 +24,7 @@ import java.util.Arrays; import java.util.List; import software.amazon.jdbc.exceptions.ExceptionHandler; import software.amazon.jdbc.exceptions.MySQLExceptionHandler; +import software.amazon.jdbc.hostlistprovider.ConnectionStringHostListProvider; public class MysqlDialect implements Dialect { @@ -77,4 +78,8 @@ public class MysqlDialect implements Dialect { public List<String> getDialectUpdateCandidates() { return dialectUpdateCandidates; } + + public HostListProviderSupplier getHostListProvider() { + return ConnectionStringHostListProvider::new; + } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/PgDialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/PgDialect.java index 43adc220..1bc6c951 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/PgDialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/PgDialect.java @@ -24,6 +24,7 @@ import java.util.Arrays; import java.util.List; import software.amazon.jdbc.exceptions.ExceptionHandler; import software.amazon.jdbc.exceptions.PgExceptionHandler; +import software.amazon.jdbc.hostlistprovider.ConnectionStringHostListProvider; /** * Generic dialect for any Postgresql database. @@ -77,4 +78,9 @@ public class PgDialect implements Dialect { public List<String> getDialectUpdateCandidates() { return dialectUpdateCandidates; } + + @Override + public HostListProviderSupplier getHostListProvider() { + return ConnectionStringHostListProvider::new; + } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/TopologyAwareDatabaseCluster.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/TopologyAwareDatabaseCluster.java deleted file mode 100644 index 388f2ae2..00000000 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/TopologyAwareDatabaseCluster.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - */ - -package software.amazon.jdbc.dialect; - -public interface TopologyAwareDatabaseCluster { - - /** - * Query should return multiple rows with the following columns. Column order is important! - * 1 - A string that represents a node name or node ID - * 2 - A boolean that represents a node role (true - writer, false - reader/replica) - * 3 - A number (or null) that represents a current CPU utilization of a node. Lesser number - * corresponds to less node load/utilization - * 4 - A number (or null) that represent a node lag comparing to a writer node. Lesser number - * corresponds to small lag in time. - * 5 - A timestamp that represents the last time a node was updated - */ - String getTopologyQuery(); - - /** - * Query should return a single row with a single column. - */ - String getNodeIdQuery(); - - /** - * Query should return a single row with a single boolean column. - */ - String getIsReaderQuery(); -} diff --git a/wrapper/src/main/java/software/amazon/jdbc/dialect/UnknownDialect.java b/wrapper/src/main/java/software/amazon/jdbc/dialect/UnknownDialect.java index 5b6a1b35..5455097f 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/dialect/UnknownDialect.java +++ b/wrapper/src/main/java/software/amazon/jdbc/dialect/UnknownDialect.java @@ -19,9 +19,13 @@ package software.amazon.jdbc.dialect; import java.sql.Connection; import java.util.Arrays; import java.util.List; +import java.util.Properties; +import org.checkerframework.checker.nullness.qual.NonNull; +import software.amazon.jdbc.HostListProviderService; import software.amazon.jdbc.HostSpec; import software.amazon.jdbc.exceptions.ExceptionHandler; import software.amazon.jdbc.exceptions.GenericExceptionHandler; +import software.amazon.jdbc.hostlistprovider.ConnectionStringHostListProvider; public class UnknownDialect implements Dialect { @@ -69,4 +73,9 @@ public class UnknownDialect implements Dialect { public List<String> getDialectUpdateCandidates() { return dialectUpdateCandidates; } + + @Override + public HostListProviderSupplier getHostListProvider() { + return ConnectionStringHostListProvider::new; + } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProvider.java b/wrapper/src/main/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProvider.java index b5a130e8..fdfe9ba5 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProvider.java +++ b/wrapper/src/main/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProvider.java @@ -47,8 +47,6 @@ import software.amazon.jdbc.HostListProviderService; import software.amazon.jdbc.HostRole; import software.amazon.jdbc.HostSpec; import software.amazon.jdbc.PropertyDefinition; -import software.amazon.jdbc.dialect.Dialect; -import software.amazon.jdbc.dialect.TopologyAwareDatabaseCluster; import software.amazon.jdbc.util.CacheMap; import software.amazon.jdbc.util.ConnectionUrlParser; import software.amazon.jdbc.util.Messages; @@ -86,6 +84,9 @@ public class AuroraHostListProvider implements DynamicHostListProvider { private final Executor networkTimeoutExecutor = new SynchronousExecutor(); private final HostListProviderService hostListProviderService; private final String originalUrl; + private final String topologyQuery; + private final String nodeIdQuery; + private final String isReaderQuery; private RdsUrlType rdsUrlType; private final RdsUtils rdsHelper; @@ -106,7 +107,6 @@ public class AuroraHostListProvider implements DynamicHostListProvider { protected String clusterId; protected HostSpec clusterInstanceTemplate; protected ConnectionUrlParser connectionUrlParser; - protected TopologyAwareDatabaseCluster topologyAwareDialect; // A primary clusterId is a clusterId that is based off of a cluster endpoint URL // (rather than a GUID or a value provided by the user). @@ -123,23 +123,36 @@ public class AuroraHostListProvider implements DynamicHostListProvider { } public AuroraHostListProvider( - final String driverProtocol, - final HostListProviderService hostListProviderService, final Properties properties, - final String originalUrl) { - this(driverProtocol, hostListProviderService, properties, originalUrl, new ConnectionUrlParser()); + final String originalUrl, + final HostListProviderService hostListProviderService, + final String topologyQuery, + final String nodeIdQuery, + final String isReaderQuery) { + this(hostListProviderService, + properties, + originalUrl, + topologyQuery, + nodeIdQuery, + isReaderQuery, + new ConnectionUrlParser()); } public AuroraHostListProvider( - final String driverProtocol, final HostListProviderService hostListProviderService, final Properties properties, final String originalUrl, + final String topologyQuery, + final String nodeIdQuery, + final String isReaderQuery, final ConnectionUrlParser connectionUrlParser) { this.rdsHelper = new RdsUtils(); this.hostListProviderService = hostListProviderService; this.properties = properties; this.originalUrl = originalUrl; + this.topologyQuery = topologyQuery; + this.nodeIdQuery = nodeIdQuery; + this.isReaderQuery = isReaderQuery; this.connectionUrlParser = connectionUrlParser; } @@ -337,15 +350,6 @@ public class AuroraHostListProvider implements DynamicHostListProvider { * @throws SQLException if errors occurred while retrieving the topology. */ protected List<HostSpec> queryForTopology(final Connection conn) throws SQLException { - - if (this.topologyAwareDialect == null) { - if (!(this.hostListProviderService.getDialect() instanceof TopologyAwareDatabaseCluster)) { - LOGGER.warning(() -> Messages.get("AuroraHostListProvider.invalidDialect")); - return null; - } - this.topologyAwareDialect = (TopologyAwareDatabaseCluster) this.hostListProviderService.getDialect(); - } - int networkTimeout = -1; try { networkTimeout = conn.getNetworkTimeout(); @@ -359,7 +363,7 @@ public class AuroraHostListProvider implements DynamicHostListProvider { } try (final Statement stmt = conn.createStatement(); - final ResultSet resultSet = stmt.executeQuery(this.topologyAwareDialect.getTopologyQuery())) { + final ResultSet resultSet = stmt.executeQuery(this.topologyQuery)) { return processQueryResults(resultSet); } catch (final SQLSyntaxErrorException e) { throw new SQLException(Messages.get("AuroraHostListProvider.invalidQuery"), e); @@ -429,7 +433,7 @@ public class AuroraHostListProvider implements DynamicHostListProvider { * @throws SQLException If unable to retrieve the hostName from the result set */ private HostSpec createHost(final ResultSet resultSet) throws SQLException { - // According to TopologyAwareDatabaseCluster.getTopologyQuery() the result set + // According to the topology query the result set // should contain 4 columns: node ID, 1/0 (writer/reader), CPU utilization, node lag in time. String hostName = resultSet.getString(1); final boolean isWriter = resultSet.getBoolean(2); @@ -637,9 +641,7 @@ public class AuroraHostListProvider implements DynamicHostListProvider { @Override public HostRole getHostRole(Connection conn) throws SQLException { try (final Statement stmt = conn.createStatement(); - final ResultSet rs = stmt.executeQuery( - getTopologyAwareDialect("AuroraHostListProvider.invalidDialectForGetHostRole") - .getIsReaderQuery())) { + final ResultSet rs = stmt.executeQuery(this.isReaderQuery)) { if (rs.next()) { boolean isReader = rs.getBoolean(1); return isReader ? HostRole.READER : HostRole.WRITER; @@ -654,9 +656,7 @@ public class AuroraHostListProvider implements DynamicHostListProvider { @Override public HostSpec identifyConnection(Connection connection) throws SQLException { try (final Statement stmt = connection.createStatement(); - final ResultSet resultSet = stmt.executeQuery( - getTopologyAwareDialect("AuroraHostListProvider.invalidDialectForIdentifyConnection") - .getNodeIdQuery())) { + final ResultSet resultSet = stmt.executeQuery(this.nodeIdQuery)) { if (resultSet.next()) { final String instanceName = resultSet.getString(1); @@ -678,17 +678,4 @@ public class AuroraHostListProvider implements DynamicHostListProvider { throw new SQLException(Messages.get("AuroraHostListProvider.errorIdentifyConnection")); } - - private TopologyAwareDatabaseCluster getTopologyAwareDialect(String exceptionMessageIdentifier) throws SQLException { - if (this.topologyAwareDialect == null) { - Dialect dialect = this.hostListProviderService.getDialect(); - if (!(dialect instanceof TopologyAwareDatabaseCluster)) { - throw new SQLException( - Messages.get(exceptionMessageIdentifier, - new Object[] {dialect})); - } - this.topologyAwareDialect = (TopologyAwareDatabaseCluster) this.hostListProviderService.getDialect(); - } - return this.topologyAwareDialect; - } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/AuroraHostListConnectionPlugin.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/AuroraHostListConnectionPlugin.java index 384c1f92..873c1a68 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/plugin/AuroraHostListConnectionPlugin.java +++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/AuroraHostListConnectionPlugin.java @@ -25,9 +25,11 @@ import software.amazon.jdbc.HostListProvider; import software.amazon.jdbc.HostListProviderService; import software.amazon.jdbc.JdbcCallable; import software.amazon.jdbc.PluginService; +import software.amazon.jdbc.dialect.HostListProviderSupplier; import software.amazon.jdbc.hostlistprovider.AuroraHostListProvider; import software.amazon.jdbc.util.Messages; +@Deprecated public class AuroraHostListConnectionPlugin extends AbstractConnectionPlugin { private static final Set<String> subscribedMethods = Collections.unmodifiableSet(new HashSet<>( @@ -57,8 +59,9 @@ public class AuroraHostListConnectionPlugin extends AbstractConnectionPlugin { } if (hostListProviderService.isStaticHostListProvider()) { - hostListProviderService.setHostListProvider( - new AuroraHostListProvider(driverProtocol, hostListProviderService, props, initialUrl)); + HostListProviderSupplier supplier = + this.pluginService.getDialect().getHostListProvider(); + hostListProviderService.setHostListProvider(supplier.getProvider(props, initialUrl, hostListProviderService)); } else if (!(provider instanceof AuroraHostListProvider)) { throw new SQLException(Messages.get("AuroraHostListConnectionPlugin.providerAlreadySet", new Object[] {provider.getClass().getName()})); diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPlugin.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPlugin.java index 136bbe48..2496f178 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPlugin.java +++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPlugin.java @@ -207,7 +207,7 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { public void initHostProvider( final String driverProtocol, final String initialUrl, - final Properties props, + final Properties properties, final HostListProviderService hostListProviderService, final JdbcCallable<Void, SQLException> initHostProviderFunc) throws SQLException { @@ -215,7 +215,6 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { initialUrl, hostListProviderService, initHostProviderFunc, - () -> new AuroraHostListProvider(driverProtocol, hostListProviderService, props, initialUrl), () -> new ClusterAwareReaderFailoverHandler( this.pluginService, @@ -237,7 +236,6 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { final String initialUrl, final HostListProviderService hostListProviderService, final JdbcCallable<Void, SQLException> initHostProviderFunc, - final Supplier<HostListProvider> hostListProviderSupplier, final Supplier<ClusterAwareReaderFailoverHandler> readerFailoverHandlerSupplier, final Supplier<ClusterAwareWriterFailoverHandler> writerFailoverHandlerSupplier) throws SQLException { @@ -247,7 +245,9 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { } if (hostListProviderService.isStaticHostListProvider()) { - hostListProviderService.setHostListProvider(hostListProviderSupplier.get()); + throw new SQLException(Messages.get( + "Failover.invalidHostListProvider", + new Object[] {this.pluginService.getHostListProvider()})); } this.readerFailoverHandler = readerFailoverHandlerSupplier.get(); @@ -271,7 +271,7 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { LOGGER.finer( () -> Messages.get( "Failover.parameterValue", - new Object[] {"failoverMode", this.failoverMode})); + new Object[]{"failoverMode", this.failoverMode})); } @Override @@ -309,7 +309,7 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { } } - LOGGER.fine(() -> Messages.get("Failover.invalidNode", new Object[] {currentHost})); + LOGGER.fine(() -> Messages.get("Failover.invalidNode", new Object[]{currentHost})); } private boolean isNodeStillValid(final String node, final Map<String, EnumSet<NodeChangeOptions>> changes) { @@ -415,7 +415,7 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { LOGGER.fine( () -> Messages.get( "Failover.establishedConnection", - new Object[] {host})); + new Object[]{host})); } catch (final SQLException e) { if (this.pluginService.getCurrentConnection() != null) { final String msg = "Connection to " @@ -484,8 +484,8 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { /** * Transfers basic session state from one connection to another. * - * @param from The connection to transfer state from - * @param to The connection to transfer state to + * @param from The connection to transfer state from + * @param to The connection to transfer state to * @throws SQLException if a database access error occurs, this method is called on a closed connection, this * method is called during a distributed transaction, or this method is called during a * transaction @@ -509,7 +509,7 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { final Class<E> exceptionClass) throws E { Throwable exceptionToThrow = wrapperException; if (originalException != null) { - LOGGER.finer(() -> Messages.get("Failover.detectedException", new Object[] {originalException.getMessage()})); + LOGGER.finer(() -> Messages.get("Failover.detectedException", new Object[]{originalException.getMessage()})); if (this.lastExceptionDealtWith != originalException && shouldExceptionTriggerConnectionSwitch(originalException)) { invalidateCurrentConnection(); @@ -609,13 +609,13 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { this.pluginService.setCurrentConnection(result.getConnection(), result.getHost()); - this.pluginService.getCurrentHostSpec().removeAlias(oldAliases.toArray(new String[] {})); + this.pluginService.getCurrentHostSpec().removeAlias(oldAliases.toArray(new String[]{})); updateTopology(true); LOGGER.fine( () -> Messages.get( "Failover.establishedConnection", - new Object[] {this.pluginService.getCurrentHostSpec()})); + new Object[]{this.pluginService.getCurrentHostSpec()})); } protected void failoverWriter() throws SQLException { @@ -640,7 +640,7 @@ public class FailoverConnectionPlugin extends AbstractConnectionPlugin { LOGGER.fine( () -> Messages.get( "Failover.establishedConnection", - new Object[] {this.pluginService.getCurrentHostSpec()})); + new Object[]{this.pluginService.getCurrentHostSpec()})); this.pluginService.refreshHostList(); } diff --git a/wrapper/src/main/java/software/amazon/jdbc/plugin/staledns/AuroraStaleDnsHelper.java b/wrapper/src/main/java/software/amazon/jdbc/plugin/staledns/AuroraStaleDnsHelper.java index d2b7858d..3cb4c415 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/plugin/staledns/AuroraStaleDnsHelper.java +++ b/wrapper/src/main/java/software/amazon/jdbc/plugin/staledns/AuroraStaleDnsHelper.java @@ -19,10 +19,7 @@ package software.amazon.jdbc.plugin.staledns; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; -import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.SQLSyntaxErrorException; -import java.sql.Statement; import java.util.EnumSet; import java.util.Map; import java.util.Properties; @@ -33,7 +30,6 @@ import software.amazon.jdbc.HostSpec; import software.amazon.jdbc.JdbcCallable; import software.amazon.jdbc.NodeChangeOptions; import software.amazon.jdbc.PluginService; -import software.amazon.jdbc.dialect.TopologyAwareDatabaseCluster; import software.amazon.jdbc.util.Messages; import software.amazon.jdbc.util.RdsUtils; import software.amazon.jdbc.util.Utils; @@ -83,11 +79,7 @@ public class AuroraStaleDnsHelper { return conn; } - String query = null; - if (this.pluginService.getDialect() instanceof TopologyAwareDatabaseCluster) { - query = ((TopologyAwareDatabaseCluster) this.pluginService.getDialect()).getIsReaderQuery(); - } - if (query == null || isReadOnly(conn, query)) { + if (this.pluginService.getHostRole(conn) == HostRole.READER) { // This is if-statement is only reached if the connection url is a writer cluster endpoint. // If the new connection resolves to a reader instance, this means the topology is outdated. // Force refresh to update the topology. @@ -177,25 +169,4 @@ public class AuroraStaleDnsHelper { } return null; } - - private boolean isReadOnly(final Connection connection, final String query) - throws SQLSyntaxErrorException { - for (int i = 0; i < RETRIES; i++) { - try (final Statement statement = connection.createStatement(); - final ResultSet rs = statement.executeQuery(query)) { - if (rs.next()) { - return rs.getBoolean(1); - } - } catch (final SQLSyntaxErrorException e) { - throw e; - } catch (final SQLException e) { - - // Return false if the SQLException is not a network error. Otherwise, retry. - if (!pluginService.isNetworkException(e)) { - return false; - } - } - } - return false; - } } diff --git a/wrapper/src/main/java/software/amazon/jdbc/wrapper/ConnectionWrapper.java b/wrapper/src/main/java/software/amazon/jdbc/wrapper/ConnectionWrapper.java index 32ab6fc9..9dee4be8 100644 --- a/wrapper/src/main/java/software/amazon/jdbc/wrapper/ConnectionWrapper.java +++ b/wrapper/src/main/java/software/amazon/jdbc/wrapper/ConnectionWrapper.java @@ -40,6 +40,7 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import software.amazon.jdbc.ConnectionPluginManager; import software.amazon.jdbc.ConnectionProvider; +import software.amazon.jdbc.HostListProvider; import software.amazon.jdbc.HostListProviderService; import software.amazon.jdbc.PluginManagerService; import software.amazon.jdbc.PluginService; @@ -49,6 +50,7 @@ import software.amazon.jdbc.cleanup.CanReleaseResources; import software.amazon.jdbc.dialect.Dialect; import software.amazon.jdbc.dialect.DialectManager; import software.amazon.jdbc.dialect.DialectProvider; +import software.amazon.jdbc.dialect.HostListProviderSupplier; import software.amazon.jdbc.hostlistprovider.ConnectionStringHostListProvider; import software.amazon.jdbc.util.Messages; import software.amazon.jdbc.util.SqlState; @@ -121,9 +123,11 @@ public class ConnectionWrapper implements Connection, CanReleaseResources { this.pluginManagerService = pluginManagerService; this.pluginManager.init(this.pluginService, props, pluginManagerService); - - this.hostListProviderService.setHostListProvider( - new ConnectionStringHostListProvider(props, this.originalUrl, this.hostListProviderService)); + final HostListProviderSupplier supplier = this.pluginService.getDialect().getHostListProvider(); + if (supplier != null) { + final HostListProvider provider = supplier.getProvider(props, this.originalUrl, hostListProviderService); + hostListProviderService.setHostListProvider(provider); + } this.pluginManager.initHostProvider( this.targetDriverProtocol, this.originalUrl, props, this.hostListProviderService); diff --git a/wrapper/src/main/resources/messages.properties b/wrapper/src/main/resources/messages.properties index c787452e..fe928e9d 100644 --- a/wrapper/src/main/resources/messages.properties +++ b/wrapper/src/main/resources/messages.properties @@ -25,11 +25,8 @@ AuroraHostListProvider.invalidTopology=The topology query returned an invalid to AuroraHostListProvider.suggestedClusterId=ClusterId ''{0}'' is suggested for url ''{1}''. AuroraHostListProvider.parsedListEmpty=Can''t parse connection string: ''{0}'' AuroraHostListProvider.invalidQuery=Error obtaining host list. Provided database might not be an Aurora Db cluster -AuroraHostListProvider.invalidDialect=Expecting a dialect that supports a cluster topology. -AuroraHostListProvider.invalidDialectForGetHostRole=An Aurora dialect is required to analyze a host's role. The detected dialect was ''{0}'' AuroraHostListProvider.errorGettingHostRole=An error occurred while obtaining the connected host's role. This could occur if the connection is broken or if you are not connected to an Aurora database. AuroraHostListProvider.errorIdentifyConnection=An error occurred while obtaining the connection's host ID. -AuroraHostListProvider.invalidDialectForIdentifyConnection=An Aurora dialect is required to analyze the instance associated with this connection. The detected dialect was ''{0}'' AuroraHostListProvider.errorGettingNetworkTimeout=An error occurred while getting the connection network timeout: {0} # AWS Credentials Manager @@ -143,6 +140,8 @@ Failover.topologyObtained=Topology obtained: {0} Failover.invalidNode=Node is no longer available in the topology: {0} Failover.failedToUpdateCurrentHostspecAvailability=Failed to update current hostspec availability. Failover.noOperationsAfterConnectionClosed=No operations allowed after connection closed. +Failover.invalidHostListProvider=Incorrect type of host list provider found, please ensure the correct host list provider is specified. The host list provider in use is: ''{0}'', the plugin is expected a cluster-aware host list provider such as the AuroraHostListProvider. + # HikariPooledConnectionProvider HikariPooledConnectionProvider.errorConnectingWithDataSource=Unable to connect to ''{0}'' using the Hikari data source. diff --git a/wrapper/src/test/java/integration/container/aurora/TestAuroraHostListProvider.java b/wrapper/src/test/java/integration/container/aurora/TestAuroraHostListProvider.java index 75a58321..b6702881 100644 --- a/wrapper/src/test/java/integration/container/aurora/TestAuroraHostListProvider.java +++ b/wrapper/src/test/java/integration/container/aurora/TestAuroraHostListProvider.java @@ -24,12 +24,11 @@ import software.amazon.jdbc.hostlistprovider.AuroraHostListProvider; public class TestAuroraHostListProvider extends AuroraHostListProvider { public TestAuroraHostListProvider( - String driverProtocol, HostListProviderService hostListProviderService, Properties properties, String originalUrl) { - super(driverProtocol, hostListProviderService, properties, originalUrl); + super(properties, originalUrl, hostListProviderService, "", "", ""); } public static void clearCache() { diff --git a/wrapper/src/test/java/integration/container/tests/DataSourceTests.java b/wrapper/src/test/java/integration/container/tests/DataSourceTests.java index a9fe0648..e5499185 100644 --- a/wrapper/src/test/java/integration/container/tests/DataSourceTests.java +++ b/wrapper/src/test/java/integration/container/tests/DataSourceTests.java @@ -116,6 +116,7 @@ public class DataSourceTests { ds.setJdbcUrl(ConnectionStringHelper.getUrl()); final Properties targetDataSourceProps = new Properties(); + targetDataSourceProps.setProperty(PropertyDefinition.PLUGINS.name, ""); ds.setTargetDataSourceProperties(targetDataSourceProps); final Hashtable<String, Object> env = new Hashtable<>(); diff --git a/wrapper/src/test/java/software/amazon/jdbc/PluginServiceImplTests.java b/wrapper/src/test/java/software/amazon/jdbc/PluginServiceImplTests.java index c2cedf96..764ec7a1 100644 --- a/wrapper/src/test/java/software/amazon/jdbc/PluginServiceImplTests.java +++ b/wrapper/src/test/java/software/amazon/jdbc/PluginServiceImplTests.java @@ -654,7 +654,9 @@ public class PluginServiceImplTests { when(target.getDialect()).thenReturn(dialect); when(resultSet.next()).thenReturn(true, false); // Result set contains 1 row. when(resultSet.getString(eq(1))).thenReturn("ip"); - when(hostListProvider.identifyConnection(eq(newConnection))).thenReturn(new HostSpec("instance")); + if (dialect instanceof AuroraPgDialect) { + when(hostListProvider.identifyConnection(eq(newConnection))).thenReturn(new HostSpec("instance")); + } target.fillAliases(newConnection, empty); diff --git a/wrapper/src/test/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProviderTest.java b/wrapper/src/test/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProviderTest.java index 006773de..80172672 100644 --- a/wrapper/src/test/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProviderTest.java +++ b/wrapper/src/test/java/software/amazon/jdbc/hostlistprovider/AuroraHostListProviderTest.java @@ -62,7 +62,6 @@ import software.amazon.jdbc.PluginService; import software.amazon.jdbc.dialect.AuroraMysqlDialect; import software.amazon.jdbc.dialect.AuroraPgDialect; import software.amazon.jdbc.dialect.Dialect; -import software.amazon.jdbc.dialect.TopologyAwareDatabaseCluster; import software.amazon.jdbc.hostlistprovider.AuroraHostListProvider.FetchTopologyResult; class AuroraHostListProviderTest { @@ -75,7 +74,7 @@ class AuroraHostListProviderTest { @Mock private ResultSet mockResultSet; @Mock private PluginService mockPluginService; @Mock private HostListProviderService mockHostListProviderService; - @Mock(extraInterfaces = TopologyAwareDatabaseCluster.class) private Dialect mockTopologyAwareDialect; + @Mock Dialect mockTopologyAwareDialect; @Captor private ArgumentCaptor<String> queryCaptor; private AutoCloseable closeable; @@ -91,7 +90,6 @@ class AuroraHostListProviderTest { when(mockConnection.createStatement()).thenReturn(mockStatement); when(mockStatement.executeQuery(queryCaptor.capture())).thenReturn(mockResultSet); when(mockHostListProviderService.getDialect()).thenReturn(mockTopologyAwareDialect); - when(((TopologyAwareDatabaseCluster) mockTopologyAwareDialect).getNodeIdQuery()).thenReturn("nodeIdQuery"); } @AfterEach @@ -100,10 +98,14 @@ class AuroraHostListProviderTest { closeable.close(); } - private AuroraHostListProvider getAuroraHostListProvider(String protocol, - HostListProviderService mockHostListProviderService, String originalUrl) throws SQLException { + private AuroraHostListProvider getAuroraHostListProvider( + HostListProviderService mockHostListProviderService, + String originalUrl) throws SQLException { AuroraHostListProvider provider = new AuroraHostListProvider( - protocol, mockHostListProviderService, new Properties(), originalUrl); + new Properties(), + originalUrl, + mockHostListProviderService, + "foo", "bar", "baz"); provider.init(); // provider.clusterId = "cluster-id"; return provider; @@ -112,7 +114,7 @@ class AuroraHostListProviderTest { @Test void testGetTopology_returnCachedTopology() throws SQLException { auroraHostListProvider = Mockito.spy( - getAuroraHostListProvider("protocol", mockHostListProviderService, "protocol://url/")); + getAuroraHostListProvider(mockHostListProviderService, "protocol://url/")); final Instant lastUpdated = Instant.now(); final List<HostSpec> expected = hosts; @@ -127,7 +129,7 @@ class AuroraHostListProviderTest { @Test void testGetTopology_withForceUpdate_returnsUpdatedTopology() throws SQLException { auroraHostListProvider = Mockito.spy( - getAuroraHostListProvider("jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); + getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url")); auroraHostListProvider.isInitialized = true; AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, hosts, defaultRefreshRateNano); @@ -144,7 +146,7 @@ class AuroraHostListProviderTest { @Test void testGetTopology_noForceUpdate_queryReturnsEmptyHostList() throws SQLException { auroraHostListProvider = Mockito.spy( - getAuroraHostListProvider("jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); + getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url")); auroraHostListProvider.clusterId = "cluster-id"; auroraHostListProvider.isInitialized = true; @@ -162,7 +164,7 @@ class AuroraHostListProviderTest { @Test void testGetTopology_withForceUpdate_returnsInitialHostList() throws SQLException { auroraHostListProvider = Mockito.spy( - getAuroraHostListProvider("jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); + getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url")); auroraHostListProvider.clear(); doReturn(new ArrayList<>()).when(auroraHostListProvider).queryForTopology(mockConnection); @@ -183,35 +185,26 @@ class AuroraHostListProviderTest { when(mockResultSet.getBoolean(eq(2))).thenReturn(true); when(mockResultSet.getString(eq(1))).thenReturn("mysql"); - when(((TopologyAwareDatabaseCluster) mockTopologyAwareDialect).getTopologyQuery()) - .thenReturn(new AuroraMysqlDialect().getTopologyQuery()); auroraHostListProvider = - getAuroraHostListProvider("mysql", mockHostListProviderService, "mysql://url/"); + getAuroraHostListProvider(mockHostListProviderService, "mysql://url/"); List<HostSpec> hosts = auroraHostListProvider.queryForTopology(mockConnection); - String query = queryCaptor.getValue(); assertEquals(expectedMySQL, hosts); - assertEquals(new AuroraMysqlDialect().getTopologyQuery(), query); when(mockResultSet.next()).thenReturn(true, false); when(mockResultSet.getString(eq(1))).thenReturn("postgresql"); - when(((TopologyAwareDatabaseCluster) mockTopologyAwareDialect).getTopologyQuery()) - .thenReturn(new AuroraPgDialect().getTopologyQuery()); - auroraHostListProvider = - getAuroraHostListProvider("postgresql", mockHostListProviderService, "postgresql://url/"); + getAuroraHostListProvider(mockHostListProviderService, "postgresql://url/"); hosts = auroraHostListProvider.queryForTopology(mockConnection); - query = queryCaptor.getValue(); assertEquals(expectedPostgres, hosts); - assertEquals(new AuroraPgDialect().getTopologyQuery(), query); } @Test void testQueryForTopology_queryResultsInException() throws SQLException { auroraHostListProvider = - getAuroraHostListProvider("protocol", mockHostListProviderService, "protocol://url/"); + getAuroraHostListProvider(mockHostListProviderService, "protocol://url/"); when(mockStatement.executeQuery(queryCaptor.capture())).thenThrow(new SQLSyntaxErrorException()); assertThrows( @@ -221,8 +214,7 @@ class AuroraHostListProviderTest { @Test void testGetCachedTopology_returnCachedTopology() throws SQLException { - auroraHostListProvider = getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url"); + auroraHostListProvider = getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url"); final List<HostSpec> expected = hosts; AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, expected, defaultRefreshRateNano); @@ -233,14 +225,12 @@ class AuroraHostListProviderTest { @Test void testGetCachedTopology_returnNull() throws InterruptedException, SQLException { - auroraHostListProvider = getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url"); + auroraHostListProvider = getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url"); // Test getCachedTopology with empty topology. assertNull(auroraHostListProvider.getCachedTopology()); auroraHostListProvider.clear(); - auroraHostListProvider = getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url"); + auroraHostListProvider = getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url"); final long refreshRateOneNanosecond = 1; AuroraHostListProvider.topologyCache.put(auroraHostListProvider.clusterId, hosts, refreshRateOneNanosecond); TimeUnit.NANOSECONDS.sleep(1); @@ -254,7 +244,7 @@ class AuroraHostListProviderTest { AuroraHostListProvider.clearAll(); AuroraHostListProvider provider1 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://cluster-a.domain.com/")); provider1.init(); final List<HostSpec> topologyClusterA = Arrays.asList( @@ -271,7 +261,7 @@ class AuroraHostListProviderTest { assertEquals(topologyClusterA, topologyProvider1); AuroraHostListProvider provider2 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://cluster-b.domain.com/")); provider2.init(); assertNull(provider2.getCachedTopology()); @@ -293,7 +283,7 @@ class AuroraHostListProviderTest { AuroraHostListProvider.clearAll(); AuroraHostListProvider provider1 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://cluster-a.cluster-xyz.us-east-2.rds.amazonaws.com/")); provider1.init(); final List<HostSpec> topologyClusterA = Arrays.asList( @@ -309,7 +299,7 @@ class AuroraHostListProviderTest { assertEquals(topologyClusterA, topologyProvider1); AuroraHostListProvider provider2 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://cluster-a.cluster-xyz.us-east-2.rds.amazonaws.com/")); provider2.init(); @@ -328,7 +318,7 @@ class AuroraHostListProviderTest { AuroraHostListProvider.clearAll(); AuroraHostListProvider provider1 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://cluster-a.cluster-xyz.us-east-2.rds.amazonaws.com/")); provider1.init(); final List<HostSpec> topologyClusterA = Arrays.asList( @@ -344,7 +334,7 @@ class AuroraHostListProviderTest { assertEquals(topologyClusterA, topologyProvider1); AuroraHostListProvider provider2 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://instance-a-3.xyz.us-east-2.rds.amazonaws.com/")); provider2.init(); @@ -363,7 +353,7 @@ class AuroraHostListProviderTest { AuroraHostListProvider.clearAll(); AuroraHostListProvider provider1 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://instance-a-2.xyz.us-east-2.rds.amazonaws.com/")); provider1.init(); final List<HostSpec> topologyClusterA = Arrays.asList( @@ -381,7 +371,7 @@ class AuroraHostListProviderTest { // AuroraHostListProvider.logCache(); AuroraHostListProvider provider2 = Mockito.spy( - getAuroraHostListProvider("jdbc:something://", mockHostListProviderService, + getAuroraHostListProvider(mockHostListProviderService, "jdbc:something://cluster-a.cluster-xyz.us-east-2.rds.amazonaws.com/")); provider2.init(); @@ -411,7 +401,6 @@ class AuroraHostListProviderTest { @Test void testIdentifyConnectionWithInvalidNodeIdQuery() throws SQLException { auroraHostListProvider = Mockito.spy(getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); @@ -425,7 +414,6 @@ class AuroraHostListProviderTest { @Test void testIdentifyConnectionNullTopology() throws SQLException { auroraHostListProvider = Mockito.spy(getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); auroraHostListProvider.clusterInstanceTemplate = new HostSpec("?.pattern"); @@ -443,7 +431,6 @@ class AuroraHostListProviderTest { new HostSpec("instance-a-1.xyz.us-east-2.rds.amazonaws.com", HostSpec.NO_PORT, HostRole.WRITER)); auroraHostListProvider = Mockito.spy(getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); when(mockResultSet.next()).thenReturn(true); @@ -463,7 +450,6 @@ class AuroraHostListProviderTest { final List<HostSpec> cachedTopology = Collections.singletonList(expectedHost); auroraHostListProvider = Mockito.spy(getAuroraHostListProvider( - "jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); when(mockResultSet.next()).thenReturn(true); @@ -478,7 +464,7 @@ class AuroraHostListProviderTest { @Test void testGetTopology_StaleRecord() throws SQLException { auroraHostListProvider = Mockito.spy( - getAuroraHostListProvider("jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); + getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url")); auroraHostListProvider.isInitialized = true; final String hostName1 = "hostName1"; @@ -506,7 +492,7 @@ class AuroraHostListProviderTest { @Test void testGetTopology_InvalidLastUpdatedTimestamp() throws SQLException { auroraHostListProvider = Mockito.spy( - getAuroraHostListProvider("jdbc:someprotocol://", mockHostListProviderService, "jdbc:someprotocol://url")); + getAuroraHostListProvider(mockHostListProviderService, "jdbc:someprotocol://url")); auroraHostListProvider.isInitialized = true; final String hostName = "hostName"; diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/AuroraConnectionTrackerPluginTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/AuroraConnectionTrackerPluginTest.java index c853d2ea..8452056d 100644 --- a/wrapper/src/test/java/software/amazon/jdbc/plugin/AuroraConnectionTrackerPluginTest.java +++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/AuroraConnectionTrackerPluginTest.java @@ -46,7 +46,6 @@ import software.amazon.jdbc.HostSpec; import software.amazon.jdbc.JdbcCallable; import software.amazon.jdbc.PluginService; import software.amazon.jdbc.dialect.Dialect; -import software.amazon.jdbc.dialect.TopologyAwareDatabaseCluster; import software.amazon.jdbc.plugin.failover.FailoverSQLException; import software.amazon.jdbc.util.RdsUrlType; import software.amazon.jdbc.util.RdsUtils; @@ -58,7 +57,7 @@ public class AuroraConnectionTrackerPluginTest { @Mock Statement mockStatement; @Mock ResultSet mockResultSet; @Mock PluginService mockPluginService; - @Mock(extraInterfaces = TopologyAwareDatabaseCluster.class) private Dialect mockTopologyAwareDialect; + @Mock Dialect mockTopologyAwareDialect; @Mock RdsUtils mockRdsUtils; @Mock OpenedConnectionTracker mockTracker; @Mock JdbcCallable<Connection, SQLException> mockConnectionFunction; @@ -80,7 +79,6 @@ public class AuroraConnectionTrackerPluginTest { when(mockRdsUtils.identifyRdsType(any())).thenReturn(RdsUrlType.RDS_INSTANCE); when(mockPluginService.getCurrentConnection()).thenReturn(mockConnection); when(mockPluginService.getDialect()).thenReturn(mockTopologyAwareDialect); - when(((TopologyAwareDatabaseCluster) mockTopologyAwareDialect).getNodeIdQuery()).thenReturn("any"); } @AfterEach diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/AwsSecretsManagerConnectionPluginTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/AwsSecretsManagerConnectionPluginTest.java index 9dae2da4..0a551715 100644 --- a/wrapper/src/test/java/software/amazon/jdbc/plugin/AwsSecretsManagerConnectionPluginTest.java +++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/AwsSecretsManagerConnectionPluginTest.java @@ -59,7 +59,6 @@ import software.amazon.jdbc.PluginServiceImpl; import software.amazon.jdbc.PropertyDefinition; import software.amazon.jdbc.dialect.Dialect; import software.amazon.jdbc.dialect.DialectManager; -import software.amazon.jdbc.dialect.TopologyAwareDatabaseCluster; import software.amazon.jdbc.exceptions.ExceptionHandler; import software.amazon.jdbc.exceptions.ExceptionManager; import software.amazon.jdbc.exceptions.MySQLExceptionHandler; @@ -99,7 +98,7 @@ public class AwsSecretsManagerConnectionPluginTest { @Mock JdbcCallable<Connection, SQLException> connectFunc; @Mock PluginServiceImpl mockService; @Mock ConnectionPluginManager mockConnectionPluginManager; - @Mock(extraInterfaces = TopologyAwareDatabaseCluster.class) private Dialect mockTopologyAwareDialect; + @Mock Dialect mockTopologyAwareDialect; @Mock DialectManager mockDialectManager; @BeforeEach diff --git a/wrapper/src/test/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPluginTest.java b/wrapper/src/test/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPluginTest.java index 34624e9e..f6d1f76c 100644 --- a/wrapper/src/test/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPluginTest.java +++ b/wrapper/src/test/java/software/amazon/jdbc/plugin/failover/FailoverConnectionPluginTest.java @@ -68,17 +68,28 @@ class FailoverConnectionPluginTest { private static final String MONITOR_METHOD_NAME = "Connection.executeQuery"; private static final Object[] EMPTY_ARGS = {}; - @Mock PluginService mockPluginService; - @Mock Connection mockConnection; - @Mock HostSpec mockHostSpec; - @Mock HostListProviderService mockHostListProviderService; - @Mock AuroraHostListProvider mockHostListProvider; - @Mock JdbcCallable<Void, SQLException> mockInitHostProviderFunc; - @Mock ClusterAwareReaderFailoverHandler mockReaderFailoverHandler; - @Mock ClusterAwareWriterFailoverHandler mockWriterFailoverHandler; - @Mock ReaderFailoverResult mockReaderResult; - @Mock WriterFailoverResult mockWriterResult; - @Mock JdbcCallable<ResultSet, SQLException> mockSqlFunction; + @Mock + PluginService mockPluginService; + @Mock + Connection mockConnection; + @Mock + HostSpec mockHostSpec; + @Mock + HostListProviderService mockHostListProviderService; + @Mock + AuroraHostListProvider mockHostListProvider; + @Mock + JdbcCallable<Void, SQLException> mockInitHostProviderFunc; + @Mock + ClusterAwareReaderFailoverHandler mockReaderFailoverHandler; + @Mock + ClusterAwareWriterFailoverHandler mockWriterFailoverHandler; + @Mock + ReaderFailoverResult mockReaderResult; + @Mock + WriterFailoverResult mockWriterResult; + @Mock + JdbcCallable<ResultSet, SQLException> mockSqlFunction; private final Properties properties = new Properties(); private FailoverConnectionPlugin plugin; @@ -113,7 +124,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); @@ -121,21 +131,19 @@ class FailoverConnectionPluginTest { } @Test - void test_initHostProvider_withStaticHostListProvider() throws SQLException { + void test_initHostProvider_withStaticHostListProvider() { when(mockHostListProviderService.isStaticHostListProvider()).thenReturn(true); initializePlugin(); - plugin.initHostProvider( - "initialUrl", - mockHostListProviderService, - mockInitHostProviderFunc, - () -> mockHostListProvider, - () -> mockReaderFailoverHandler, - () -> mockWriterFailoverHandler); - - verify(mockHostListProviderService).isStaticHostListProvider(); - verify(mockHostListProviderService).setHostListProvider(eq(mockHostListProvider)); + assertThrows(SQLException.class, () -> { + plugin.initHostProvider( + "initialUrl", + mockHostListProviderService, + mockInitHostProviderFunc, + () -> mockReaderFailoverHandler, + () -> mockWriterFailoverHandler); + }); } @Test @@ -149,7 +157,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); @@ -298,7 +305,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); @@ -327,7 +333,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); @@ -349,7 +354,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); @@ -371,7 +375,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); @@ -396,7 +399,6 @@ class FailoverConnectionPluginTest { "initialUrl", mockHostListProviderService, mockInitHostProviderFunc, - () -> mockHostListProvider, () -> mockReaderFailoverHandler, () -> mockWriterFailoverHandler); [parent: 9be007da2ae4]