From 3375554e14eb793d636dd1b0d8ffb94c3d501003 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Wed, 4 Nov 2026 10:16:17 -0700 Subject: [PATCH 1/5] fix: fail fast when failover can't resolve instance hosts behind an IP or custom domain When the connection host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set, instance hosts are built as bare instance identifiers that usually don't resolve, so failover retried until failover_timeout_sec (300 s by default). - On Aurora and RDS Multi-AZ DB clusters, connections that list failover explicitly in wrapper_plugins now raise at startup, naming the host and both fixes. With the default plugin list, a warning is logged once per host. - The topology monitor records unresolvable instance hosts as a fatal configuration error, so writer failover raises FailoverFailedError right away. Reader failover and writer connection attempts check for the same condition. Temporary DNS failures and other network errors still retry. - gdb_failover on a database identified as a regional cluster gets its own message explaining that global_cluster_instance_host_patterns doesn't apply. - Driver error handlers gain unknown_host_error? for mysql2, pg and trilogy. --- CHANGELOG.md | 1 + lib/aws_advanced_ruby_driver_wrapper.rb | 1 + .../errors.rb | 17 ++ .../errors/error_handler.rb | 21 +++ .../errors/mysql_error_handler.rb | 6 + .../errors/pg_error_handler.rb | 8 +- .../errors/trilogy_error_handler.rb | 9 ++ .../host/global_aurora_host_list_provider.rb | 6 + .../host/rds_host_list_provider.rb | 13 ++ .../monitoring/cluster_topology_monitor.rb | 53 +++++- .../plugins/failover_plugin.rb | 131 ++++++++++++--- .../plugins/gdb/gdb_failover_plugin.rb | 22 +++ .../services/dialect_service.rb | 7 + .../utils/rds_utils.rb | 8 +- .../utils/retry_util.rb | 17 +- spec/unit/errors/mysql_error_handler_spec.rb | 25 +++ spec/unit/errors/pg_error_handler_spec.rb | 30 ++++ .../unit/errors/trilogy_error_handler_spec.rb | 41 +++++ spec/unit/failover_plugin_spec.rb | 153 +++++++++++++++++- .../global_aurora_host_list_provider_spec.rb | 12 ++ spec/unit/host/rds_host_list_provider_spec.rb | 42 +++++ .../cluster_topology_monitor_spec.rb | 124 ++++++++++++++ .../global_cluster_topology_monitor_spec.rb | 8 + .../plugins/gdb/gdb_failover_plugin_spec.rb | 50 +++++- spec/unit/retry_util_spec.rb | 24 +++ 25 files changed, 792 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad99cfd7..8174e560 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - The Blue/Green Deployment plugin now invalidates connections that were opened to the old blue environment before a switchover, controlled by the new `bg_drop_blue_connections` property (default `true`). Once a switchover is confirmed, each such connection is closed the next time it is used, so with the failover plugin enabled it fails over through Blue/Green routing and raises `FailoverSuccessError` (or `TransactionStateUnknownError` inside a transaction), and without failover the driver raises its closed-connection error. ### :crab: Changed +- Connections with `failover` explicitly in `wrapper_plugins` now fail at startup when the host isn't a recognized RDS endpoint and `cluster_instance_host_pattern` isn't set; previously failover failed after `failover_timeout_sec`. The check applies only to Aurora and RDS Multi-AZ DB clusters. When `failover` comes from the default plugin list, the wrapper logs a warning instead, and a failover in that setup now raises `FailoverFailedError` as soon as an instance host can't be resolved, with a message that names `cluster_instance_host_pattern`. The same applies to `gdb_failover` when the host isn't a recognized RDS endpoint, `cluster_instance_host_pattern` isn't set, and the database is identified as a regional cluster rather than a Global Database (for example with `wrapper_dialect: aurora-pg`), since `global_cluster_instance_host_patterns` is only read for Global Databases; the error explains how to fix the dialect or switch to `failover` ([PR #235](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/235), [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/enhanced-failover#host-pattern)). - Simplified the KMS Encryption Plugin's PostgreSQL trigger SQL to read the column's HMAC key from `key_storage` for every row. Re-run the trigger SQL from the [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/using-plugins/kms-encryption#postgresql-1) to update existing deployments ([PR #216](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/216)). ## [1.0.1] - 2026-10-07 diff --git a/lib/aws_advanced_ruby_driver_wrapper.rb b/lib/aws_advanced_ruby_driver_wrapper.rb index 2a699858..5fa78e15 100644 --- a/lib/aws_advanced_ruby_driver_wrapper.rb +++ b/lib/aws_advanced_ruby_driver_wrapper.rb @@ -72,6 +72,7 @@ def self.clear_caches Utils::RdsUtils.clear_cache Services::DialectService.known_endpoint_dialects.clear Services::HostService.clear_id_cache + Plugins::FailoverPlugin::MISSING_PATTERN_WARNED_HOSTS.clear if defined?(Plugins::FailoverPlugin) end # Runs in a forked child (see ForkHook). Only the forking thread survives a fork, so every background diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors.rb b/lib/aws_advanced_ruby_driver_wrapper/errors.rb index 5fd2d523..8f423e38 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors.rb @@ -56,5 +56,22 @@ class SecretsManagerAuthError < AwsError; end class PluginConflictError < AwsError; end class BlueGreenTimeoutError < AwsError; end class BlueGreenSwitchoverError < AwsError; end + + # Raised when a DB instance host can't be resolved because the connection host isn't a recognized RDS + # endpoint and cluster_instance_host_pattern isn't set, so instance hosts were built as bare instance + # identifiers. This is a configuration error, so retrying won't help. + class UnresolvableInstanceHostError < AwsError + # @param instance_host [String] the DB instance host that could not be resolved + # @param connection_host [String] the host the application connected with + def initialize(instance_host, connection_host) + super( + "Unable to resolve the DB instance host '#{instance_host}' while discovering the cluster topology. " \ + "The connection host '#{connection_host}' is not a recognized RDS endpoint and cluster_instance_host_pattern " \ + 'is not set, so the wrapper built a DB instance host that cannot be resolved. This is a configuration error ' \ + 'rather than a transient failover condition. Set cluster_instance_host_pattern to a DNS pattern that resolves ' \ + "to the cluster's instances (for example, '?.XXX.us-east-1.rds.amazonaws.com')." + ) + end + end end end diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb index 6b67fb99..2d4405d2 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb @@ -17,6 +17,8 @@ module AwsAdvancedRubyDriverWrapper module Errors module ErrorHandler + TEMPORARY_RESOLUTION_FAILURE = 'temporary failure' + def network_error?(error) check_cause_chain(error) { |sql_state, _| network_error_by_sql_state?(sql_state) } end @@ -41,8 +43,27 @@ def read_only_error_by_sql_state?(sql_state, error_code = nil) raise NotImplementedError end + # Whether the error, or any error in its cause chain, is a driver error meaning the host name does not + # exist. Temporary resolver failures ("Temporary failure in name resolution") don't count, since the + # same host may resolve on the next attempt. + # + # @param error [Exception] + # @return [Boolean] + def unknown_host_error?(error) + check_cause_chain(error) { |_, current| unknown_host?(current) && !temporary_resolution_failure?(current) } + end + private + # Driver-specific check for an error raised when the host name could not be resolved. + def unknown_host?(_error) + false + end + + def temporary_resolution_failure?(error) + [error, error.cause].compact.any? { |e| e.message.to_s.downcase.include?(TEMPORARY_RESOLUTION_FAILURE) } + end + def extract_sql_state(error) @driver_dialect.sql_state(error) end diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb index 771db235..252abd32 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb @@ -31,6 +31,7 @@ class MysqlErrorHandler 2026, # CR_SSL_CONNECTION_ERROR 2055 # CR_SERVER_LOST_EXTENDED (lost connection with state info) ].freeze + UNKNOWN_HOST_ERROR_CODE = 2005 # CR_UNKNOWN_HOST def initialize(driver_dialect) @driver_dialect = driver_dialect @@ -67,6 +68,11 @@ def read_only_error_by_sql_state?(sql_state, error_code = nil) private + def unknown_host?(error) + defined?(Mysql2::Error) && error.is_a?(Mysql2::Error) && + error.respond_to?(:error_number) && error.error_number == UNKNOWN_HOST_ERROR_CODE + end + def connection_error_network?(error) return false unless defined?(Mysql2::Error::ConnectionError) && error.is_a?(Mysql2::Error::ConnectionError) diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb index 0d6ca58e..740a2c5e 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb @@ -25,6 +25,7 @@ class PgErrorHandler ACCESS_ERROR_SQL_STATES = Set['08004', '28P01', '28000'].freeze READ_ONLY_SQL_STATE = '25006' LOGIN_ERROR_MESSAGE = 'authentication failed' + UNKNOWN_HOST_MESSAGE = 'could not translate host name' NETWORK_ERROR_MESSAGES = [ 'unexpected eof', 'closed the connection unexpectedly', @@ -47,7 +48,7 @@ class PgErrorHandler CONNECT_FAILURE_MESSAGES = [ 'connection refused', 'timeout expired', - 'could not translate host name', + UNKNOWN_HOST_MESSAGE, 'no route to host', 'network is unreachable', 'host is unreachable', @@ -107,6 +108,11 @@ def read_only_error_by_sql_state?(sql_state, _error_code = nil) private + def unknown_host?(error) + defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad) && + error.message.to_s.downcase.include?(UNKNOWN_HOST_MESSAGE) + end + def connection_bad_network_error?(error) return false unless defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad) diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb index bc34f6e5..882b3459 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb @@ -36,6 +36,9 @@ class TrilogyErrorHandler # credential was not accepted, so for login-retry purposes it is a login error. AUTH_PROTOCOL_VIOLATION = 'trilogy_auth_recv' PROTOCOL_VIOLATION_MARKER = 'TRILOGY_PROTOCOL_VIOLATION' + # Raised by trilogy's C extension when it resolves the host itself. Newer versions resolve the host in + # Ruby instead and raise a connection error caused by a SocketError. + DNS_ERROR_MARKER = 'TRILOGY_DNS_ERROR' def initialize(driver_dialect) @driver_dialect = driver_dialect @@ -81,6 +84,12 @@ def network_failure?(error) !LOGIN_ERROR_CODES.include?(code) && code != LOCK_WAIT_TIMEOUT_ERROR_CODE end + def unknown_host?(error) + return false unless defined?(::Trilogy::ConnectionError) && error.is_a?(::Trilogy::ConnectionError) + + error.cause.is_a?(SocketError) || error.message.to_s.include?(DNS_ERROR_MARKER) + end + def error_code(error) error.respond_to?(:error_code) ? error.error_code : nil end diff --git a/lib/aws_advanced_ruby_driver_wrapper/host/global_aurora_host_list_provider.rb b/lib/aws_advanced_ruby_driver_wrapper/host/global_aurora_host_list_provider.rb index da9025ee..75eddc2a 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/host/global_aurora_host_list_provider.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/host/global_aurora_host_list_provider.rb @@ -48,6 +48,12 @@ def force_refresh(verify_writer, timeout_sec) nil end + # Instance hosts come from the region templates in global_cluster_instance_host_patterns, which is + # required, so they never depend on the bare instance template built for a non-RDS connection host. + def instance_host_pattern_missing? + false + end + private def build_instance_templates_by_region diff --git a/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb b/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb index 461558a2..ac038a08 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb @@ -46,6 +46,8 @@ def initialize(service_container:, topology_utils:) props = @service_container.connection_service.wrapper_props @cluster_id = PropertyDefinition::CLUSTER_ID.get_string(props) @instance_template = build_instance_template(props) + @instance_host_pattern_missing = PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.get(props).nil? && + @instance_template.host == Utils::RdsUtils::BARE_INSTANCE_HOST_PATTERN validate_host_pattern!(@instance_template.host) @rds_url_type = Utils::RdsUtils.identify_rds_type(initial_host_info.host) @@ -92,6 +94,7 @@ def force_refresh(verify_writer, timeout_sec) service_container: @service_container, cluster_id: @cluster_id, instance_template: @instance_template, + instance_host_pattern_missing: instance_host_pattern_missing?, topology_utils: @topology_utils, monitoring_driver_props: @monitoring_driver_props, monitoring_wrapper_props: @monitoring_wrapper_props @@ -107,6 +110,16 @@ def stop_monitor @service_container.monitor_service.stop_and_remove(:cluster_topology, @cluster_id) end + # Whether DB instance hosts can't be derived from the topology. This is the case when the connection + # host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set: the instance template + # is then a bare '?', so instance hosts are bare instance identifiers that usually don't resolve. An + # explicitly set '?' pattern doesn't count, since bare identifiers may resolve in the user's environment. + # + # @return [Boolean] + def instance_host_pattern_missing? + @instance_host_pattern_missing + end + private def stored_topology diff --git a/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb b/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb index 3d512a11..e73c53f6 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb @@ -16,11 +16,13 @@ require_relative 'monitor' require_relative 'monitor_connection' +require_relative '../errors' require_relative '../host/host_role' require_relative '../host/host_availability' require_relative '../utils/events/monitor_reset_event' require_relative '../utils/rds_utils' require_relative '../property_definition' +require 'concurrent' require 'timeout' module AwsAdvancedRubyDriverWrapper @@ -39,6 +41,8 @@ class ClusterTopologyMonitor < Monitor # @param service_container [Services::ServiceContainer] # @param cluster_id [String] # @param instance_template [Host::HostInfo] + # @param instance_host_pattern_missing [Boolean] whether instance hosts are bare instance identifiers + # because the connection host isn't an RDS endpoint and cluster_instance_host_pattern isn't set # @param topology_utils [Object] responds to #query_topology, #writer_instance? # @param monitoring_driver_props [Hash] driver props with prefixed driver overrides merged in # @param monitoring_wrapper_props [Hash] wrapper prop overrides extracted from prefixed props @@ -48,13 +52,15 @@ def initialize( instance_template:, topology_utils:, monitoring_driver_props:, - monitoring_wrapper_props: {} + monitoring_wrapper_props: {}, + instance_host_pattern_missing: false ) super(termination_timeout_sec: TERMINATION_TIMEOUT_SEC) @service_container = service_container @cluster_id = cluster_id @instance_template = instance_template + @instance_host_pattern_missing = instance_host_pattern_missing @topology_utils = topology_utils @monitoring_driver_props = monitoring_driver_props @monitoring_wrapper_props = monitoring_wrapper_props @@ -89,6 +95,9 @@ def initialize( @completed_one_cycle = {} @latest_topology = nil @stable_start_time = 0 + # A non-recoverable configuration error found by an instance monitor. Once set, threads waiting to + # verify the writer raise it instead of waiting out their timeout. Cleared when the monitor is reset. + @fatal_error = Concurrent::AtomicReference.new end # Forces a topology refresh, ignoring any cached topology. Blocks until updated or raises on timeout. @@ -389,11 +398,45 @@ def attempt_host_connection(host_info, attempts) rescue StandardError => e raise if @service_container.dialect_service.login_error?(e) + if unresolvable_due_to_misconfiguration?(e) + # Retrying can't help, since the host is a bare instance identifier that will never resolve. + record_fatal_error(Errors::UnresolvableInstanceHostError.new(host_info.host, initial_host_info&.host)) + return nil + end + logger.debug("[#{@cluster_id}] Connection to #{host_info.host} failed: #{e.message}") sleep(calculate_backoff(attempts)) nil end + # Whether a connection failure means the host can never be resolved because of the configuration: + # the connection host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set, + # so instance hosts were built from a bare '?' template. Other unresolved hosts, such as a real + # instance endpoint during a failover, are retried as usual. + # + # @param error [StandardError] + # @return [Boolean] + def unresolvable_due_to_misconfiguration?(error) + @instance_host_pattern_missing && @service_container.dialect_service.unknown_host_error?(error) + end + + # Records a non-recoverable configuration error, stops the instance monitors, and wakes threads + # waiting to verify the writer so they raise it right away. + # + # @param error [Errors::AwsError] + def record_fatal_error(error) + logger.error("[#{@cluster_id}] #{error.message}") if @fatal_error.compare_and_set(nil, error) + @stop_instance_monitors = true + @topology_mutex.synchronize { @topology_cv.broadcast } + end + + # @raise [Errors::AwsError] the recorded fatal error, if any. A copy is raised so that each waiting + # thread gets its own backtrace. + def raise_if_fatal_error + fatal = @fatal_error.get + raise fatal.dup if fatal + end + def check_host_role(conn) @service_container.dialect_service.db_dialect.host_role(conn) rescue StandardError => e @@ -537,7 +580,11 @@ def update_hosts_availability(hosts) # --- force_refresh support --- + # A recorded fatal error is only raised to callers verifying the writer, which is what failover does. + # Other topology reads, such as the host list refresh behind every new connection, keep getting the + # cached topology or a timeout as before, so the misconfiguration doesn't stop new connections. def wait_for_topology_update(timeout_sec, verify_writer = false) + raise_if_fatal_error if verify_writer current_hosts = stored_hosts @topology_mutex.synchronize do @@ -557,6 +604,7 @@ def wait_for_topology_update(timeout_sec, verify_writer = false) # consistent), so we keep waiting until the cached writer matches the writer this monitor has independently # verified by probing instances directly, or the timeout is hit. while wait_for_topology?(current_hosts, verify_writer) && monotonic_time < deadline && !stopped? + raise_if_fatal_error if verify_writer remaining = deadline - monotonic_time break if remaining <= 0 @@ -564,6 +612,8 @@ def wait_for_topology_update(timeout_sec, verify_writer = false) end end + raise_if_fatal_error if verify_writer + latest = stored_hosts if latest.equal?(current_hosts) raise Timeout::Error, "Topology not updated within #{timeout_sec}s for cluster #{@cluster_id}" @@ -624,6 +674,7 @@ def reset! @verified_writer = false @writer_info = nil @high_refresh_end_time = 0 + @fatal_error.set(nil) clear_topology_cache @topology_mutex.synchronize do diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb index 1578c256..a084222d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb @@ -41,6 +41,12 @@ class FailoverPlugin TELEMETRY_WRITER_FAILOVER = 'failover to writer host' TELEMETRY_READER_FAILOVER = 'failover to replica' + PLUGIN_CODE = 'failover' + + # Connection hosts already warned about a missing cluster_instance_host_pattern, so that the warning is + # logged once per host rather than once per connection. + MISSING_PATTERN_WARNED_HOSTS = Concurrent::Set.new + def initialize(service_container, props = ::Concurrent::Map.new) @service_container = service_container @wrapper_props = props @@ -65,28 +71,9 @@ def initialize(service_container, props = ::Concurrent::Map.new) def connect(host_info, driver_props, is_initial_connection, pipeline_callable) init_failover_mode - - unless PropertyDefinition::ENABLE_CONNECT_FAILOVER.get_bool(@wrapper_props) - return verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable) - end - - topology_host = host_service.hosts.find { |h| h.host_and_port == host_info&.host_and_port } - - if !topology_host.nil? && topology_host.availability == Host::HostAvailability::UNAVAILABLE - host_service.refresh_host_list - return connect_via_failover(is_initial_connection) - end - - begin - conn = verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable) - host_service.refresh_host_list if is_initial_connection - conn - rescue StandardError => e - raise unless trigger_failover?(e) - - host_service.set_availability(host_info, Host::HostAvailability::UNAVAILABLE) - connect_via_failover(is_initial_connection) - end + conn = connect_with_failover(host_info, driver_props, is_initial_connection, pipeline_callable) + check_instance_host_pattern(conn) if is_initial_connection + conn end def execute(method_name, pipeline_callable, *, **, &) @@ -117,6 +104,89 @@ def execute(method_name, pipeline_callable, *, **, &) private + def connect_with_failover(host_info, driver_props, is_initial_connection, pipeline_callable) + unless PropertyDefinition::ENABLE_CONNECT_FAILOVER.get_bool(@wrapper_props) + return verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable) + end + + topology_host = host_service.hosts.find { |h| h.host_and_port == host_info&.host_and_port } + + if !topology_host.nil? && topology_host.availability == Host::HostAvailability::UNAVAILABLE + host_service.refresh_host_list + return connect_via_failover(is_initial_connection) + end + + begin + conn = verified_connection(is_initial_connection, host_info, driver_props, pipeline_callable) + host_service.refresh_host_list if is_initial_connection + conn + rescue StandardError => e + raise unless trigger_failover?(e) + + host_service.set_availability(host_info, Host::HostAvailability::UNAVAILABLE) + connect_via_failover(is_initial_connection) + end + end + + # Failover needs DB instance hosts it can resolve. Whether it has them is only known once the initial + # connection has settled the dialect: cluster dialects (Aurora, RDS Multi-AZ DB cluster) then use an + # RdsHostListProvider, which reports whether the instance host pattern is missing. A single instance or a + # community database never has one, so it isn't affected. When the plugin was listed explicitly in + # wrapper_plugins the missing pattern is a configuration error; when it comes from the default plugin + # list, a warning is logged instead. + # + # @param conn [Object] the initial connection, closed if the check fails + # @raise [Errors::AwsError] if the plugin was requested explicitly and the instance host pattern is missing + def check_instance_host_pattern(conn) + return unless instance_host_pattern_missing? + + host = connection_service.initial_host_info&.host + if plugin_requested_explicitly? + close_quietly(conn) + raise Errors::AwsError, missing_instance_host_pattern_message(host, explicit: true) + end + + logger.warn(missing_instance_host_pattern_message(host, explicit: false)) if MISSING_PATTERN_WARNED_HOSTS.add?(host) + end + + def instance_host_pattern_missing? + provider = host_service.host_list_provider + provider.respond_to?(:instance_host_pattern_missing?) && provider.instance_host_pattern_missing? + end + + # @return [Boolean] whether wrapper_plugins was set by the user. This plugin is loaded, so it is in the list. + def plugin_requested_explicitly? + @wrapper_props.key?(PropertyDefinition::PLUGINS.name) + end + + def missing_instance_host_pattern_message(host, explicit:) + plugin_code = self.class::PLUGIN_CODE + remedy = if explicit + "remove #{plugin_code} from #{PropertyDefinition::PLUGINS.name}" + else + "set #{PropertyDefinition::PLUGINS.name} to a list without #{plugin_code} (it is enabled by default)" + end + + "The connection host '#{host}' is not a recognized RDS endpoint and " \ + "#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} is not set, so the #{plugin_code} plugin cannot " \ + 'build DB instance hosts from the cluster topology and failover will not work. ' \ + "Set #{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} to a DNS pattern that resolves to the " \ + "cluster's instances (for example, '?.XXX.us-east-1.rds.amazonaws.com'), or #{remedy}." + end + + # Raises when a topology host can't be resolved because the instance host pattern is missing. Failover + # can reach a topology host without the topology monitor having probed it first (reader failover always, + # writer failover when the monitor verified the writer through the connection host), so it needs its own + # check to avoid retrying such hosts until failover_timeout_sec. + # + # @raise [Errors::FailoverFailedError] + def raise_if_instance_host_unresolvable(host_info, error) + return unless instance_host_pattern_missing? && dialect_service.unknown_host_error?(error) + + error = Errors::UnresolvableInstanceHostError.new(host_info.host, connection_service.initial_host_info&.host) + raise Errors::FailoverFailedError, error.message + end + def connect_via_failover(is_initial_connection) begin failover @@ -311,8 +381,12 @@ def failover_reader logger.info { 'Starting reader failover' } - unless host_service.force_refresh_host_list?(verify_writer: false, timeout_sec: 0) - raise Errors::FailoverFailedError, 'The request to discover the new topology was unsuccessful' + begin + unless host_service.force_refresh_host_list?(verify_writer: false, timeout_sec: 0) + raise Errors::FailoverFailedError, 'The request to discover the new topology was unsuccessful' + end + rescue Errors::UnresolvableInstanceHostError => e + raise Errors::FailoverFailedError, e.message end begin @@ -344,10 +418,14 @@ def failover_writer end was_in_transaction = @service_container.session_state_service.in_transaction? - result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, deadline: failover_deadline) + result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, + deadline: failover_deadline, + on_connect_error: method(:raise_if_instance_host_unresolvable)) raise Errors::FailoverFailedError, 'Unable to connect to a writer instance' unless result&.connection && result.host_info connection_service.update_current_connection(result.connection, result.host_info) + rescue Errors::UnresolvableInstanceHostError => e + raise Errors::FailoverFailedError, e.message rescue Timeout::Error close_quietly(result&.connection) raise Errors::FailoverFailedError, @@ -467,8 +545,9 @@ def attempt_reader_connection(host_info) end [:unknown, nil] end - rescue StandardError + rescue StandardError => e close_quietly(conn) + raise_if_instance_host_unresolvable(host_info, e) [:failed, nil] end diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb index fcb2c6a8..67fa398d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb @@ -15,6 +15,7 @@ # limitations under the License. require_relative '../failover_plugin' +require_relative '../../db_dialects/dialect_codes' require_relative '../../errors' require_relative '../../host/host_role' require_relative '../../property_definition' @@ -39,6 +40,7 @@ module Gdb # regions are never selected. class GdbFailoverPlugin < FailoverPlugin TELEMETRY_FAILOVER = 'global database failover' + PLUGIN_CODE = 'gdb_failover' def initialize(service_container, props = ::Concurrent::Map.new) super @@ -418,6 +420,26 @@ def failover_reader def failover_writer raise NotImplementedError, "#{self.class} performs failover via #failover" end + + # The instance host pattern can only be missing when the database was identified as a regional cluster: + # for a Global Database, instance hosts come from global_cluster_instance_host_patterns, which is + # required. On a regional cluster that setting is not read, so the message explains how to have the + # database treated as a Global Database, or how to configure the regional cluster instead. + def missing_instance_host_pattern_message(host, **) + pattern_name = PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name + "The connection host '#{host}' is not a recognized RDS endpoint, #{pattern_name} is not set, and the " \ + 'database was identified as a regional cluster rather than an Aurora Global Database, so ' \ + "#{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name} does not apply and the #{PLUGIN_CODE} " \ + 'plugin cannot build DB instance hosts from the cluster topology. If the cluster is a member of a Global ' \ + "Database, set #{PropertyDefinition::DIALECT.name} to '#{global_dialect_code}' (without it, a Global " \ + 'Database is only detected when it spans more than one region). For a standalone cluster, use the ' \ + "failover plugin instead, and set #{pattern_name} to a DNS pattern that resolves to the cluster's " \ + "instances (for example, '?.XXX.us-east-1.rds.amazonaws.com')." + end + + def global_dialect_code + driver_dialect.database_engine == :mysql ? DialectCodes::GLOBAL_AURORA_MYSQL : DialectCodes::GLOBAL_AURORA_PG + end end end end diff --git a/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb b/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb index a341f6e7..28925817 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb @@ -164,6 +164,13 @@ def read_only_error?(error) @error_handler.read_only_error?(error) end + # @param error [Exception] + # @return [Boolean] whether the error means the host name could not be resolved. Custom error + # handlers that don't implement #unknown_host_error? never report one. + def unknown_host_error?(error) + @error_handler.respond_to?(:unknown_host_error?) && @error_handler.unknown_host_error?(error) + end + private # Resolves the initial database dialect from the initial connection info. diff --git a/lib/aws_advanced_ruby_driver_wrapper/utils/rds_utils.rb b/lib/aws_advanced_ruby_driver_wrapper/utils/rds_utils.rb index f93cb26e..b6ff69d3 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/utils/rds_utils.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/utils/rds_utils.rb @@ -46,6 +46,10 @@ module Utils module RdsUtils extend self + # The instance host pattern derived for a host that isn't a recognized RDS endpoint. It has no domain, + # so hosts built from it are bare instance identifiers. + BARE_INSTANCE_HOST_PATTERN = '?' + # Authoritative allow-list of AWS regions that can host an RDS/Aurora endpoint. KNOWN_REGIONS = %w[ af-south-1 @@ -394,11 +398,11 @@ def rds_instance_name(host) def rds_instance_host_pattern(host) prepared = prepared_host(host) - return '?' if blank?(prepared) + return BARE_INSTANCE_HOST_PATTERN if blank?(prepared) groups = cache_match(prepared, *DNS_PATTERNS) domain = groups&.[]('domain') - domain ? "?.#{domain}" : '?' + domain ? "?.#{domain}" : BARE_INSTANCE_HOST_PATTERN end def rds_region(host) diff --git a/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb b/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb index fb18c008..207e1f75 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb @@ -40,10 +40,13 @@ def initialize(service_container) # @param plugin_to_skip [Object] the plugin that should be skipped in the connect pipeline # @param plugin_manager [Services::PluginManager] # @param deadline [Time] the point in time at which to give up + # @param on_connect_error [#call, nil] called with the candidate host and the error when a connection + # attempt fails; it may raise to stop retrying # @return [Result] the new connection and the host it was opened to # @raise [Timeout::Error] if no connection could be established before the deadline - def connect_to_writer(plugin_to_skip, plugin_manager, deadline:) - connect_to_allowed_host(plugin_to_skip, plugin_manager, verify_role: Host::HostRole::WRITER, deadline: deadline) do |allowed_hosts| + def connect_to_writer(plugin_to_skip, plugin_manager, deadline:, on_connect_error: nil) + connect_to_allowed_host(plugin_to_skip, plugin_manager, verify_role: Host::HostRole::WRITER, deadline: deadline, + on_connect_error: on_connect_error) do |allowed_hosts| writer_candidate = @host_service.all_hosts.find { |h| h.role == Host::HostRole::WRITER } if writer_candidate.nil? @@ -70,11 +73,14 @@ def connect_to_writer(plugin_to_skip, plugin_manager, deadline:) # @param deadline [Time] the point in time at which to give up # @param verify_role [Symbol, nil] the role the new connection must report, or nil to accept any host # @param strategy [String] the host selection strategy used to order the candidates + # @param on_connect_error [#call, nil] called with the candidate host and the error when a connection + # attempt fails; it may raise to stop retrying # @yieldparam allowed_hosts [Array] the current allowed hosts # @yieldreturn [Array, nil] the hosts to attempt, or nil/empty to refresh and retry # @return [Result] the new connection and the host it was opened to # @raise [Timeout::Error] if no connection could be established before the deadline - def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_role: nil, strategy: DEFAULT_STRATEGY) + def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_role: nil, strategy: DEFAULT_STRATEGY, + on_connect_error: nil) strategy = DEFAULT_STRATEGY if strategy.nil? || strategy.to_s.empty? loop do @@ -102,7 +108,7 @@ def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_ro break # Give up on this candidate list and refresh the topology. end - result = attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) + result = attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager, on_connect_error) return result if result remaining.delete(candidate) @@ -115,7 +121,7 @@ def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_ro private # @return [Result, nil] the result, or nil if the connection failed or reported the wrong role - def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) + def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager, on_connect_error = nil) conn = plugin_manager.connect(candidate, @connection_service.driver_props, false, plugin_to_skip: plugin_to_skip) # Since the roles in the host list might not be accurate, we execute a query to check the instance's role. @@ -132,6 +138,7 @@ def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) rescue StandardError => e logger.debug { "Exception connecting to #{candidate.host}: #{e.message}" } close_quietly(conn) + on_connect_error&.call(candidate, e) nil end diff --git a/spec/unit/errors/mysql_error_handler_spec.rb b/spec/unit/errors/mysql_error_handler_spec.rb index b15cdce2..296dca9b 100644 --- a/spec/unit/errors/mysql_error_handler_spec.rb +++ b/spec/unit/errors/mysql_error_handler_spec.rb @@ -21,6 +21,31 @@ let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::Mysql2DriverDialect.new } subject(:handler) { described_class.new(driver_dialect) } + describe '#unknown_host_error?' do + it 'is true for an unknown host error' do + error = Mysql2::Error::ConnectionError.new("Unknown MySQL server host 'instance-1' (8)", nil, 2005) + expect(handler.unknown_host_error?(error)).to be(true) + end + + it 'is true when the unknown host error is a cause' do + error = begin + begin + raise Mysql2::Error::ConnectionError.new("Unknown MySQL server host 'instance-1' (8)", nil, 2005) + rescue Mysql2::Error + raise AwsAdvancedRubyDriverWrapper::Errors::AwsError, 'wrapped' + end + rescue AwsAdvancedRubyDriverWrapper::Errors::AwsError => e + e + end + expect(handler.unknown_host_error?(error)).to be(true) + end + + it 'is false for other connection errors' do + error = Mysql2::Error::ConnectionError.new("Can't connect to MySQL server on 'instance-1' (61)", nil, 2003) + expect(handler.unknown_host_error?(error)).to be(false) + end + end + describe '#network_error_by_sql_state?' do it 'returns true for 08 prefix states (except 08004)' do expect(handler.network_error_by_sql_state?('08001')).to be true diff --git a/spec/unit/errors/pg_error_handler_spec.rb b/spec/unit/errors/pg_error_handler_spec.rb index 45b3f3c4..749848c6 100644 --- a/spec/unit/errors/pg_error_handler_spec.rb +++ b/spec/unit/errors/pg_error_handler_spec.rb @@ -21,6 +21,36 @@ let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect.new } subject(:handler) { described_class.new(driver_dialect) } + describe '#unknown_host_error?' do + it 'is true when the host name cannot be translated' do + error = PG::ConnectionBad.new('could not translate host name "instance-1" to address: nodename nor servname provided') + expect(handler.unknown_host_error?(error)).to be(true) + end + + it 'is true when the error is a cause' do + error = begin + begin + raise PG::ConnectionBad, 'could not translate host name "instance-1" to address: Name or service not known' + rescue PG::ConnectionBad + raise AwsAdvancedRubyDriverWrapper::Errors::AwsError, 'wrapped' + end + rescue AwsAdvancedRubyDriverWrapper::Errors::AwsError => e + e + end + expect(handler.unknown_host_error?(error)).to be(true) + end + + it 'is false for a temporary resolver failure' do + error = PG::ConnectionBad.new('could not translate host name "instance-1" to address: Temporary failure in name resolution') + expect(handler.unknown_host_error?(error)).to be(false) + end + + it 'is false for other connection errors' do + error = PG::ConnectionBad.new('connection to server at "10.0.0.12", port 5432 failed: Connection refused') + expect(handler.unknown_host_error?(error)).to be(false) + end + end + describe '#network_error_by_sql_state?' do it 'returns true for admin shutdown (57P01)' do expect(handler.network_error_by_sql_state?('57P01')).to be true diff --git a/spec/unit/errors/trilogy_error_handler_spec.rb b/spec/unit/errors/trilogy_error_handler_spec.rb index 012a89b3..80a1053f 100644 --- a/spec/unit/errors/trilogy_error_handler_spec.rb +++ b/spec/unit/errors/trilogy_error_handler_spec.rb @@ -22,6 +22,47 @@ let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::TrilogyDriverDialect.new } subject(:handler) { described_class.new(driver_dialect) } + describe '#unknown_host_error?' do + it 'is true when the connection error is caused by a failed host lookup' do + error = begin + begin + raise SocketError, 'getaddrinfo: nodename nor servname provided, or not known' + rescue SocketError + raise Trilogy::BaseConnectionError, 'unable to connect to "instance-1:3306"' + end + rescue Trilogy::BaseConnectionError => e + e + end + expect(handler.unknown_host_error?(error)).to be(true) + end + + it 'is false when the failed host lookup is temporary' do + error = begin + begin + raise SocketError, 'getaddrinfo: Temporary failure in name resolution' + rescue SocketError + raise Trilogy::BaseConnectionError, 'unable to connect to "instance-1:3306"' + end + rescue Trilogy::BaseConnectionError => e + e + end + expect(handler.unknown_host_error?(error)).to be(false) + end + + it 'is false for a SocketError that is not from the driver' do + expect(handler.unknown_host_error?(SocketError.new('getaddrinfo: nodename nor servname provided'))).to be(false) + end + + it 'is true for a DNS error raised by the C extension' do + error = Trilogy::BaseConnectionError.new('trilogy_connect: TRILOGY_DNS_ERROR') + expect(handler.unknown_host_error?(error)).to be(true) + end + + it 'is false for other connection errors' do + expect(handler.unknown_host_error?(Trilogy::SyscallError::ECONNREFUSED.new('connect'))).to be(false) + end + end + describe '#network_error?' do { 'a read or write timeout' => -> { Trilogy::TimeoutError.new('trilogy_query_recv') }, diff --git a/spec/unit/failover_plugin_spec.rb b/spec/unit/failover_plugin_spec.rb index d7d120bf..0fe6c9f5 100644 --- a/spec/unit/failover_plugin_spec.rb +++ b/spec/unit/failover_plugin_spec.rb @@ -79,9 +79,12 @@ refresh_host_list: nil, force_refresh_host_list?: true, set_availability: nil, - select_host: reader_host) + select_host: reader_host, + host_list_provider: host_list_provider) end + let(:host_list_provider) { nil } + let(:connection_service) do double('connection_service', current_connection: connection, @@ -321,6 +324,154 @@ end end + describe 'missing cluster_instance_host_pattern' do + let(:non_rds_host) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '10.0.0.12', port: '5432') } + let(:pipeline_callable) { -> { connection } } + let(:pattern_missing) { true } + let(:host_list_provider) { double('rds_host_list_provider', instance_host_pattern_missing?: pattern_missing) } + let(:log_output) { StringIO.new } + let(:original_logger) { AwsAdvancedRubyDriverWrapper.logger } + + before do + allow(connection_service).to receive(:initial_host_info).and_return(non_rds_host) + described_class::MISSING_PATTERN_WARNED_HOSTS.clear + original_logger + # A logger at the default level, so the test also shows the warning is visible without debug logging. + AwsAdvancedRubyDriverWrapper.logger = Logger.new(log_output, level: Logger::INFO) + end + + after do + AwsAdvancedRubyDriverWrapper.logger = original_logger + described_class::MISSING_PATTERN_WARNED_HOSTS.clear + end + + context 'when failover is listed explicitly in wrapper_plugins' do + before { props[:wrapper_plugins] = 'failover,initial_connection' } + + it 'raises a configuration error naming the host and both fixes' do + expect { plugin.connect(non_rds_host, props, true, pipeline_callable) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::AwsError) { |error| + expect(error.message).to include("'10.0.0.12' is not a recognized RDS endpoint") + expect(error.message).to include('Set cluster_instance_host_pattern') + expect(error.message).to include('?.XXX.us-east-1.rds.amazonaws.com') + expect(error.message).to include('remove failover from wrapper_plugins') + } + end + + it 'closes the initial connection' do + expect(driver_dialect).to receive(:close_connection).with(connection) + expect { plugin.connect(non_rds_host, props, true, pipeline_callable) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::AwsError) + end + + it 'does not check connections other than the initial one' do + expect(plugin.connect(non_rds_host, props, false, pipeline_callable)).to eq(connection) + end + + context 'when the dialect is not a cluster dialect' do + # Single RDS instances and community databases use a host list provider without instance templates. + let(:host_list_provider) { double('connection_string_host_list_provider') } + + it 'returns the connection' do + expect(plugin.connect(non_rds_host, props, true, pipeline_callable)).to eq(connection) + end + end + + context 'when the host is a recognized RDS endpoint or cluster_instance_host_pattern is set' do + let(:pattern_missing) { false } + + it 'returns the connection without logging a warning' do + expect(plugin.connect(non_rds_host, props, true, pipeline_callable)).to eq(connection) + expect(log_output.string).to be_empty + end + end + end + + context 'when failover comes from the default plugin list' do + it 'returns the connection and logs a warning naming the host and both fixes' do + expect(plugin.connect(non_rds_host, props, true, pipeline_callable)).to eq(connection) + expect(log_output.string).to include('WARN') + expect(log_output.string).to include("'10.0.0.12' is not a recognized RDS endpoint") + expect(log_output.string).to include('Set cluster_instance_host_pattern') + expect(log_output.string).to include('set wrapper_plugins to a list without failover') + end + + it 'logs the warning once per host' do + plugin.connect(non_rds_host, props, true, pipeline_callable) + described_class.new(service_container, props).connect(non_rds_host, props, true, pipeline_callable) + + expect(log_output.string.scan('is not a recognized RDS endpoint').size).to eq(1) + end + + context 'when the host is a recognized RDS endpoint or cluster_instance_host_pattern is set' do + let(:pattern_missing) { false } + + it 'does not log a warning' do + plugin.connect(non_rds_host, props, true, pipeline_callable) + expect(log_output.string).to be_empty + end + end + end + + describe 'during failover' do + let(:bare_reader) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-2', port: '5432', role: host_role::READER) } + let(:bare_writer) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-1', port: '5432', role: host_role::WRITER) } + let(:dns_error) { StandardError.new("Unknown MySQL server host 'instance-2' (8)") } + + before do + props[:failover_timeout_sec] = 2 + plugin.connect(non_rds_host, props, true, pipeline_callable) + allow(host_service).to receive_messages(hosts: [bare_writer, bare_reader], all_hosts: [bare_writer, bare_reader], + select_host: bare_reader) + allow(plugin_manager).to receive(:connect).and_raise(dns_error) + end + + it 'fails writer failover when the verified writer host cannot be resolved' do + allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(true) + allow(retry_util).to receive(:connect_to_writer) do |*, on_connect_error:, **| + on_connect_error.call(bare_writer, dns_error) + end + + expect { plugin.send(:failover) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, + /Unable to resolve the DB instance host 'instance-1'.*cluster_instance_host_pattern/m) + end + + it 'fails writer failover with the monitor error instead of waiting out failover_timeout_sec' do + monitor_error = AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError.new('instance-2', '10.0.0.12') + allow(host_service).to receive(:force_refresh_host_list?).and_raise(monitor_error) + + expect { plugin.send(:failover) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, /cluster_instance_host_pattern/) + end + + context 'with a reader failover mode' do + before { plugin.instance_variable_set(:@failover_mode, failover_mode::READER_OR_WRITER) } + + it 'fails promptly when a topology host cannot be resolved' do + allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(true) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + expect { plugin.send(:failover) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, + /Unable to resolve the DB instance host 'instance-2'.*cluster_instance_host_pattern/m) + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1 + end + + it 'keeps retrying other connection errors until failover_timeout_sec' do + allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(false) + props[:failover_timeout_sec] = 0.3 + timed_plugin = described_class.new(service_container, props) + timed_plugin.connect(non_rds_host, props, true, pipeline_callable) + timed_plugin.instance_variable_set(:@failover_mode, failover_mode::READER_OR_WRITER) + + expect { timed_plugin.send(:failover) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, 'Unable to connect to a reader instance') + end + end + end + end + describe 'verified_connection (stale DNS)' do let(:pipeline_callable) { -> { connection } } diff --git a/spec/unit/host/global_aurora_host_list_provider_spec.rb b/spec/unit/host/global_aurora_host_list_provider_spec.rb index 56675a54..5279ea84 100644 --- a/spec/unit/host/global_aurora_host_list_provider_spec.rb +++ b/spec/unit/host/global_aurora_host_list_provider_spec.rb @@ -134,6 +134,18 @@ end end + describe '#instance_host_pattern_missing?' do + context 'when connecting with a custom domain and no cluster_instance_host_pattern' do + let(:initial_host_info) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'db.example.com', port: 5432) } + let(:wrapper_props) { { global_cluster_instance_host_patterns: instance_templates_str } } + + it 'is false because instance hosts come from global_cluster_instance_host_patterns' do + expect(provider.instance_template.host).to eq('?') + expect(provider.instance_host_pattern_missing?).to be(false) + end + end + end + describe '#force_refresh' do it 'returns nil on timeout' do result = provider.force_refresh(false, 0.1) diff --git a/spec/unit/host/rds_host_list_provider_spec.rb b/spec/unit/host/rds_host_list_provider_spec.rb index 70d683db..490208b5 100644 --- a/spec/unit/host/rds_host_list_provider_spec.rb +++ b/spec/unit/host/rds_host_list_provider_spec.rb @@ -157,6 +157,48 @@ end end + describe '#instance_host_pattern_missing?' do + it 'is false for a recognized RDS endpoint' do + expect(provider.instance_host_pattern_missing?).to be(false) + end + + context 'when connecting with an IP address and no cluster_instance_host_pattern' do + let(:initial_host_info) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '10.0.0.12', port: 5432) } + + it 'is true' do + expect(provider.instance_template.host).to eq('?') + expect(provider.instance_host_pattern_missing?).to be(true) + end + end + + context 'when connecting with a custom domain and no cluster_instance_host_pattern' do + let(:initial_host_info) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'db.example.com', port: 5432) } + + it 'is true' do + expect(provider.instance_host_pattern_missing?).to be(true) + end + end + + context 'when connecting with an IP address and cluster_instance_host_pattern explicitly set to ?' do + # Bare instance identifiers may resolve in the user's environment, e.g. through a DNS search domain. + let(:initial_host_info) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '10.0.0.12', port: 5432) } + let(:wrapper_props) { { cluster_instance_host_pattern: '?' } } + + it 'is false' do + expect(provider.instance_host_pattern_missing?).to be(false) + end + end + + context 'when connecting with a custom domain and cluster_instance_host_pattern set' do + let(:initial_host_info) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'db.example.com', port: 5432) } + let(:wrapper_props) { { cluster_instance_host_pattern: '?.abc123.us-east-2.rds.amazonaws.com' } } + + it 'is false' do + expect(provider.instance_host_pattern_missing?).to be(false) + end + end + end + describe '#refresh' do context 'when topology is cached' do let(:cached_topology) do diff --git a/spec/unit/monitoring/cluster_topology_monitor_spec.rb b/spec/unit/monitoring/cluster_topology_monitor_spec.rb index 2ce58ff3..e810cafc 100644 --- a/spec/unit/monitoring/cluster_topology_monitor_spec.rb +++ b/spec/unit/monitoring/cluster_topology_monitor_spec.rb @@ -294,6 +294,130 @@ end end + describe 'unresolvable instance hosts' do + let(:initial_host) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '10.0.0.12', port: 5432) } + let(:bare_template) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '?', port: 5432) } + let(:bare_hosts) do + [ + AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-1', port: 5432, id: 'instance-1', + role: AwsAdvancedRubyDriverWrapper::Host::HostRole::WRITER), + AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-2', port: 5432, id: 'instance-2', + role: AwsAdvancedRubyDriverWrapper::Host::HostRole::READER) + ] + end + let(:dns_error) { StandardError.new("Unknown MySQL server host 'instance-1' (8)") } + let(:unknown_host) { true } + let(:pattern_missing) { true } + + subject(:monitor) do + described_class.new( + service_container: service_container, + cluster_id: cluster_id, + instance_template: bare_template, + instance_host_pattern_missing: pattern_missing, + topology_utils: topology_utils, + monitoring_driver_props: { host: 'localhost', port: 5432 }, + monitoring_wrapper_props: {} + ) + end + + def wait_for_fatal_error + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 + sleep(0.05) until monitor.instance_variable_get(:@fatal_error).get || + Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + end + + before do + allow(connection_service).to receive(:initial_host_info).and_return(initial_host) + allow(topology_utils).to receive(:query_topology).and_return(bare_hosts) + # The initial host is reachable but isn't the writer, so the monitor probes the instance hosts. + allow(db_dialect).to receive(:host_role).and_return(AwsAdvancedRubyDriverWrapper::Host::HostRole::READER) + allow(plugin_manager).to receive(:internal_connect) do |host_info, *| + raise dns_error unless host_info.equal?(initial_host) + + mock_connection + end + allow(dialect_service).to receive(:login_error?).and_return(false) + allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(unknown_host) + end + + context 'when the bare template comes from a non-RDS connection host without cluster_instance_host_pattern' do + it 'raises a configuration error promptly instead of waiting out the timeout' do + monitor.start + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + + expect { monitor.force_refresh(true, 30.0) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError) { |error| + expect(error.message).to match(/Unable to resolve the DB instance host 'instance-\d'/) + expect(error.message).to include("connection host '10.0.0.12'") + expect(error.message).to include('Set cluster_instance_host_pattern') + } + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 5 + end + + it 'raises the recorded error on later writer verifications without waiting' do + monitor.start + wait_for_fatal_error + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + + expect { monitor.force_refresh(true, 30.0) }.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError) + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1 + end + + it 'keeps serving topology reads that do not verify the writer' do + monitor.start + wait_for_fatal_error + # Simulates the topology cache expiring after the error was recorded. + storage_service.remove(:topology, cluster_id) + + expect(monitor.force_refresh(false, 0)).to be_nil + expect { monitor.force_refresh(false, 0.2) }.to raise_error(Timeout::Error) + end + + it 'clears the recorded error when the monitor is reset' do + monitor.send(:record_fatal_error, + AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError.new('instance-1', '10.0.0.12')) + + monitor.send(:reset!) + + expect(monitor.instance_variable_get(:@fatal_error).get).to be_nil + end + end + + context 'when the connection fails with a login error' do + before { allow(dialect_service).to receive(:login_error?).with(dns_error).and_return(true) } + + it 'does not record a configuration error' do + monitor.start + sleep(0.3) + + expect(monitor.instance_variable_get(:@fatal_error).get).to be_nil + end + end + + context 'when the connection error is not an unresolved host' do + let(:unknown_host) { false } + + it 'keeps retrying until the timeout' do + monitor.start + + expect { monitor.force_refresh(true, 0.5) }.to raise_error(Timeout::Error) + end + end + + context 'when the instance host pattern is not missing' do + # For example a connection host that is an RDS endpoint, or an explicitly set pattern. An instance host + # that doesn't resolve, e.g. during a failover, is retried as usual. + let(:pattern_missing) { false } + + it 'keeps retrying until the timeout' do + monitor.start + + expect { monitor.force_refresh(true, 0.5) }.to raise_error(Timeout::Error) + end + end + end + describe '#process_event' do it 'resets state when receiving MonitorResetEvent for this cluster' do monitor.instance_variable_get(:@monitoring_connection).set(mock_connection, close_old: false) diff --git a/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb b/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb index 1ea7a640..aff589b8 100644 --- a/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb +++ b/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb @@ -116,6 +116,14 @@ storage_service.shutdown end + describe '#unresolvable_due_to_misconfiguration?' do + it 'is false even with a bare instance template, since hosts come from the region templates' do + monitor.instance_variable_set(:@instance_template, AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '?', port: 5432)) + + expect(monitor.send(:unresolvable_due_to_misconfiguration?, SocketError.new('getaddrinfo'))).to be(false) + end + end + describe '#query_topology override' do it 'calls query_global_topology with instance_templates_by_region' do monitor.instance_variable_get(:@monitoring_connection).set(mock_connection, close_old: false) diff --git a/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb b/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb index fa49720f..ec5a32b9 100644 --- a/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb +++ b/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb @@ -74,9 +74,12 @@ def host_info(host, role) hosts: topology, refresh_host_list: nil, force_refresh_host_list?: true, - set_availability: nil) + set_availability: nil, + host_list_provider: host_list_provider) end + let(:host_list_provider) { nil } + let(:initial_host) { home_writer } let(:connection_service) do @@ -117,6 +120,51 @@ def init plugin.send(:init_failover_mode) end + describe 'missing instance host pattern' do + let(:initial_host) { host_info('10.0.0.12', host_role::WRITER) } + let(:pattern_missing) { true } + let(:host_list_provider) { double('host_list_provider', instance_host_pattern_missing?: pattern_missing) } + + before do + props[:wrapper_plugins] = 'gdb_failover' + props[:failover_home_region] = 'us-east-1' + allow(driver_dialect).to receive(:database_engine).and_return(:postgresql) + end + + context 'when the database was identified as a regional cluster' do + it 'raises explaining that global_cluster_instance_host_patterns does not apply, and how to fix it' do + expect(driver_dialect).to receive(:close_connection).with(connection) + expect { plugin.connect(initial_host, props, true, -> { connection }) } + .to raise_error(errors::AwsError) { |error| + expect(error.message).to include("'10.0.0.12' is not a recognized RDS endpoint, cluster_instance_host_pattern is not set") + expect(error.message).to include('regional cluster rather than an Aurora Global Database') + expect(error.message).to include('global_cluster_instance_host_patterns does not apply') + expect(error.message).to include("set wrapper_dialect to 'global-aurora-pg'") + expect(error.message).to include('only detected when it spans more than one region') + expect(error.message).to include('use the failover plugin instead, and set cluster_instance_host_pattern') + } + end + end + + context 'when the driver is a MySQL driver' do + before { allow(driver_dialect).to receive(:database_engine).and_return(:mysql) } + + it 'names the MySQL Global Database dialect' do + expect { plugin.connect(initial_host, props, true, -> { connection }) } + .to raise_error(errors::AwsError, /set wrapper_dialect to 'global-aurora-mysql'/) + end + end + + context 'when the database was identified as a Global Database' do + # GlobalAuroraHostListProvider builds instance hosts from global_cluster_instance_host_patterns. + let(:pattern_missing) { false } + + it 'returns the connection' do + expect(plugin.connect(initial_host, props, true, -> { connection })).to eq(connection) + end + end + end + describe 'mode initialization' do it 'derives the home region from a region-bearing initial endpoint' do init diff --git a/spec/unit/retry_util_spec.rb b/spec/unit/retry_util_spec.rb index 39488e08..8db44c2a 100644 --- a/spec/unit/retry_util_spec.rb +++ b/spec/unit/retry_util_spec.rb @@ -189,6 +189,30 @@ end end + describe 'on_connect_error' do + let(:connect_error) { StandardError.new("Unknown MySQL server host 'writer-instance' (8)") } + + before { allow(plugin_manager).to receive(:connect).and_raise(connect_error) } + + it 'passes each failed attempt to the hook, which can stop retrying by raising' do + hook = lambda do |host, error| + raise ArgumentError, "#{host.host}: #{error.message}" + end + + expect { retry_util.connect_to_writer(plugin_to_skip, plugin_manager, deadline: Time.now + 5, on_connect_error: hook) } + .to raise_error(ArgumentError, /writer-instance.*Unknown MySQL server host/) + end + + it 'keeps retrying until the deadline when the hook returns' do + calls = 0 + hook = ->(*) { calls += 1 } + + expect { retry_util.connect_to_writer(plugin_to_skip, plugin_manager, deadline: Time.now + 0.2, on_connect_error: hook) } + .to raise_error(Timeout::Error) + expect(calls).to be >= 1 + end + end + describe '#connect_to_allowed_host' do before do allow(plugin_manager).to receive(:connect).and_return(connection) From bcdc3bda9b57f395929247edb00eb4379d325f99 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Wed, 4 Nov 2026 15:41:18 -0700 Subject: [PATCH 2/5] fix: warn instead of raising at connect when cluster_instance_host_pattern is missing Connections whose host isn't a recognized RDS endpoint and that don't set cluster_instance_host_pattern now log a warning on Aurora and RDS Multi-AZ DB clusters, whether or not failover is listed explicitly in wrapper_plugins. Failover still fails fast with FailoverFailedError when an instance host can't be resolved. A future major version will raise at connect instead. - The warning says failover will fail, and keeps the fix that applies (remove failover from wrapper_plugins, or set wrapper_plugins without it when the default list is in use). - gdb_failover on a database identified as a regional cluster now warns too, and its failover paths get the same fail-fast as failover: the topology monitor error becomes FailoverFailedError, and its connection attempts use the on_connect_error hook. - CHANGELOG entry moved to Fixed. --- CHANGELOG.md | 4 +- .../plugins/failover_plugin.rb | 22 +++---- .../plugins/gdb/gdb_failover_plugin.rb | 18 +++-- spec/unit/failover_plugin_spec.rb | 27 ++++---- .../plugins/gdb/gdb_failover_plugin_spec.rb | 65 +++++++++++++++---- 5 files changed, 89 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8174e560..124cc074 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,9 +13,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - The Blue/Green Deployment plugin now invalidates connections that were opened to the old blue environment before a switchover, controlled by the new `bg_drop_blue_connections` property (default `true`). Once a switchover is confirmed, each such connection is closed the next time it is used, so with the failover plugin enabled it fails over through Blue/Green routing and raises `FailoverSuccessError` (or `TransactionStateUnknownError` inside a transaction), and without failover the driver raises its closed-connection error. ### :crab: Changed -- Connections with `failover` explicitly in `wrapper_plugins` now fail at startup when the host isn't a recognized RDS endpoint and `cluster_instance_host_pattern` isn't set; previously failover failed after `failover_timeout_sec`. The check applies only to Aurora and RDS Multi-AZ DB clusters. When `failover` comes from the default plugin list, the wrapper logs a warning instead, and a failover in that setup now raises `FailoverFailedError` as soon as an instance host can't be resolved, with a message that names `cluster_instance_host_pattern`. The same applies to `gdb_failover` when the host isn't a recognized RDS endpoint, `cluster_instance_host_pattern` isn't set, and the database is identified as a regional cluster rather than a Global Database (for example with `wrapper_dialect: aurora-pg`), since `global_cluster_instance_host_patterns` is only read for Global Databases; the error explains how to fix the dialect or switch to `failover` ([PR #235](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/235), [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/enhanced-failover#host-pattern)). - Simplified the KMS Encryption Plugin's PostgreSQL trigger SQL to read the column's HMAC key from `key_storage` for every row. Re-run the trigger SQL from the [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/using-plugins/kms-encryption#postgresql-1) to update existing deployments ([PR #216](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/216)). +### :bug: Fixed +- Fixed failover retrying instance hosts that can't be resolved until `failover_timeout_sec` (default 300 s) when the connection host isn't a recognized RDS endpoint (an IP address or your own domain name) and `cluster_instance_host_pattern` isn't set. Failover now raises `FailoverFailedError` as soon as such a host fails to resolve, with a message that names `cluster_instance_host_pattern`. On Aurora and RDS Multi-AZ DB clusters, the wrapper also logs a warning when the first connection to such a host opens. For `gdb_failover` on a database identified as a regional cluster rather than a Global Database (for example with `wrapper_dialect: aurora-pg`), the warning explains that `global_cluster_instance_host_patterns` doesn't apply. A future major version will raise an error at connect for this configuration ([PR #235](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/235), [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/enhanced-failover#host-pattern)). + ## [1.0.1] - 2026-10-07 ### :bug: Fixed diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb index a084222d..7ff263db 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb @@ -72,7 +72,7 @@ def initialize(service_container, props = ::Concurrent::Map.new) def connect(host_info, driver_props, is_initial_connection, pipeline_callable) init_failover_mode conn = connect_with_failover(host_info, driver_props, is_initial_connection, pipeline_callable) - check_instance_host_pattern(conn) if is_initial_connection + warn_if_instance_host_pattern_missing if is_initial_connection conn end @@ -131,22 +131,16 @@ def connect_with_failover(host_info, driver_props, is_initial_connection, pipeli # Failover needs DB instance hosts it can resolve. Whether it has them is only known once the initial # connection has settled the dialect: cluster dialects (Aurora, RDS Multi-AZ DB cluster) then use an # RdsHostListProvider, which reports whether the instance host pattern is missing. A single instance or a - # community database never has one, so it isn't affected. When the plugin was listed explicitly in - # wrapper_plugins the missing pattern is a configuration error; when it comes from the default plugin - # list, a warning is logged instead. - # - # @param conn [Object] the initial connection, closed if the check fails - # @raise [Errors::AwsError] if the plugin was requested explicitly and the instance host pattern is missing - def check_instance_host_pattern(conn) + # community database never has one, so it isn't affected. A missing pattern is logged as a warning, once + # per host, and the connection is still returned; failover then fails fast instead of retrying hosts that + # can't be resolved. + def warn_if_instance_host_pattern_missing return unless instance_host_pattern_missing? host = connection_service.initial_host_info&.host - if plugin_requested_explicitly? - close_quietly(conn) - raise Errors::AwsError, missing_instance_host_pattern_message(host, explicit: true) - end + return unless MISSING_PATTERN_WARNED_HOSTS.add?(host) - logger.warn(missing_instance_host_pattern_message(host, explicit: false)) if MISSING_PATTERN_WARNED_HOSTS.add?(host) + logger.warn(missing_instance_host_pattern_message(host, explicit: plugin_requested_explicitly?)) end def instance_host_pattern_missing? @@ -169,7 +163,7 @@ def missing_instance_host_pattern_message(host, explicit:) "The connection host '#{host}' is not a recognized RDS endpoint and " \ "#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} is not set, so the #{plugin_code} plugin cannot " \ - 'build DB instance hosts from the cluster topology and failover will not work. ' \ + 'build DB instance hosts from the cluster topology, and failover will fail with FailoverFailedError. ' \ "Set #{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} to a DNS pattern that resolves to the " \ "cluster's instances (for example, '?.XXX.us-east-1.rds.amazonaws.com'), or #{remedy}." end diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb index 67fa398d..82747886 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb @@ -218,8 +218,12 @@ def failover_with_plan def failover_plan # This is expected to return once the topology has stabilized, i.e. once the cluster # control plane has already chosen a new writer. - unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout) - raise Errors::FailoverFailedError, 'The request to discover the new topology timed out or was unsuccessful' + begin + unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout) + raise Errors::FailoverFailedError, 'The request to discover the new topology timed out or was unsuccessful' + end + rescue Errors::UnresolvableInstanceHostError => e + raise Errors::FailoverFailedError, e.message end writer_candidate = host_service.all_hosts.find { |h| h.role == Host::HostRole::WRITER } @@ -306,7 +310,9 @@ def failover_to_writer(writer_candidate, writer_region, deadline) success = false begin - result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, deadline: deadline) + result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, + deadline: deadline, + on_connect_error: method(:raise_if_instance_host_unresolvable)) if result&.connection && result.host_info success = true connection_service.update_current_connection(result.connection, result.host_info) @@ -332,7 +338,8 @@ def failover_to_allowed_host(mode, deadline) @service_container.plugin_manager, verify_role: verify_role_for(mode), strategy: @reader_selector_strategy, - deadline: deadline + deadline: deadline, + on_connect_error: method(:raise_if_instance_host_unresolvable) ) { |allowed_hosts| allowed_hosts_for(mode, allowed_hosts) } if result&.connection && result.host_info success = true @@ -430,7 +437,8 @@ def missing_instance_host_pattern_message(host, **) "The connection host '#{host}' is not a recognized RDS endpoint, #{pattern_name} is not set, and the " \ 'database was identified as a regional cluster rather than an Aurora Global Database, so ' \ "#{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name} does not apply and the #{PLUGIN_CODE} " \ - 'plugin cannot build DB instance hosts from the cluster topology. If the cluster is a member of a Global ' \ + 'plugin cannot build DB instance hosts from the cluster topology, and failover will fail with ' \ + 'FailoverFailedError. If the cluster is a member of a Global ' \ "Database, set #{PropertyDefinition::DIALECT.name} to '#{global_dialect_code}' (without it, a Global " \ 'Database is only detected when it spans more than one region). For a standalone cluster, use the ' \ "failover plugin instead, and set #{pattern_name} to a DNS pattern that resolves to the cluster's " \ diff --git a/spec/unit/failover_plugin_spec.rb b/spec/unit/failover_plugin_spec.rb index 0fe6c9f5..a54cc051 100644 --- a/spec/unit/failover_plugin_spec.rb +++ b/spec/unit/failover_plugin_spec.rb @@ -348,32 +348,33 @@ context 'when failover is listed explicitly in wrapper_plugins' do before { props[:wrapper_plugins] = 'failover,initial_connection' } - it 'raises a configuration error naming the host and both fixes' do - expect { plugin.connect(non_rds_host, props, true, pipeline_callable) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::AwsError) { |error| - expect(error.message).to include("'10.0.0.12' is not a recognized RDS endpoint") - expect(error.message).to include('Set cluster_instance_host_pattern') - expect(error.message).to include('?.XXX.us-east-1.rds.amazonaws.com') - expect(error.message).to include('remove failover from wrapper_plugins') - } + it 'returns the connection and logs a warning naming the host and both fixes' do + expect(plugin.connect(non_rds_host, props, true, pipeline_callable)).to eq(connection) + expect(log_output.string).to include('WARN') + expect(log_output.string).to include("'10.0.0.12' is not a recognized RDS endpoint") + expect(log_output.string).to include('failover will fail with FailoverFailedError') + expect(log_output.string).to include('Set cluster_instance_host_pattern') + expect(log_output.string).to include('?.XXX.us-east-1.rds.amazonaws.com') + expect(log_output.string).to include('remove failover from wrapper_plugins') end - it 'closes the initial connection' do - expect(driver_dialect).to receive(:close_connection).with(connection) - expect { plugin.connect(non_rds_host, props, true, pipeline_callable) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::AwsError) + it 'keeps the initial connection open' do + expect(driver_dialect).not_to receive(:close_connection) + plugin.connect(non_rds_host, props, true, pipeline_callable) end it 'does not check connections other than the initial one' do expect(plugin.connect(non_rds_host, props, false, pipeline_callable)).to eq(connection) + expect(log_output.string).to be_empty end context 'when the dialect is not a cluster dialect' do # Single RDS instances and community databases use a host list provider without instance templates. let(:host_list_provider) { double('connection_string_host_list_provider') } - it 'returns the connection' do + it 'returns the connection without logging a warning' do expect(plugin.connect(non_rds_host, props, true, pipeline_callable)).to eq(connection) + expect(log_output.string).to be_empty end end diff --git a/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb b/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb index ec5a32b9..5f20d10f 100644 --- a/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb +++ b/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb @@ -124,25 +124,36 @@ def init let(:initial_host) { host_info('10.0.0.12', host_role::WRITER) } let(:pattern_missing) { true } let(:host_list_provider) { double('host_list_provider', instance_host_pattern_missing?: pattern_missing) } + let(:log_output) { StringIO.new } + let(:original_logger) { AwsAdvancedRubyDriverWrapper.logger } before do props[:wrapper_plugins] = 'gdb_failover' props[:failover_home_region] = 'us-east-1' allow(driver_dialect).to receive(:database_engine).and_return(:postgresql) + described_class::MISSING_PATTERN_WARNED_HOSTS.clear + original_logger + AwsAdvancedRubyDriverWrapper.logger = Logger.new(log_output, level: Logger::INFO) + end + + after do + AwsAdvancedRubyDriverWrapper.logger = original_logger + described_class::MISSING_PATTERN_WARNED_HOSTS.clear end context 'when the database was identified as a regional cluster' do - it 'raises explaining that global_cluster_instance_host_patterns does not apply, and how to fix it' do - expect(driver_dialect).to receive(:close_connection).with(connection) - expect { plugin.connect(initial_host, props, true, -> { connection }) } - .to raise_error(errors::AwsError) { |error| - expect(error.message).to include("'10.0.0.12' is not a recognized RDS endpoint, cluster_instance_host_pattern is not set") - expect(error.message).to include('regional cluster rather than an Aurora Global Database') - expect(error.message).to include('global_cluster_instance_host_patterns does not apply') - expect(error.message).to include("set wrapper_dialect to 'global-aurora-pg'") - expect(error.message).to include('only detected when it spans more than one region') - expect(error.message).to include('use the failover plugin instead, and set cluster_instance_host_pattern') - } + it 'returns the connection and warns that global_cluster_instance_host_patterns does not apply, and how to fix it' do + expect(plugin.connect(initial_host, props, true, -> { connection })).to eq(connection) + + message = log_output.string + expect(message).to include('WARN') + expect(message).to include("'10.0.0.12' is not a recognized RDS endpoint, cluster_instance_host_pattern is not set") + expect(message).to include('regional cluster rather than an Aurora Global Database') + expect(message).to include('global_cluster_instance_host_patterns does not apply') + expect(message).to include('failover will fail with FailoverFailedError') + expect(message).to include("set wrapper_dialect to 'global-aurora-pg'") + expect(message).to include('only detected when it spans more than one region') + expect(message).to include('use the failover plugin instead, and set cluster_instance_host_pattern') end end @@ -150,8 +161,8 @@ def init before { allow(driver_dialect).to receive(:database_engine).and_return(:mysql) } it 'names the MySQL Global Database dialect' do - expect { plugin.connect(initial_host, props, true, -> { connection }) } - .to raise_error(errors::AwsError, /set wrapper_dialect to 'global-aurora-mysql'/) + plugin.connect(initial_host, props, true, -> { connection }) + expect(log_output.string).to include("set wrapper_dialect to 'global-aurora-mysql'") end end @@ -159,8 +170,34 @@ def init # GlobalAuroraHostListProvider builds instance hosts from global_cluster_instance_host_patterns. let(:pattern_missing) { false } - it 'returns the connection' do + it 'returns the connection without logging a warning' do expect(plugin.connect(initial_host, props, true, -> { connection })).to eq(connection) + expect(log_output.string).to be_empty + end + end + + context 'during failover' do + let(:dns_error) { StandardError.new("Unknown MySQL server host 'instance-1' (8)") } + + before { plugin.connect(initial_host, props, true, -> { connection }) } + + it 'raises FailoverFailedError when the topology monitor reports an unresolvable instance host' do + monitor_error = errors::UnresolvableInstanceHostError.new('instance-1', '10.0.0.12') + allow(host_service).to receive(:force_refresh_host_list?).and_raise(monitor_error) + + expect { plugin.send(:failover) }.to raise_error(errors::FailoverFailedError, /cluster_instance_host_pattern/) + end + + it 'fails fast when a host it connects to cannot be resolved' do + # The IP connection host isn't a writer endpoint, so the mode defaults to home_reader_or_writer. + allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(true) + allow(retry_util).to receive(:connect_to_allowed_host) do |*, on_connect_error:, **| + on_connect_error.call(host_info('instance-1', host_role::WRITER), dns_error) + end + allow(host_service).to receive(:all_hosts).and_return([host_info('instance-1', host_role::WRITER)]) + + expect { plugin.send(:failover) } + .to raise_error(errors::FailoverFailedError, /Unable to resolve the DB instance host 'instance-1'/) end end end From fbe89574ffc8c43dcf4ca1ccd7f52f8ba496d3fa Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Mon, 30 Nov 2026 10:20:05 -0700 Subject: [PATCH 3/5] fix: fail failover immediately when cluster_instance_host_pattern is missing Replace the DNS-based fail-fast with a configuration check. When the connection host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set, failover (writer, reader and gdb_failover) now raises FailoverFailedError as soon as it starts, with the same explanation as the warning logged at connect, instead of waiting for instance hosts to fail to resolve. An explicitly set '?' pattern opts out of both, for environments where bare instance identifiers resolve. - Remove the topology monitor's fatal error, the RetryUtil on_connect_error hook, the reader-failover check, and unknown_host_error? from the error handlers, along with UnresolvableInstanceHostError. - Build the warning and the failover error from the same message methods on FailoverPlugin; gdb_failover overrides only its problem and fix wording, and its fix now also says to set global_cluster_instance_host_patterns. - Warnings mention the '?' opt-out and read as separate sentences. - Add specs that go through execute and connect, and flag the behavior change in the CHANGELOG. --- CHANGELOG.md | 3 +- .../errors.rb | 17 --- .../errors/error_handler.rb | 21 --- .../errors/mysql_error_handler.rb | 6 - .../errors/pg_error_handler.rb | 8 +- .../errors/trilogy_error_handler.rb | 9 -- .../host/rds_host_list_provider.rb | 4 +- .../monitoring/cluster_topology_monitor.rb | 53 +------- .../plugins/failover_plugin.rb | 85 +++++++----- .../plugins/gdb/gdb_failover_plugin.rb | 42 +++--- .../services/dialect_service.rb | 7 - .../utils/retry_util.rb | 17 +-- spec/unit/errors/mysql_error_handler_spec.rb | 25 ---- spec/unit/errors/pg_error_handler_spec.rb | 30 ----- .../unit/errors/trilogy_error_handler_spec.rb | 41 ------ spec/unit/failover_plugin_spec.rb | 116 ++++++++++------ .../cluster_topology_monitor_spec.rb | 124 ------------------ .../global_cluster_topology_monitor_spec.rb | 8 -- .../plugins/gdb/gdb_failover_plugin_spec.rb | 29 ++-- spec/unit/retry_util_spec.rb | 24 ---- 20 files changed, 167 insertions(+), 502 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76ee95d8..47ad7198 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - **Behavior change:** a successful failover during ActiveRecord's connection check (`active?`) no longer raises `FailoverSuccessError`: no statement of the application's was in flight, so the adapter reconnects silently, as ActiveRecord does for a dead connection, and the next statement runs on the new writer. `TransactionStateUnknownError` is still raised when an ActiveRecord transaction was open, because that transaction was lost; otherwise `active?` returns `false`. A failover during `reset!` completes the reset on the new writer instead of raising. `active?` returns `false`, and `reset!` raises `ActiveRecord::ConnectionFailed`, when failover fails. `aws_mysql2` and `aws_trilogy` are unchanged by these `active?`/`reset!` changes. - Hardened every ActiveRecord adapter (`aws_postgresql`, `aws_mysql2`, `aws_trilogy`) against any other code path that touches the raw connection outside `with_raw_connection` after a failover. The wrapper's `Method invoked against old connection` error is now flagged `needs_reconfiguration`, so the adapter's exception translation clears ActiveRecord's prepared statement cache and re-applies the connection's settings on the first such failure, instead of every statement prepared before the failover failing until the connection is discarded. - **Behavior change:** that error is still an `AwsError` with the same message, but `needs_reconfiguration` is now `true` (`connection_broken` stays `false`). Code that inspects `needs_reconfiguration` on wrapper errors will now see it set. -- Fixed failover retrying instance hosts that can't be resolved until `failover_timeout_sec` (default 300 s) when the connection host isn't a recognized RDS endpoint (an IP address or your own domain name) and `cluster_instance_host_pattern` isn't set. Failover now raises `FailoverFailedError` as soon as such a host fails to resolve, with a message that names `cluster_instance_host_pattern`. On Aurora and RDS Multi-AZ DB clusters, the wrapper also logs a warning when the first connection to such a host opens. For `gdb_failover` on a database identified as a regional cluster rather than a Global Database (for example with `wrapper_dialect: aurora-pg`), the warning explains that `global_cluster_instance_host_patterns` doesn't apply. A future major version will raise an error at connect for this configuration ([PR #235](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/235), [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/enhanced-failover#host-pattern)). +- Fixed failover retrying instance hosts that can't be resolved until `failover_timeout_sec` (default 300 s) when the connection host isn't a recognized RDS endpoint (an IP address or your own domain name) and `cluster_instance_host_pattern` isn't set. With `failover` or `gdb_failover` loaded (`failover` is in the default plugin list) on an Aurora or RDS Multi-AZ DB cluster, the wrapper now logs a warning when the first connection to such a host opens, and failover raises `FailoverFailedError` immediately, with a message that names `cluster_instance_host_pattern`. For `gdb_failover` on a database identified as a regional cluster rather than a Global Database (for example with `wrapper_dialect: aurora-pg`), the message explains that `global_cluster_instance_host_patterns` doesn't apply. A future major version will raise an error at connect for this configuration ([PR #235](https://github.com/aws/aws-advanced-ruby-driver-wrapper/pull/235), [documentation](https://aws.github.io/aws-advanced-wrapper-docs/ruby/enhanced-failover#host-pattern)). + - **Behavior change:** if bare instance identifiers resolve in your environment (for example through a DNS search domain), failover used to succeed in this configuration and now fails immediately. Set `cluster_instance_host_pattern: "?"` to keep the previous behavior. ## [1.1.0] - 2026-11-05 diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors.rb b/lib/aws_advanced_ruby_driver_wrapper/errors.rb index 8f423e38..5fd2d523 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors.rb @@ -56,22 +56,5 @@ class SecretsManagerAuthError < AwsError; end class PluginConflictError < AwsError; end class BlueGreenTimeoutError < AwsError; end class BlueGreenSwitchoverError < AwsError; end - - # Raised when a DB instance host can't be resolved because the connection host isn't a recognized RDS - # endpoint and cluster_instance_host_pattern isn't set, so instance hosts were built as bare instance - # identifiers. This is a configuration error, so retrying won't help. - class UnresolvableInstanceHostError < AwsError - # @param instance_host [String] the DB instance host that could not be resolved - # @param connection_host [String] the host the application connected with - def initialize(instance_host, connection_host) - super( - "Unable to resolve the DB instance host '#{instance_host}' while discovering the cluster topology. " \ - "The connection host '#{connection_host}' is not a recognized RDS endpoint and cluster_instance_host_pattern " \ - 'is not set, so the wrapper built a DB instance host that cannot be resolved. This is a configuration error ' \ - 'rather than a transient failover condition. Set cluster_instance_host_pattern to a DNS pattern that resolves ' \ - "to the cluster's instances (for example, '?.XXX.us-east-1.rds.amazonaws.com')." - ) - end - end end end diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb index e79857c9..25fe95c5 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/error_handler.rb @@ -17,8 +17,6 @@ module AwsAdvancedRubyDriverWrapper module Errors module ErrorHandler - TEMPORARY_RESOLUTION_FAILURE = 'temporary failure' - def network_error?(error) check_cause_chain(error) { |sql_state, _| network_error_by_sql_state?(sql_state) } end @@ -43,16 +41,6 @@ def read_only_error_by_sql_state?(sql_state, error_code = nil) raise NotImplementedError end - # Whether the error, or any error in its cause chain, is a driver error meaning the host name does not - # exist. Temporary resolver failures ("Temporary failure in name resolution") don't count, since the - # same host may resolve on the next attempt. - # - # @param error [Exception] - # @return [Boolean] - def unknown_host_error?(error) - check_cause_chain(error) { |_, current| unknown_host?(current) && !temporary_resolution_failure?(current) } - end - # Whether the driver reported +error+ as a database error, i.e. it carries a SQLSTATE (or, for # trilogy, a MySQL error code). This is not a strict server-vs-client split: mysql2 also reports # SQLSTATE HY000 for client-side failures such as a lost connection. Used by the Blue/Green status @@ -71,15 +59,6 @@ def schema_error?(error) private - # Driver-specific check for an error raised when the host name could not be resolved. - def unknown_host?(_error) - false - end - - def temporary_resolution_failure?(error) - [error, error.cause].compact.any? { |e| e.message.to_s.downcase.include?(TEMPORARY_RESOLUTION_FAILURE) } - end - def extract_sql_state(error) @driver_dialect.sql_state(error) end diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb index 68a133fb..69dfc91d 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/mysql_error_handler.rb @@ -32,7 +32,6 @@ class MysqlErrorHandler 2055, # CR_SERVER_LOST_EXTENDED (lost connection with state info) 4031 # ER_CLIENT_INTERACTION_TIMEOUT (MySQL 8.0.24+ closed a connection that exceeded wait_timeout) ].freeze - UNKNOWN_HOST_ERROR_CODE = 2005 # CR_UNKNOWN_HOST def initialize(driver_dialect) @driver_dialect = driver_dialect @@ -69,11 +68,6 @@ def read_only_error_by_sql_state?(sql_state, error_code = nil) private - def unknown_host?(error) - defined?(Mysql2::Error) && error.is_a?(Mysql2::Error) && - error.respond_to?(:error_number) && error.error_number == UNKNOWN_HOST_ERROR_CODE - end - def connection_error_network?(error) return false unless defined?(Mysql2::Error) && error.is_a?(Mysql2::Error) diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb index 740a2c5e..0d6ca58e 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/pg_error_handler.rb @@ -25,7 +25,6 @@ class PgErrorHandler ACCESS_ERROR_SQL_STATES = Set['08004', '28P01', '28000'].freeze READ_ONLY_SQL_STATE = '25006' LOGIN_ERROR_MESSAGE = 'authentication failed' - UNKNOWN_HOST_MESSAGE = 'could not translate host name' NETWORK_ERROR_MESSAGES = [ 'unexpected eof', 'closed the connection unexpectedly', @@ -48,7 +47,7 @@ class PgErrorHandler CONNECT_FAILURE_MESSAGES = [ 'connection refused', 'timeout expired', - UNKNOWN_HOST_MESSAGE, + 'could not translate host name', 'no route to host', 'network is unreachable', 'host is unreachable', @@ -108,11 +107,6 @@ def read_only_error_by_sql_state?(sql_state, _error_code = nil) private - def unknown_host?(error) - defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad) && - error.message.to_s.downcase.include?(UNKNOWN_HOST_MESSAGE) - end - def connection_bad_network_error?(error) return false unless defined?(PG::ConnectionBad) && error.is_a?(PG::ConnectionBad) diff --git a/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb b/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb index 420d48e6..c60eb86c 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/errors/trilogy_error_handler.rb @@ -50,9 +50,6 @@ class TrilogyErrorHandler # credential was not accepted, so for login-retry purposes it is a login error. AUTH_PROTOCOL_VIOLATION = 'trilogy_auth_recv' PROTOCOL_VIOLATION_MARKER = 'TRILOGY_PROTOCOL_VIOLATION' - # Raised by trilogy's C extension when it resolves the host itself. Newer versions resolve the host in - # Ruby instead and raise a connection error caused by a SocketError. - DNS_ERROR_MARKER = 'TRILOGY_DNS_ERROR' def initialize(driver_dialect) @driver_dialect = driver_dialect @@ -110,12 +107,6 @@ def network_failure?(error) !LOGIN_ERROR_CODES.include?(code) && code != LOCK_WAIT_TIMEOUT_ERROR_CODE end - def unknown_host?(error) - return false unless defined?(::Trilogy::ConnectionError) && error.is_a?(::Trilogy::ConnectionError) - - error.cause.is_a?(SocketError) || error.message.to_s.include?(DNS_ERROR_MARKER) - end - def error_code(error) error.respond_to?(:error_code) ? error.error_code : nil end diff --git a/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb b/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb index ac038a08..494fd0d1 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/host/rds_host_list_provider.rb @@ -94,7 +94,6 @@ def force_refresh(verify_writer, timeout_sec) service_container: @service_container, cluster_id: @cluster_id, instance_template: @instance_template, - instance_host_pattern_missing: instance_host_pattern_missing?, topology_utils: @topology_utils, monitoring_driver_props: @monitoring_driver_props, monitoring_wrapper_props: @monitoring_wrapper_props @@ -113,7 +112,8 @@ def stop_monitor # Whether DB instance hosts can't be derived from the topology. This is the case when the connection # host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set: the instance template # is then a bare '?', so instance hosts are bare instance identifiers that usually don't resolve. An - # explicitly set '?' pattern doesn't count, since bare identifiers may resolve in the user's environment. + # explicitly set '?' pattern doesn't count: it is how users whose environment resolves bare instance + # identifiers (e.g. through a DNS search domain) opt out of the warning and of failing over immediately. # # @return [Boolean] def instance_host_pattern_missing? diff --git a/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb b/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb index e73c53f6..3d512a11 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/monitoring/cluster_topology_monitor.rb @@ -16,13 +16,11 @@ require_relative 'monitor' require_relative 'monitor_connection' -require_relative '../errors' require_relative '../host/host_role' require_relative '../host/host_availability' require_relative '../utils/events/monitor_reset_event' require_relative '../utils/rds_utils' require_relative '../property_definition' -require 'concurrent' require 'timeout' module AwsAdvancedRubyDriverWrapper @@ -41,8 +39,6 @@ class ClusterTopologyMonitor < Monitor # @param service_container [Services::ServiceContainer] # @param cluster_id [String] # @param instance_template [Host::HostInfo] - # @param instance_host_pattern_missing [Boolean] whether instance hosts are bare instance identifiers - # because the connection host isn't an RDS endpoint and cluster_instance_host_pattern isn't set # @param topology_utils [Object] responds to #query_topology, #writer_instance? # @param monitoring_driver_props [Hash] driver props with prefixed driver overrides merged in # @param monitoring_wrapper_props [Hash] wrapper prop overrides extracted from prefixed props @@ -52,15 +48,13 @@ def initialize( instance_template:, topology_utils:, monitoring_driver_props:, - monitoring_wrapper_props: {}, - instance_host_pattern_missing: false + monitoring_wrapper_props: {} ) super(termination_timeout_sec: TERMINATION_TIMEOUT_SEC) @service_container = service_container @cluster_id = cluster_id @instance_template = instance_template - @instance_host_pattern_missing = instance_host_pattern_missing @topology_utils = topology_utils @monitoring_driver_props = monitoring_driver_props @monitoring_wrapper_props = monitoring_wrapper_props @@ -95,9 +89,6 @@ def initialize( @completed_one_cycle = {} @latest_topology = nil @stable_start_time = 0 - # A non-recoverable configuration error found by an instance monitor. Once set, threads waiting to - # verify the writer raise it instead of waiting out their timeout. Cleared when the monitor is reset. - @fatal_error = Concurrent::AtomicReference.new end # Forces a topology refresh, ignoring any cached topology. Blocks until updated or raises on timeout. @@ -398,45 +389,11 @@ def attempt_host_connection(host_info, attempts) rescue StandardError => e raise if @service_container.dialect_service.login_error?(e) - if unresolvable_due_to_misconfiguration?(e) - # Retrying can't help, since the host is a bare instance identifier that will never resolve. - record_fatal_error(Errors::UnresolvableInstanceHostError.new(host_info.host, initial_host_info&.host)) - return nil - end - logger.debug("[#{@cluster_id}] Connection to #{host_info.host} failed: #{e.message}") sleep(calculate_backoff(attempts)) nil end - # Whether a connection failure means the host can never be resolved because of the configuration: - # the connection host isn't a recognized RDS endpoint and cluster_instance_host_pattern isn't set, - # so instance hosts were built from a bare '?' template. Other unresolved hosts, such as a real - # instance endpoint during a failover, are retried as usual. - # - # @param error [StandardError] - # @return [Boolean] - def unresolvable_due_to_misconfiguration?(error) - @instance_host_pattern_missing && @service_container.dialect_service.unknown_host_error?(error) - end - - # Records a non-recoverable configuration error, stops the instance monitors, and wakes threads - # waiting to verify the writer so they raise it right away. - # - # @param error [Errors::AwsError] - def record_fatal_error(error) - logger.error("[#{@cluster_id}] #{error.message}") if @fatal_error.compare_and_set(nil, error) - @stop_instance_monitors = true - @topology_mutex.synchronize { @topology_cv.broadcast } - end - - # @raise [Errors::AwsError] the recorded fatal error, if any. A copy is raised so that each waiting - # thread gets its own backtrace. - def raise_if_fatal_error - fatal = @fatal_error.get - raise fatal.dup if fatal - end - def check_host_role(conn) @service_container.dialect_service.db_dialect.host_role(conn) rescue StandardError => e @@ -580,11 +537,7 @@ def update_hosts_availability(hosts) # --- force_refresh support --- - # A recorded fatal error is only raised to callers verifying the writer, which is what failover does. - # Other topology reads, such as the host list refresh behind every new connection, keep getting the - # cached topology or a timeout as before, so the misconfiguration doesn't stop new connections. def wait_for_topology_update(timeout_sec, verify_writer = false) - raise_if_fatal_error if verify_writer current_hosts = stored_hosts @topology_mutex.synchronize do @@ -604,7 +557,6 @@ def wait_for_topology_update(timeout_sec, verify_writer = false) # consistent), so we keep waiting until the cached writer matches the writer this monitor has independently # verified by probing instances directly, or the timeout is hit. while wait_for_topology?(current_hosts, verify_writer) && monotonic_time < deadline && !stopped? - raise_if_fatal_error if verify_writer remaining = deadline - monotonic_time break if remaining <= 0 @@ -612,8 +564,6 @@ def wait_for_topology_update(timeout_sec, verify_writer = false) end end - raise_if_fatal_error if verify_writer - latest = stored_hosts if latest.equal?(current_hosts) raise Timeout::Error, "Topology not updated within #{timeout_sec}s for cluster #{@cluster_id}" @@ -674,7 +624,6 @@ def reset! @verified_writer = false @writer_info = nil @high_refresh_end_time = 0 - @fatal_error.set(nil) clear_topology_cache @topology_mutex.synchronize do diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb index 7ff263db..b0857d10 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/failover_plugin.rb @@ -132,15 +132,29 @@ def connect_with_failover(host_info, driver_props, is_initial_connection, pipeli # connection has settled the dialect: cluster dialects (Aurora, RDS Multi-AZ DB cluster) then use an # RdsHostListProvider, which reports whether the instance host pattern is missing. A single instance or a # community database never has one, so it isn't affected. A missing pattern is logged as a warning, once - # per host, and the connection is still returned; failover then fails fast instead of retrying hosts that - # can't be resolved. + # per host, and the connection is still returned; failover then fails immediately (see + # #raise_if_instance_host_pattern_missing). def warn_if_instance_host_pattern_missing return unless instance_host_pattern_missing? host = connection_service.initial_host_info&.host return unless MISSING_PATTERN_WARNED_HOSTS.add?(host) - logger.warn(missing_instance_host_pattern_message(host, explicit: plugin_requested_explicitly?)) + logger.warn("#{missing_instance_host_pattern_problem(host)}. Failover will fail with FailoverFailedError. " \ + "#{missing_instance_host_pattern_fix}") + end + + # Failover can't reach any DB instance when the instance host pattern is missing, since the instance hosts + # are bare instance identifiers. Failing right away, with the same explanation as the warning logged at + # connect, is better than retrying them until failover_timeout_sec. + # + # @raise [Errors::FailoverFailedError] if the instance host pattern is missing + def raise_if_instance_host_pattern_missing + return unless instance_host_pattern_missing? + + host = connection_service.initial_host_info&.host + raise Errors::FailoverFailedError, + "Failover is not possible. #{missing_instance_host_pattern_problem(host)}. #{missing_instance_host_pattern_fix}" end def instance_host_pattern_missing? @@ -153,32 +167,38 @@ def plugin_requested_explicitly? @wrapper_props.key?(PropertyDefinition::PLUGINS.name) end - def missing_instance_host_pattern_message(host, explicit:) + # The warning logged at connect and the error raised by failover are both built from the methods below, so + # they describe the problem and its fix the same way. + + # @return [String] a clause, without trailing punctuation, saying why the instance hosts can't be built + def missing_instance_host_pattern_reason(host) + "The connection host '#{host}' is not a recognized RDS endpoint and " \ + "#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} is not set" + end + + # @return [String] what to set cluster_instance_host_pattern to, phrased to follow "Set" or "set" + def instance_host_pattern_setting + "#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} to a DNS pattern that resolves to the cluster's " \ + "instances (for example, '?.XXX.us-east-1.rds.amazonaws.com', or '?' if bare instance identifiers " \ + 'resolve in your environment)' + end + + # @return [String] a clause, without trailing punctuation, describing the problem + def missing_instance_host_pattern_problem(host) + "#{missing_instance_host_pattern_reason(host)}, so the #{self.class::PLUGIN_CODE} plugin cannot build " \ + 'DB instance hosts from the cluster topology' + end + + # @return [String] the fixes, as one or more full sentences + def missing_instance_host_pattern_fix plugin_code = self.class::PLUGIN_CODE - remedy = if explicit + remedy = if plugin_requested_explicitly? "remove #{plugin_code} from #{PropertyDefinition::PLUGINS.name}" else "set #{PropertyDefinition::PLUGINS.name} to a list without #{plugin_code} (it is enabled by default)" end - "The connection host '#{host}' is not a recognized RDS endpoint and " \ - "#{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} is not set, so the #{plugin_code} plugin cannot " \ - 'build DB instance hosts from the cluster topology, and failover will fail with FailoverFailedError. ' \ - "Set #{PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name} to a DNS pattern that resolves to the " \ - "cluster's instances (for example, '?.XXX.us-east-1.rds.amazonaws.com'), or #{remedy}." - end - - # Raises when a topology host can't be resolved because the instance host pattern is missing. Failover - # can reach a topology host without the topology monitor having probed it first (reader failover always, - # writer failover when the monitor verified the writer through the connection host), so it needs its own - # check to avoid retrying such hosts until failover_timeout_sec. - # - # @raise [Errors::FailoverFailedError] - def raise_if_instance_host_unresolvable(host_info, error) - return unless instance_host_pattern_missing? && dialect_service.unknown_host_error?(error) - - error = Errors::UnresolvableInstanceHostError.new(host_info.host, connection_service.initial_host_info&.host) - raise Errors::FailoverFailedError, error.message + "Set #{instance_host_pattern_setting}, or #{remedy}." end def connect_via_failover(is_initial_connection) @@ -374,13 +394,10 @@ def failover_reader failover_deadline = failover_start + @failover_timeout logger.info { 'Starting reader failover' } + raise_if_instance_host_pattern_missing - begin - unless host_service.force_refresh_host_list?(verify_writer: false, timeout_sec: 0) - raise Errors::FailoverFailedError, 'The request to discover the new topology was unsuccessful' - end - rescue Errors::UnresolvableInstanceHostError => e - raise Errors::FailoverFailedError, e.message + unless host_service.force_refresh_host_list?(verify_writer: false, timeout_sec: 0) + raise Errors::FailoverFailedError, 'The request to discover the new topology was unsuccessful' end begin @@ -405,6 +422,7 @@ def failover_writer result = nil logger.info { 'Starting writer failover' } + raise_if_instance_host_pattern_missing begin unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout) @@ -412,14 +430,10 @@ def failover_writer end was_in_transaction = @service_container.session_state_service.in_transaction? - result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, - deadline: failover_deadline, - on_connect_error: method(:raise_if_instance_host_unresolvable)) + result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, deadline: failover_deadline) raise Errors::FailoverFailedError, 'Unable to connect to a writer instance' unless result&.connection && result.host_info connection_service.update_current_connection(result.connection, result.host_info) - rescue Errors::UnresolvableInstanceHostError => e - raise Errors::FailoverFailedError, e.message rescue Timeout::Error close_quietly(result&.connection) raise Errors::FailoverFailedError, @@ -539,9 +553,8 @@ def attempt_reader_connection(host_info) end [:unknown, nil] end - rescue StandardError => e + rescue StandardError close_quietly(conn) - raise_if_instance_host_unresolvable(host_info, e) [:failed, nil] end diff --git a/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb b/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb index 82747886..0056b954 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/plugins/gdb/gdb_failover_plugin.rb @@ -218,12 +218,9 @@ def failover_with_plan def failover_plan # This is expected to return once the topology has stabilized, i.e. once the cluster # control plane has already chosen a new writer. - begin - unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout) - raise Errors::FailoverFailedError, 'The request to discover the new topology timed out or was unsuccessful' - end - rescue Errors::UnresolvableInstanceHostError => e - raise Errors::FailoverFailedError, e.message + raise_if_instance_host_pattern_missing + unless host_service.force_refresh_host_list?(verify_writer: true, timeout_sec: @failover_timeout) + raise Errors::FailoverFailedError, 'The request to discover the new topology timed out or was unsuccessful' end writer_candidate = host_service.all_hosts.find { |h| h.role == Host::HostRole::WRITER } @@ -310,9 +307,7 @@ def failover_to_writer(writer_candidate, writer_region, deadline) success = false begin - result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, - deadline: deadline, - on_connect_error: method(:raise_if_instance_host_unresolvable)) + result = @retry_util.connect_to_writer(self, @service_container.plugin_manager, deadline: deadline) if result&.connection && result.host_info success = true connection_service.update_current_connection(result.connection, result.host_info) @@ -338,8 +333,7 @@ def failover_to_allowed_host(mode, deadline) @service_container.plugin_manager, verify_role: verify_role_for(mode), strategy: @reader_selector_strategy, - deadline: deadline, - on_connect_error: method(:raise_if_instance_host_unresolvable) + deadline: deadline ) { |allowed_hosts| allowed_hosts_for(mode, allowed_hosts) } if result&.connection && result.host_info success = true @@ -430,19 +424,19 @@ def failover_writer # The instance host pattern can only be missing when the database was identified as a regional cluster: # for a Global Database, instance hosts come from global_cluster_instance_host_patterns, which is - # required. On a regional cluster that setting is not read, so the message explains how to have the - # database treated as a Global Database, or how to configure the regional cluster instead. - def missing_instance_host_pattern_message(host, **) - pattern_name = PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name - "The connection host '#{host}' is not a recognized RDS endpoint, #{pattern_name} is not set, and the " \ - 'database was identified as a regional cluster rather than an Aurora Global Database, so ' \ - "#{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name} does not apply and the #{PLUGIN_CODE} " \ - 'plugin cannot build DB instance hosts from the cluster topology, and failover will fail with ' \ - 'FailoverFailedError. If the cluster is a member of a Global ' \ - "Database, set #{PropertyDefinition::DIALECT.name} to '#{global_dialect_code}' (without it, a Global " \ - 'Database is only detected when it spans more than one region). For a standalone cluster, use the ' \ - "failover plugin instead, and set #{pattern_name} to a DNS pattern that resolves to the cluster's " \ - "instances (for example, '?.XXX.us-east-1.rds.amazonaws.com')." + # required. On a regional cluster that setting is not read, so the problem and fix explain how to have + # the database treated as a Global Database, or how to configure the regional cluster instead. + def missing_instance_host_pattern_problem(host) + "#{missing_instance_host_pattern_reason(host)}. The database was identified as a regional cluster rather " \ + "than an Aurora Global Database, so #{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name} " \ + "does not apply and the #{PLUGIN_CODE} plugin cannot build DB instance hosts from the cluster topology" + end + + def missing_instance_host_pattern_fix + "If the cluster is a member of a Global Database, set #{PropertyDefinition::DIALECT.name} to " \ + "'#{global_dialect_code}' (without it, a Global Database is only detected when it spans more than one " \ + "region) and set #{PropertyDefinition::GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.name}. For a standalone " \ + "cluster, use the failover plugin instead, and set #{instance_host_pattern_setting}." end def global_dialect_code diff --git a/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb b/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb index ec14b4e6..0400e44e 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/services/dialect_service.rb @@ -164,13 +164,6 @@ def read_only_error?(error) @error_handler.read_only_error?(error) end - # @param error [Exception] - # @return [Boolean] whether the error means the host name could not be resolved. Custom error - # handlers that don't implement #unknown_host_error? never report one. - def unknown_host_error?(error) - @error_handler.respond_to?(:unknown_host_error?) && @error_handler.unknown_host_error?(error) - end - # Whether the driver reported the error as a database error (it carries a SQLSTATE, or for # trilogy a MySQL error code). Not a strict server-vs-client split; see ErrorHandler#database_error?. # @param error [Exception] diff --git a/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb b/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb index 207e1f75..fb18c008 100644 --- a/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb +++ b/lib/aws_advanced_ruby_driver_wrapper/utils/retry_util.rb @@ -40,13 +40,10 @@ def initialize(service_container) # @param plugin_to_skip [Object] the plugin that should be skipped in the connect pipeline # @param plugin_manager [Services::PluginManager] # @param deadline [Time] the point in time at which to give up - # @param on_connect_error [#call, nil] called with the candidate host and the error when a connection - # attempt fails; it may raise to stop retrying # @return [Result] the new connection and the host it was opened to # @raise [Timeout::Error] if no connection could be established before the deadline - def connect_to_writer(plugin_to_skip, plugin_manager, deadline:, on_connect_error: nil) - connect_to_allowed_host(plugin_to_skip, plugin_manager, verify_role: Host::HostRole::WRITER, deadline: deadline, - on_connect_error: on_connect_error) do |allowed_hosts| + def connect_to_writer(plugin_to_skip, plugin_manager, deadline:) + connect_to_allowed_host(plugin_to_skip, plugin_manager, verify_role: Host::HostRole::WRITER, deadline: deadline) do |allowed_hosts| writer_candidate = @host_service.all_hosts.find { |h| h.role == Host::HostRole::WRITER } if writer_candidate.nil? @@ -73,14 +70,11 @@ def connect_to_writer(plugin_to_skip, plugin_manager, deadline:, on_connect_erro # @param deadline [Time] the point in time at which to give up # @param verify_role [Symbol, nil] the role the new connection must report, or nil to accept any host # @param strategy [String] the host selection strategy used to order the candidates - # @param on_connect_error [#call, nil] called with the candidate host and the error when a connection - # attempt fails; it may raise to stop retrying # @yieldparam allowed_hosts [Array] the current allowed hosts # @yieldreturn [Array, nil] the hosts to attempt, or nil/empty to refresh and retry # @return [Result] the new connection and the host it was opened to # @raise [Timeout::Error] if no connection could be established before the deadline - def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_role: nil, strategy: DEFAULT_STRATEGY, - on_connect_error: nil) + def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_role: nil, strategy: DEFAULT_STRATEGY) strategy = DEFAULT_STRATEGY if strategy.nil? || strategy.to_s.empty? loop do @@ -108,7 +102,7 @@ def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_ro break # Give up on this candidate list and refresh the topology. end - result = attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager, on_connect_error) + result = attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) return result if result remaining.delete(candidate) @@ -121,7 +115,7 @@ def connect_to_allowed_host(plugin_to_skip, plugin_manager, deadline:, verify_ro private # @return [Result, nil] the result, or nil if the connection failed or reported the wrong role - def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager, on_connect_error = nil) + def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager) conn = plugin_manager.connect(candidate, @connection_service.driver_props, false, plugin_to_skip: plugin_to_skip) # Since the roles in the host list might not be accurate, we execute a query to check the instance's role. @@ -138,7 +132,6 @@ def attempt_connection(candidate, verify_role, plugin_to_skip, plugin_manager, o rescue StandardError => e logger.debug { "Exception connecting to #{candidate.host}: #{e.message}" } close_quietly(conn) - on_connect_error&.call(candidate, e) nil end diff --git a/spec/unit/errors/mysql_error_handler_spec.rb b/spec/unit/errors/mysql_error_handler_spec.rb index c6a110c6..716a3842 100644 --- a/spec/unit/errors/mysql_error_handler_spec.rb +++ b/spec/unit/errors/mysql_error_handler_spec.rb @@ -21,31 +21,6 @@ let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::Mysql2DriverDialect.new } subject(:handler) { described_class.new(driver_dialect) } - describe '#unknown_host_error?' do - it 'is true for an unknown host error' do - error = Mysql2::Error::ConnectionError.new("Unknown MySQL server host 'instance-1' (8)", nil, 2005) - expect(handler.unknown_host_error?(error)).to be(true) - end - - it 'is true when the unknown host error is a cause' do - error = begin - begin - raise Mysql2::Error::ConnectionError.new("Unknown MySQL server host 'instance-1' (8)", nil, 2005) - rescue Mysql2::Error - raise AwsAdvancedRubyDriverWrapper::Errors::AwsError, 'wrapped' - end - rescue AwsAdvancedRubyDriverWrapper::Errors::AwsError => e - e - end - expect(handler.unknown_host_error?(error)).to be(true) - end - - it 'is false for other connection errors' do - error = Mysql2::Error::ConnectionError.new("Can't connect to MySQL server on 'instance-1' (61)", nil, 2003) - expect(handler.unknown_host_error?(error)).to be(false) - end - end - describe '#network_error_by_sql_state?' do it 'returns true for 08 prefix states (except 08004)' do expect(handler.network_error_by_sql_state?('08001')).to be true diff --git a/spec/unit/errors/pg_error_handler_spec.rb b/spec/unit/errors/pg_error_handler_spec.rb index 7e1e41fc..c7467932 100644 --- a/spec/unit/errors/pg_error_handler_spec.rb +++ b/spec/unit/errors/pg_error_handler_spec.rb @@ -21,36 +21,6 @@ let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::PgDriverDialect.new } subject(:handler) { described_class.new(driver_dialect) } - describe '#unknown_host_error?' do - it 'is true when the host name cannot be translated' do - error = PG::ConnectionBad.new('could not translate host name "instance-1" to address: nodename nor servname provided') - expect(handler.unknown_host_error?(error)).to be(true) - end - - it 'is true when the error is a cause' do - error = begin - begin - raise PG::ConnectionBad, 'could not translate host name "instance-1" to address: Name or service not known' - rescue PG::ConnectionBad - raise AwsAdvancedRubyDriverWrapper::Errors::AwsError, 'wrapped' - end - rescue AwsAdvancedRubyDriverWrapper::Errors::AwsError => e - e - end - expect(handler.unknown_host_error?(error)).to be(true) - end - - it 'is false for a temporary resolver failure' do - error = PG::ConnectionBad.new('could not translate host name "instance-1" to address: Temporary failure in name resolution') - expect(handler.unknown_host_error?(error)).to be(false) - end - - it 'is false for other connection errors' do - error = PG::ConnectionBad.new('connection to server at "10.0.0.12", port 5432 failed: Connection refused') - expect(handler.unknown_host_error?(error)).to be(false) - end - end - describe '#network_error_by_sql_state?' do it 'returns true for admin shutdown (57P01)' do expect(handler.network_error_by_sql_state?('57P01')).to be true diff --git a/spec/unit/errors/trilogy_error_handler_spec.rb b/spec/unit/errors/trilogy_error_handler_spec.rb index 72e08571..ebbcd242 100644 --- a/spec/unit/errors/trilogy_error_handler_spec.rb +++ b/spec/unit/errors/trilogy_error_handler_spec.rb @@ -22,47 +22,6 @@ let(:driver_dialect) { AwsAdvancedRubyDriverWrapper::DriverDialects::TrilogyDriverDialect.new } subject(:handler) { described_class.new(driver_dialect) } - describe '#unknown_host_error?' do - it 'is true when the connection error is caused by a failed host lookup' do - error = begin - begin - raise SocketError, 'getaddrinfo: nodename nor servname provided, or not known' - rescue SocketError - raise Trilogy::BaseConnectionError, 'unable to connect to "instance-1:3306"' - end - rescue Trilogy::BaseConnectionError => e - e - end - expect(handler.unknown_host_error?(error)).to be(true) - end - - it 'is false when the failed host lookup is temporary' do - error = begin - begin - raise SocketError, 'getaddrinfo: Temporary failure in name resolution' - rescue SocketError - raise Trilogy::BaseConnectionError, 'unable to connect to "instance-1:3306"' - end - rescue Trilogy::BaseConnectionError => e - e - end - expect(handler.unknown_host_error?(error)).to be(false) - end - - it 'is false for a SocketError that is not from the driver' do - expect(handler.unknown_host_error?(SocketError.new('getaddrinfo: nodename nor servname provided'))).to be(false) - end - - it 'is true for a DNS error raised by the C extension' do - error = Trilogy::BaseConnectionError.new('trilogy_connect: TRILOGY_DNS_ERROR') - expect(handler.unknown_host_error?(error)).to be(true) - end - - it 'is false for other connection errors' do - expect(handler.unknown_host_error?(Trilogy::SyscallError::ECONNREFUSED.new('connect'))).to be(false) - end - end - describe '#network_error?' do { 'a read or write timeout' => -> { Trilogy::TimeoutError.new('trilogy_query_recv') }, diff --git a/spec/unit/failover_plugin_spec.rb b/spec/unit/failover_plugin_spec.rb index b422a6a7..c5d4b982 100644 --- a/spec/unit/failover_plugin_spec.rb +++ b/spec/unit/failover_plugin_spec.rb @@ -371,7 +371,7 @@ expect(plugin.connect(non_rds_host, props, true, pipeline_callable)).to eq(connection) expect(log_output.string).to include('WARN') expect(log_output.string).to include("'10.0.0.12' is not a recognized RDS endpoint") - expect(log_output.string).to include('failover will fail with FailoverFailedError') + expect(log_output.string).to include('Failover will fail with FailoverFailedError') expect(log_output.string).to include('Set cluster_instance_host_pattern') expect(log_output.string).to include('?.XXX.us-east-1.rds.amazonaws.com') expect(log_output.string).to include('remove failover from wrapper_plugins') @@ -416,6 +416,14 @@ expect(log_output.string).to include('set wrapper_plugins to a list without failover') end + it 'logs the warning again after the caches are cleared' do + plugin.connect(non_rds_host, props, true, pipeline_callable) + AwsAdvancedRubyDriverWrapper.clear_caches + described_class.new(service_container, props).connect(non_rds_host, props, true, pipeline_callable) + + expect(log_output.string.scan('is not a recognized RDS endpoint').size).to eq(2) + end + it 'logs the warning once per host' do plugin.connect(non_rds_host, props, true, pipeline_callable) described_class.new(service_container, props).connect(non_rds_host, props, true, pipeline_callable) @@ -434,59 +442,93 @@ end describe 'during failover' do - let(:bare_reader) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-2', port: '5432', role: host_role::READER) } - let(:bare_writer) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-1', port: '5432', role: host_role::WRITER) } - let(:dns_error) { StandardError.new("Unknown MySQL server host 'instance-2' (8)") } - before do - props[:failover_timeout_sec] = 2 plugin.connect(non_rds_host, props, true, pipeline_callable) - allow(host_service).to receive_messages(hosts: [bare_writer, bare_reader], all_hosts: [bare_writer, bare_reader], - select_host: bare_reader) - allow(plugin_manager).to receive(:connect).and_raise(dns_error) + allow(host_service).to receive(:force_refresh_host_list?).and_return(true) end - it 'fails writer failover when the verified writer host cannot be resolved' do - allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(true) - allow(retry_util).to receive(:connect_to_writer) do |*, on_connect_error:, **| - on_connect_error.call(bare_writer, dns_error) - end + it 'fails writer failover immediately, without discovering the topology or connecting' do + expect(host_service).not_to receive(:force_refresh_host_list?) + expect(retry_util).not_to receive(:connect_to_writer) expect { plugin.send(:failover) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, - /Unable to resolve the DB instance host 'instance-1'.*cluster_instance_host_pattern/m) + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError) { |error| + expect(error.message).to start_with('Failover is not possible. ') + expect(error.message).to include("'10.0.0.12' is not a recognized RDS endpoint and cluster_instance_host_pattern is not set") + expect(error.message).to include('Set cluster_instance_host_pattern') + expect(error.message).to include('set wrapper_plugins to a list without failover') + } end - it 'fails writer failover with the monitor error instead of waiting out failover_timeout_sec' do - monitor_error = AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError.new('instance-2', '10.0.0.12') - allow(host_service).to receive(:force_refresh_host_list?).and_raise(monitor_error) + it 'fails reader failover immediately' do + plugin.instance_variable_set(:@failover_mode, failover_mode::READER_OR_WRITER) + expect(host_service).not_to receive(:force_refresh_host_list?) + expect(plugin_manager).not_to receive(:connect) expect { plugin.send(:failover) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, /cluster_instance_host_pattern/) + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, /cluster_instance_host_pattern is not set/) + end + + it 'counts the attempt as a failed failover' do + counters = described_class::FailoverCounters.new( + triggered: double('triggered', inc: nil), succeeded: double('succeeded', inc: nil), failed: double('failed', inc: nil) + ) + plugin.instance_variable_set(:@writer_failover_counters, counters) + expect(counters.failed).to receive(:inc) + + expect { plugin.send(:failover) }.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError) end - context 'with a reader failover mode' do - before { plugin.instance_variable_set(:@failover_mode, failover_mode::READER_OR_WRITER) } + context 'when a network error interrupts a call' do + let(:network_error) { StandardError.new('connection reset') } + + before do + allow(dialect_service).to receive(:network_error?).with(network_error).and_return(true) + allow(session_state_service).to receive(:in_transaction?).and_return(true) + end - it 'fails promptly when a topology host cannot be resolved' do - allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(true) + it 'rolls back the open transaction and raises FailoverFailedError caused by the original error' do + expect(driver_dialect).to receive(:execute).with(connection, 'ROLLBACK') + expect(host_service).not_to receive(:force_refresh_host_list?) - started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - expect { plugin.send(:failover) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, - /Unable to resolve the DB instance host 'instance-2'.*cluster_instance_host_pattern/m) - expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1 + expect { plugin.execute('connection.exec', -> { raise network_error }) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError) { |error| + expect(error.message).to include('cluster_instance_host_pattern is not set') + expect(error.cause).to eq(network_error) + } end - it 'keeps retrying other connection errors until failover_timeout_sec' do - allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(false) - props[:failover_timeout_sec] = 0.3 - timed_plugin = described_class.new(service_container, props) - timed_plugin.connect(non_rds_host, props, true, pipeline_callable) - timed_plugin.instance_variable_set(:@failover_mode, failover_mode::READER_OR_WRITER) + it 're-raises the original error when the connection was closed explicitly' do + plugin.execute(AwsAdvancedRubyDriverWrapper::RubyMethod::CONNECTION_CLOSE.name, -> {}) + + expect { plugin.execute('connection.exec', -> { raise network_error }) }.to raise_error(network_error) + end + end + + it 'raises FailoverFailedError when a call finds the connection closed' do + allow(driver_dialect).to receive(:closed?).and_return(true) + + expect { plugin.execute('connection.exec', -> { :result }) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, /cluster_instance_host_pattern is not set/) + end + + it 'raises FailoverFailedError when a connect is failed over with enable_connect_failover' do + props[:enable_connect_failover] = true + network_error = StandardError.new('connection refused') + allow(dialect_service).to receive(:network_error?).with(network_error).and_return(true) + + expect { plugin.connect(non_rds_host, props, false, -> { raise network_error }) } + .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, /cluster_instance_host_pattern is not set/) + end + + context 'when the instance host pattern is not missing' do + let(:pattern_missing) { false } + + it 'fails over as usual' do + writer_result = AwsAdvancedRubyDriverWrapper::Utils::RetryUtil::Result.new(new_connection, writer_host) + allow(retry_util).to receive(:connect_to_writer).and_return(writer_result) - expect { timed_plugin.send(:failover) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError, 'Unable to connect to a reader instance') + expect { plugin.send(:failover) }.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverSuccessError) end end end diff --git a/spec/unit/monitoring/cluster_topology_monitor_spec.rb b/spec/unit/monitoring/cluster_topology_monitor_spec.rb index e810cafc..2ce58ff3 100644 --- a/spec/unit/monitoring/cluster_topology_monitor_spec.rb +++ b/spec/unit/monitoring/cluster_topology_monitor_spec.rb @@ -294,130 +294,6 @@ end end - describe 'unresolvable instance hosts' do - let(:initial_host) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '10.0.0.12', port: 5432) } - let(:bare_template) { AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '?', port: 5432) } - let(:bare_hosts) do - [ - AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-1', port: 5432, id: 'instance-1', - role: AwsAdvancedRubyDriverWrapper::Host::HostRole::WRITER), - AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: 'instance-2', port: 5432, id: 'instance-2', - role: AwsAdvancedRubyDriverWrapper::Host::HostRole::READER) - ] - end - let(:dns_error) { StandardError.new("Unknown MySQL server host 'instance-1' (8)") } - let(:unknown_host) { true } - let(:pattern_missing) { true } - - subject(:monitor) do - described_class.new( - service_container: service_container, - cluster_id: cluster_id, - instance_template: bare_template, - instance_host_pattern_missing: pattern_missing, - topology_utils: topology_utils, - monitoring_driver_props: { host: 'localhost', port: 5432 }, - monitoring_wrapper_props: {} - ) - end - - def wait_for_fatal_error - deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5 - sleep(0.05) until monitor.instance_variable_get(:@fatal_error).get || - Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline - end - - before do - allow(connection_service).to receive(:initial_host_info).and_return(initial_host) - allow(topology_utils).to receive(:query_topology).and_return(bare_hosts) - # The initial host is reachable but isn't the writer, so the monitor probes the instance hosts. - allow(db_dialect).to receive(:host_role).and_return(AwsAdvancedRubyDriverWrapper::Host::HostRole::READER) - allow(plugin_manager).to receive(:internal_connect) do |host_info, *| - raise dns_error unless host_info.equal?(initial_host) - - mock_connection - end - allow(dialect_service).to receive(:login_error?).and_return(false) - allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(unknown_host) - end - - context 'when the bare template comes from a non-RDS connection host without cluster_instance_host_pattern' do - it 'raises a configuration error promptly instead of waiting out the timeout' do - monitor.start - started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - - expect { monitor.force_refresh(true, 30.0) } - .to raise_error(AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError) { |error| - expect(error.message).to match(/Unable to resolve the DB instance host 'instance-\d'/) - expect(error.message).to include("connection host '10.0.0.12'") - expect(error.message).to include('Set cluster_instance_host_pattern') - } - expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 5 - end - - it 'raises the recorded error on later writer verifications without waiting' do - monitor.start - wait_for_fatal_error - started = Process.clock_gettime(Process::CLOCK_MONOTONIC) - - expect { monitor.force_refresh(true, 30.0) }.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError) - expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 1 - end - - it 'keeps serving topology reads that do not verify the writer' do - monitor.start - wait_for_fatal_error - # Simulates the topology cache expiring after the error was recorded. - storage_service.remove(:topology, cluster_id) - - expect(monitor.force_refresh(false, 0)).to be_nil - expect { monitor.force_refresh(false, 0.2) }.to raise_error(Timeout::Error) - end - - it 'clears the recorded error when the monitor is reset' do - monitor.send(:record_fatal_error, - AwsAdvancedRubyDriverWrapper::Errors::UnresolvableInstanceHostError.new('instance-1', '10.0.0.12')) - - monitor.send(:reset!) - - expect(monitor.instance_variable_get(:@fatal_error).get).to be_nil - end - end - - context 'when the connection fails with a login error' do - before { allow(dialect_service).to receive(:login_error?).with(dns_error).and_return(true) } - - it 'does not record a configuration error' do - monitor.start - sleep(0.3) - - expect(monitor.instance_variable_get(:@fatal_error).get).to be_nil - end - end - - context 'when the connection error is not an unresolved host' do - let(:unknown_host) { false } - - it 'keeps retrying until the timeout' do - monitor.start - - expect { monitor.force_refresh(true, 0.5) }.to raise_error(Timeout::Error) - end - end - - context 'when the instance host pattern is not missing' do - # For example a connection host that is an RDS endpoint, or an explicitly set pattern. An instance host - # that doesn't resolve, e.g. during a failover, is retried as usual. - let(:pattern_missing) { false } - - it 'keeps retrying until the timeout' do - monitor.start - - expect { monitor.force_refresh(true, 0.5) }.to raise_error(Timeout::Error) - end - end - end - describe '#process_event' do it 'resets state when receiving MonitorResetEvent for this cluster' do monitor.instance_variable_get(:@monitoring_connection).set(mock_connection, close_old: false) diff --git a/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb b/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb index aff589b8..1ea7a640 100644 --- a/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb +++ b/spec/unit/monitoring/global_cluster_topology_monitor_spec.rb @@ -116,14 +116,6 @@ storage_service.shutdown end - describe '#unresolvable_due_to_misconfiguration?' do - it 'is false even with a bare instance template, since hosts come from the region templates' do - monitor.instance_variable_set(:@instance_template, AwsAdvancedRubyDriverWrapper::Host::HostInfo.new(host: '?', port: 5432)) - - expect(monitor.send(:unresolvable_due_to_misconfiguration?, SocketError.new('getaddrinfo'))).to be(false) - end - end - describe '#query_topology override' do it 'calls query_global_topology with instance_templates_by_region' do monitor.instance_variable_get(:@monitoring_connection).set(mock_connection, close_old: false) diff --git a/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb b/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb index 5f20d10f..b4b93bce 100644 --- a/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb +++ b/spec/unit/plugins/gdb/gdb_failover_plugin_spec.rb @@ -147,12 +147,13 @@ def init message = log_output.string expect(message).to include('WARN') - expect(message).to include("'10.0.0.12' is not a recognized RDS endpoint, cluster_instance_host_pattern is not set") + expect(message).to include("'10.0.0.12' is not a recognized RDS endpoint and cluster_instance_host_pattern is not set") expect(message).to include('regional cluster rather than an Aurora Global Database') expect(message).to include('global_cluster_instance_host_patterns does not apply') - expect(message).to include('failover will fail with FailoverFailedError') + expect(message).to include('Failover will fail with FailoverFailedError') expect(message).to include("set wrapper_dialect to 'global-aurora-pg'") expect(message).to include('only detected when it spans more than one region') + expect(message).to include('and set global_cluster_instance_host_patterns.') expect(message).to include('use the failover plugin instead, and set cluster_instance_host_pattern') end end @@ -177,27 +178,17 @@ def init end context 'during failover' do - let(:dns_error) { StandardError.new("Unknown MySQL server host 'instance-1' (8)") } - before { plugin.connect(initial_host, props, true, -> { connection }) } - it 'raises FailoverFailedError when the topology monitor reports an unresolvable instance host' do - monitor_error = errors::UnresolvableInstanceHostError.new('instance-1', '10.0.0.12') - allow(host_service).to receive(:force_refresh_host_list?).and_raise(monitor_error) - - expect { plugin.send(:failover) }.to raise_error(errors::FailoverFailedError, /cluster_instance_host_pattern/) - end - - it 'fails fast when a host it connects to cannot be resolved' do - # The IP connection host isn't a writer endpoint, so the mode defaults to home_reader_or_writer. - allow(dialect_service).to receive(:unknown_host_error?).with(dns_error).and_return(true) - allow(retry_util).to receive(:connect_to_allowed_host) do |*, on_connect_error:, **| - on_connect_error.call(host_info('instance-1', host_role::WRITER), dns_error) - end - allow(host_service).to receive(:all_hosts).and_return([host_info('instance-1', host_role::WRITER)]) + it 'fails immediately, without discovering the topology' do + expect(host_service).not_to receive(:force_refresh_host_list?) expect { plugin.send(:failover) } - .to raise_error(errors::FailoverFailedError, /Unable to resolve the DB instance host 'instance-1'/) + .to raise_error(errors::FailoverFailedError) { |error| + expect(error.message).to start_with('Failover is not possible. ') + expect(error.message).to include('global_cluster_instance_host_patterns does not apply') + expect(error.message).to include("set wrapper_dialect to 'global-aurora-pg'") + } end end end diff --git a/spec/unit/retry_util_spec.rb b/spec/unit/retry_util_spec.rb index 8db44c2a..39488e08 100644 --- a/spec/unit/retry_util_spec.rb +++ b/spec/unit/retry_util_spec.rb @@ -189,30 +189,6 @@ end end - describe 'on_connect_error' do - let(:connect_error) { StandardError.new("Unknown MySQL server host 'writer-instance' (8)") } - - before { allow(plugin_manager).to receive(:connect).and_raise(connect_error) } - - it 'passes each failed attempt to the hook, which can stop retrying by raising' do - hook = lambda do |host, error| - raise ArgumentError, "#{host.host}: #{error.message}" - end - - expect { retry_util.connect_to_writer(plugin_to_skip, plugin_manager, deadline: Time.now + 5, on_connect_error: hook) } - .to raise_error(ArgumentError, /writer-instance.*Unknown MySQL server host/) - end - - it 'keeps retrying until the deadline when the hook returns' do - calls = 0 - hook = ->(*) { calls += 1 } - - expect { retry_util.connect_to_writer(plugin_to_skip, plugin_manager, deadline: Time.now + 0.2, on_connect_error: hook) } - .to raise_error(Timeout::Error) - expect(calls).to be >= 1 - end - end - describe '#connect_to_allowed_host' do before do allow(plugin_manager).to receive(:connect).and_return(connection) From 82817b0e1a7e56c177f4faec5d7f132203941535 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Mon, 30 Nov 2026 10:24:05 -0700 Subject: [PATCH 4/5] skill: describe the warning and immediate failover failure for a missing cluster_instance_host_pattern Update the configuration and troubleshooting assistants for the new behavior, tagged [Unreleased] with before/after wording: a warning at connect, an immediate FailoverFailedError on failover, the '?' opt-out, and the gdb_failover regional-cluster message. --- skills/ruby-wrapper-configuration-assistant/SKILL.md | 9 +++++---- skills/ruby-wrapper-troubleshooting-assistant/SKILL.md | 7 +++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/skills/ruby-wrapper-configuration-assistant/SKILL.md b/skills/ruby-wrapper-configuration-assistant/SKILL.md index 134195a5..c7cc5fa6 100644 --- a/skills/ruby-wrapper-configuration-assistant/SKILL.md +++ b/skills/ruby-wrapper-configuration-assistant/SKILL.md @@ -560,7 +560,7 @@ production: cluster_instance_host_pattern: "?.XXX.us-east-1.rds.amazonaws.com" ``` -The wrapper can't recognize the host as an RDS endpoint, so it can't build per-instance hostnames from topology. Set `cluster_instance_host_pattern` (`?` = instance identifier). Set `cluster_id` only if the process connects to more than one cluster (§3.12). Leave out `initial_connection` (nothing to resolve). For `iam`, also set `iam_host` to a real RDS endpoint. For `gdb_failover`, use region-prefixed `global_cluster_instance_host_patterns` and `failover_home_region`. `bg` does not support CNAME aliases. +The wrapper can't recognize the host as an RDS endpoint, so it can't build per-instance hostnames from topology. Set `cluster_instance_host_pattern` (`?` = instance identifier). Before `[Unreleased]`, without it failover retried the bare instance names until `failover_timeout_sec` and then raised `FailoverFailedError`; from `[Unreleased]`, the wrapper logs a `WARN` at connect and failover raises `FailoverFailedError` immediately. If bare instance names resolve in the app's environment (e.g. a DNS search domain), `cluster_instance_host_pattern: "?"` keeps failing over to them. Set `cluster_id` only if the process connects to more than one cluster (§3.12). Leave out `initial_connection` (nothing to resolve). For `iam`, also set `iam_host` to a real RDS endpoint. For `gdb_failover`, use region-prefixed `global_cluster_instance_host_patterns` and `failover_home_region`. `bg` does not support CNAME aliases. ### 3.12 Multiple clusters in one app - `cluster_id` per cluster @@ -758,7 +758,7 @@ Detects that the cluster promoted a different instance and reconnects the connec | `failover_timeout_sec` | Float | `300.0` | Maximum time allowed to reconnect to a new writer or reader after failover starts. It only affects the case where failover can't find a target: with `strict_writer`, no writer becomes reachable; with `strict_reader` / `reader_or_writer`, no matching instance is reachable. A normal failover finishes well within it, so lowering it makes requests fail fast (with `FailoverFailedError`) only in that outage case. Failover connects directly to instance endpoints it knows from topology; it doesn't wait for the cluster endpoint's DNS to update. So the 40-60 second DNS delay after a failover (§5.3) is not a reason to increase `failover_timeout_sec`. | | `failover_reader_host_selector_strategy` | String | `random` | Strategy used to select a reader during reader failover (§7). | | `enable_connect_failover` | Boolean | `false` | Enables cluster-aware failover when the **initial** connection fails because of a network exception. The initial connection may be redirected to another instance. | -| `cluster_instance_host_pattern` | String | auto-derived for RDS endpoints | Pattern used to build instance endpoints when the host is not a recognizable RDS endpoint (`?` = instance identifier). Required for IP addresses and custom domains. | +| `cluster_instance_host_pattern` | String | auto-derived for RDS endpoints | Pattern used to build instance endpoints when the host is not a recognizable RDS endpoint (`?` = instance identifier). Required for IP addresses and custom domains. [Unreleased] Without it on an Aurora / Multi-AZ DB cluster: a `WARN` at connect, and failover raises `FailoverFailedError` immediately; an explicit `?` opts out. | | `cluster_id` | String | `'1'` | Shares one topology monitor and cache between connections to the same cluster (§3.12). A Global Database is one cluster for `gdb_failover` connections in any region. | | `cluster_topology_refresh_rate_sec` | Float | `5.0` | Interval at which the topology monitor refreshes a stable cluster. | | `cluster_topology_high_refresh_rate_sec` | Float | `0.1` | Interval between topology updates during the high-rate period (writer discovery, and typically about 30 seconds after a new writer is detected). | @@ -786,7 +786,7 @@ Region-aware failover for Aurora Global Database. Introduces a **home region** a | `failover_home_region` | String | parsed from URL | The AWS region the application runs in. Required when the endpoint carries no region. | | `in_home_failover_mode` | String | depends on URL | Mode while the primary **is** the home region (§9.2). Writer or global writer endpoint → `strict_writer`; other endpoints → `home_reader_or_writer`. | | `out_of_home_failover_mode` | String | depends on URL | Mode while the primary **is not** the home region. Same values and derivation as above. | -| `global_cluster_instance_host_patterns` | String | none | Comma-separated instance host patterns for every region, e.g. `?.xyz1.us-east-1.rds.amazonaws.com,?.xyz2.us-west-1.rds.amazonaws.com`. Prefix custom-domain patterns with `[region]`. Required for Global Databases. | +| `global_cluster_instance_host_patterns` | String | none | Comma-separated instance host patterns for every region, e.g. `?.xyz1.us-east-1.rds.amazonaws.com,?.xyz2.us-west-1.rds.amazonaws.com`. Prefix custom-domain patterns with `[region]`. Required for Global Databases. Only read for `global-aurora-*` dialects. [Unreleased] `gdb_failover` on a database identified as a regional cluster (e.g. `wrapper_dialect: aurora-pg`, or a single-region Global Database with `wrapper_dialect` unset) behind an IP / own domain without `cluster_instance_host_pattern` logs a `WARN` that this setting doesn't apply, and failover raises `FailoverFailedError` immediately. | | `accessible_regions` | String | all regions | Comma-separated regions the application can reach. Failover only considers nodes in these regions; topology monitoring still tracks every region. Must include the home region if set. | | `failover_timeout_sec` | Float | `300.0` | As `failover`. | | `failover_reader_host_selector_strategy` | String | `random` | As `failover`. | @@ -1529,7 +1529,8 @@ All under `AwsAdvancedRubyDriverWrapper::Errors`, subclasses of `AwsError`: | `ActiveRecord::ConnectionFailed ... FailoverFailedError` | Failover could not reach a new instance within `failover_timeout_sec` (not a success) | Check cluster health and reachability of instance endpoints (security groups, `cluster_instance_host_pattern` for IP/CNAME hosts); the pool will replace the connection | | A request or job fails with `FailoverSuccessError` under Active Record (the process keeps running; later work uses the reconnected connection) | The adapter re-raises it unchanged after reconnecting | Rescue it and replay idempotent work (§9.3) | | Session settings (timezone, search path, statement timeout) lost after failover | Not declared under `variables:` | Move them under `variables:` (§13.4) | -| Failover doesn't work behind an IP address or own domain name; topology never resolves | No `cluster_instance_host_pattern`, so per-instance hostnames can't be built | Set `cluster_instance_host_pattern` (§3.11) | +| [Unreleased] `WARN` at connect: `The connection host '' is not a recognized RDS endpoint and cluster_instance_host_pattern is not set, so the failover plugin cannot build DB instance hosts ...` | IP address or own domain name in front of an Aurora / Multi-AZ DB cluster, no `cluster_instance_host_pattern` | Set `cluster_instance_host_pattern` (§3.11), or remove `failover` from `wrapper_plugins` | +| Failover doesn't work behind an IP address or own domain name. Before `[Unreleased]`: `FailoverFailedError` after `failover_timeout_sec`; from `[Unreleased]`: `FailoverFailedError: Failover is not possible. ...` immediately | No `cluster_instance_host_pattern`, so per-instance hostnames are bare instance names | Set `cluster_instance_host_pattern` (§3.11); `?` if bare instance names resolve in the app's environment | | Topology from one cluster appears in another / failover reconnects to the wrong cluster | Several clusters share the default `cluster_id` | Distinct `cluster_id` per cluster | | Topology monitor uses the wrong user or database, or ignores timeout overrides | The monitor keeps the context of the first connection that created it for that `cluster_id` | Put `topology_monitoring_*` settings on every connection sharing the `cluster_id` | | Global Database connection fails at setup | Missing `global_cluster_instance_host_patterns`, or missing `failover_home_region` on the global endpoint | Set both (§5.2) | diff --git a/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md b/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md index 0639712b..e3cb1a7c 100644 --- a/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md +++ b/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md @@ -260,7 +260,7 @@ How it works, in brief: the `failover` plugin starts failover when a call fails 1. Is `failover` (or `gdb_failover`) loaded? Setting `wrapper_plugins` replaces the defaults, so `wrapper_plugins: iam` drops failover. 2. Was the error a network error? Statement timeouts, query cancellations, deadlocks, lock wait timeouts, constraint violations, and authentication failures don't trigger failover. With `mysql2` before 1.1.0, a `read_timeout` and MySQL's idle disconnect (error 4031) don't either (see below). -3. Was there a host list? With `DEBUG` on, `Skipping failover for : no topology available.` means the wrapper had no host list at all. That's unusual - the host list normally holds at least the host the app connected to - so if it persists, collect `DEBUG` logs and escalate (§7). (An IP address or own domain name without `cluster_instance_host_pattern` doesn't cause this line: failover does start, but the instance hostnames it builds are bare instance names that usually don't resolve, so it ends in `FailoverFailedError` - set `cluster_instance_host_pattern`.) +3. Was there a host list? With `DEBUG` on, `Skipping failover for : no topology available.` means the wrapper had no host list at all. That's unusual - the host list normally holds at least the host the app connected to - so if it persists, collect `DEBUG` logs and escalate (§7). (An IP address or own domain name without `cluster_instance_host_pattern` doesn't cause this line: failover does start, but the instance hostnames it would build are bare instance names that usually don't resolve. Before `[Unreleased]`, it retries them and ends in `FailoverFailedError` after `failover_timeout_sec`; from `[Unreleased]`, it raises `FailoverFailedError: Failover is not possible. ...` immediately, and a `WARN` was already logged at connect (§5). Set `cluster_instance_host_pattern`.) 4. Was the connection closed by the app? `Connection was explicitly closed, skipping failover`. 5. Did it fail while opening a connection? Failover covers calls on an open connection. A connection that fails to open - including a new connection an Active Record pool opens - is only redirected to another instance with `enable_connect_failover: true`. @@ -295,6 +295,7 @@ end | Message | Meaning | Check | |---|---|---| +| [Unreleased] `Failover is not possible. The connection host '' is not a recognized RDS endpoint and cluster_instance_host_pattern is not set ...` | The wrapper can't build DB instance hosts, so it didn't try to fail over. Raised immediately; a `WARN` with the same text was logged at connect | Set `cluster_instance_host_pattern` (e.g. `?.XXX.us-east-1.rds.amazonaws.com`, or `?` if bare instance names resolve). Retrying or raising `failover_timeout_sec` won't help | | `The request to discover the new topology timed out or was unsuccessful` (writer failover, `gdb_failover`) / `The request to discover the new topology was unsuccessful` (reader failover) | Writer failover: the topology monitor couldn't confirm a writer within `failover_timeout_sec`. Reader failover: the wrapper couldn't get a host list from the monitor | The monitor connects to every instance endpoint: reachability (§3.3), credentials, TLS. With `DEBUG`, look for `[] Connection to failed: ` (network and TLS failures), `[] Instance Monitor : ` (credential rejections on instance connections appear here, not as `Connection to ... failed`), and `Failed to open monitoring connection`. On PostgreSQL, a misspelled `topology_monitoring_*` option makes every monitor connection fail with `invalid connection option` | | `Unable to connect to a writer instance` / `Writer failover timed out after s. Unable to connect to a new writer instance.` | A writer was identified but the app couldn't connect to it in time | Reachability of that instance endpoint, credentials (e.g. IAM token for the instance host), cluster health | | `Unable to connect to a reader instance` | `strict_reader` / `reader_or_writer` found no usable reader | Are there healthy readers? Before 1.1.0: is `failover_reader_host_selector_strategy` `random` or a registered selector (known issue, §6.4)? From 1.1.0 a bad name is rejected at setup, but a selector that raises is logged (`Failed to select a reader using the '' host selection strategy: ...`) and treated as finding no reader | @@ -343,6 +344,7 @@ Raising `failover_timeout_sec` doesn't help any of these unless the cluster itse **Global Database (`gdb_failover`):** - Connection fails at setup - `global_cluster_instance_host_patterns` missing or malformed (§4.2), or `failover_home_region` missing on the global endpoint / IP / own domain. +- [Unreleased] Warning at connect `... The database was identified as a regional cluster rather than an Aurora Global Database, so global_cluster_instance_host_patterns does not apply ...`, then `FailoverFailedError: Failover is not possible. ...` on failover - an IP / own domain host without `cluster_instance_host_pattern`, on a database detected as regional (`wrapper_dialect: aurora-pg` / `aurora-mysql`, or a single-region Global Database with `wrapper_dialect` unset; detection needs more than one region). Set `wrapper_dialect` to `global-aurora-pg` / `global-aurora-mysql` and set `global_cluster_instance_host_patterns`; for a standalone cluster, use `failover` with `cluster_instance_host_pattern`. - Warning `Unable to determine region of writer . Please ensure you have set the global_cluster_instance_host_patterns setting.` - the patterns don't cover the writer's region. - After a cross-region switchover the connection can't write - `out_of_home_failover_mode` is a home-reader mode; use `strict_writer` for writer connections. The INFO line `The GDB primary is now , which is in region '' rather than the home region ''. Using out_of_home_failover_mode=.` shows which mode applied. - IAM on the global endpoint fails - add `initial_connection`, and grant `rds:DescribeGlobalClusters`. @@ -418,6 +420,7 @@ Lines are tagged with the `cluster_id` in brackets where one applies, e.g. `[1] | DEBUG | `Writer failover duration: ms` / `Reader failover duration: ms` | How long it took (logged whether it succeeded or failed) | | DEBUG | `Established connection to: ` | Failover succeeded; the connection now points at this host | | DEBUG | `Stale DNS data detected. Opening a connection to ` | The cluster endpoint resolved to a reader; the plugin went straight to the writer instance | +| WARN | [Unreleased] `The connection host '' is not a recognized RDS endpoint and cluster_instance_host_pattern is not set, so the failover plugin cannot build DB instance hosts from the cluster topology. Failover will fail with FailoverFailedError. ...` | Logged once per host at connect: an IP / own domain name in front of an Aurora or Multi-AZ DB cluster without the pattern. Any failover raises `FailoverFailedError` immediately (§4.4). Set `cluster_instance_host_pattern`, or `?` if bare instance names resolve | A healthy writer failover reads: `Detected error` → `Starting writer failover` → `Writer changed: A -> B` (or `Writer verified: B` / `Writer found: B`, depending on which monitor reached the new writer first) → `Writer failover duration` → `Established connection to: B` (reader failover logs `Established connection to:` before its duration line). A `Starting writer failover` that ends on the same host means the connection was lost but the writer didn't change (§4.4). @@ -477,7 +480,7 @@ Where they apply: `failover` + `initial_connection` on Aurora clusters and RDS M | `wrapper_plugins` | `failover,initial_connection` | Comma-separated string, not a list | | `wrapper_dialect` | auto-detected | `aurora-pg`, `global-aurora-pg`, `multi-az-pg-cluster`, `rds-pg`, `pg`, `aurora-mysql`, `global-aurora-mysql`, `multi-az-mysql-cluster`, `rds-mysql`, `mysql` | | `cluster_id` | `'1'` | Distinct per cluster; the same for every entry on one cluster. A Global Database is one cluster for `gdb_failover` connections in any region (§4.4). Quote numeric values in YAML | -| `cluster_instance_host_pattern` | derived for RDS hosts | Required for IP / own domain with failover: `?.XXX..rds.amazonaws.com` | +| `cluster_instance_host_pattern` | derived for RDS hosts | Required for IP / own domain with failover: `?.XXX..rds.amazonaws.com`. [Unreleased] Missing on a cluster: a `WARN` at connect, and failover fails immediately; an explicit `?` opts out | | `failover_mode` | `reader_or_writer` on `-ro-` endpoints, else `strict_writer` | `strict_writer`, `strict_reader`, `reader_or_writer` | | `failover_timeout_sec` | `300.0` | Seconds, not milliseconds | | `enable_connect_failover` | `false` | Failover when opening a connection fails | From c27fb7cdb6ea6ebc185ca7a27e5c1bd4a76b8ce5 Mon Sep 17 00:00:00 2001 From: aaron-congo Date: Mon, 30 Nov 2026 14:33:44 -0700 Subject: [PATCH 5/5] skill: clarify which host pattern applies for gdb_failover A Global Database only needs global_cluster_instance_host_patterns; on a regional dialect that setting is ignored and cluster_instance_host_pattern applies instead. --- skills/ruby-wrapper-configuration-assistant/SKILL.md | 2 +- skills/ruby-wrapper-troubleshooting-assistant/SKILL.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/ruby-wrapper-configuration-assistant/SKILL.md b/skills/ruby-wrapper-configuration-assistant/SKILL.md index c7cc5fa6..7d8f2c16 100644 --- a/skills/ruby-wrapper-configuration-assistant/SKILL.md +++ b/skills/ruby-wrapper-configuration-assistant/SKILL.md @@ -786,7 +786,7 @@ Region-aware failover for Aurora Global Database. Introduces a **home region** a | `failover_home_region` | String | parsed from URL | The AWS region the application runs in. Required when the endpoint carries no region. | | `in_home_failover_mode` | String | depends on URL | Mode while the primary **is** the home region (§9.2). Writer or global writer endpoint → `strict_writer`; other endpoints → `home_reader_or_writer`. | | `out_of_home_failover_mode` | String | depends on URL | Mode while the primary **is not** the home region. Same values and derivation as above. | -| `global_cluster_instance_host_patterns` | String | none | Comma-separated instance host patterns for every region, e.g. `?.xyz1.us-east-1.rds.amazonaws.com,?.xyz2.us-west-1.rds.amazonaws.com`. Prefix custom-domain patterns with `[region]`. Required for Global Databases. Only read for `global-aurora-*` dialects. [Unreleased] `gdb_failover` on a database identified as a regional cluster (e.g. `wrapper_dialect: aurora-pg`, or a single-region Global Database with `wrapper_dialect` unset) behind an IP / own domain without `cluster_instance_host_pattern` logs a `WARN` that this setting doesn't apply, and failover raises `FailoverFailedError` immediately. | +| `global_cluster_instance_host_patterns` | String | none | Comma-separated instance host patterns for every region, e.g. `?.xyz1.us-east-1.rds.amazonaws.com,?.xyz2.us-west-1.rds.amazonaws.com`. Prefix custom-domain patterns with `[region]`. Required for Global Databases, and the only host pattern a Global Database needs: `cluster_instance_host_pattern` isn't required there. Only read for `global-aurora-*` dialects. If the database is identified as a regional cluster instead (e.g. `wrapper_dialect: aurora-pg`, or a single-region Global Database with `wrapper_dialect` unset), this setting is ignored and `cluster_instance_host_pattern` applies, as with `failover`. [Unreleased] In that case, behind an IP / own domain without `cluster_instance_host_pattern`, `gdb_failover` logs a `WARN` that this setting doesn't apply, and failover raises `FailoverFailedError` immediately. Fix: for a Global Database, set `wrapper_dialect` to `global-aurora-pg` / `global-aurora-mysql` and keep this setting; for a standalone cluster, use `failover` with `cluster_instance_host_pattern`. | | `accessible_regions` | String | all regions | Comma-separated regions the application can reach. Failover only considers nodes in these regions; topology monitoring still tracks every region. Must include the home region if set. | | `failover_timeout_sec` | Float | `300.0` | As `failover`. | | `failover_reader_host_selector_strategy` | String | `random` | As `failover`. | diff --git a/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md b/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md index e3cb1a7c..79563f22 100644 --- a/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md +++ b/skills/ruby-wrapper-troubleshooting-assistant/SKILL.md @@ -344,7 +344,7 @@ Raising `failover_timeout_sec` doesn't help any of these unless the cluster itse **Global Database (`gdb_failover`):** - Connection fails at setup - `global_cluster_instance_host_patterns` missing or malformed (§4.2), or `failover_home_region` missing on the global endpoint / IP / own domain. -- [Unreleased] Warning at connect `... The database was identified as a regional cluster rather than an Aurora Global Database, so global_cluster_instance_host_patterns does not apply ...`, then `FailoverFailedError: Failover is not possible. ...` on failover - an IP / own domain host without `cluster_instance_host_pattern`, on a database detected as regional (`wrapper_dialect: aurora-pg` / `aurora-mysql`, or a single-region Global Database with `wrapper_dialect` unset; detection needs more than one region). Set `wrapper_dialect` to `global-aurora-pg` / `global-aurora-mysql` and set `global_cluster_instance_host_patterns`; for a standalone cluster, use `failover` with `cluster_instance_host_pattern`. +- [Unreleased] Warning at connect `... The database was identified as a regional cluster rather than an Aurora Global Database, so global_cluster_instance_host_patterns does not apply ...`, then `FailoverFailedError: Failover is not possible. ...` on failover. The host is an IP / own domain name, `cluster_instance_host_pattern` isn't set, and the database was detected as regional (`wrapper_dialect: aurora-pg` / `aurora-mysql`, or a single-region Global Database with `wrapper_dialect` unset; detection needs more than one region). `global_cluster_instance_host_patterns` is only read for `global-aurora-*` dialects; on a regional dialect, `cluster_instance_host_pattern` applies instead. Fix for a Global Database: set `wrapper_dialect` to `global-aurora-pg` / `global-aurora-mysql` and keep `global_cluster_instance_host_patterns` (the only host pattern a Global Database needs; `cluster_instance_host_pattern` isn't required). Fix for a standalone cluster: use `failover` with `cluster_instance_host_pattern`. - Warning `Unable to determine region of writer . Please ensure you have set the global_cluster_instance_host_patterns setting.` - the patterns don't cover the writer's region. - After a cross-region switchover the connection can't write - `out_of_home_failover_mode` is a home-reader mode; use `strict_writer` for writer connections. The INFO line `The GDB primary is now , which is in region '' rather than the home region ''. Using out_of_home_failover_mode=.` shows which mode applied. - IAM on the global endpoint fails - add `initial_connection`, and grant `rds:DescribeGlobalClusters`.