Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ def handle_writer_found(host_info, conn)
end

def reader_fetch_topology(conn, host_info, writer_changed)
hosts = query_topology(conn)
hosts = query_topology_or_nil(conn)
return writer_changed if hosts.nil?

@panic_mutex.synchronize do
Expand Down Expand Up @@ -502,6 +502,17 @@ def fetch_topology_and_update_cache(conn)
nil
end

# Instance monitors must outlive a failed query: the host being monitored is often the instance that is
# restarting (e.g. the promoted writer), and an error escaping the monitor loop would end its thread for good,
# since a monitor that is still registered is never respawned. On error the next iteration's role check fails
# too and reconnects.
def query_topology_or_nil(conn)
query_topology(conn)
rescue StandardError => e
logger.debug("[#{@cluster_id}] Instance monitor topology query failed: #{e.message}")
nil
end

def query_topology(conn)
@service_container.dialect_service.with_monitoring_query_timeout(conn, @monitoring_wrapper_props) do
@topology_utils.query_topology(conn, @initial_host_info, @instance_template)
Expand Down
294 changes: 294 additions & 0 deletions spec/integration/container/query_timeout_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
# frozen_string_literal: true

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

require_relative 'integration_helper'
require_relative 'utils/test_utils'
require_relative 'utils/test_environment'
require_relative 'utils/test_environment_features'
require_relative 'utils/driver_helper'
require_relative 'utils/proxy_helper'
require_relative 'utils/database_engine'
require_relative 'utils/database_engine_deployment'
require_relative 'utils/rds_test_utility'
require_relative 'utils/retry_helper'
require_relative 'utils/topology_helper'
require 'aws_advanced_ruby_driver_wrapper'

# pg_query_timeout_sec bounds the wrapper's own queries (topology monitor, role checks, dialect detection).
# Without a timeout, the monitor's topology query on that connection blocks forever.
#
# The monitor opens its connection through the cluster endpoint and keeps it while the writer is verified, so silencing
# the cluster endpoint proxy blocks the monitor but not the instance endpoints that failover and the monitor's panic
# mode connect to. Every example proves that precondition first, using the topology cache as the monitor's heartbeat:
# a healthy monitor stores a new entry every refresh, a blocked one stops. That keeps the negative controls from
# passing for the wrong reason (for example a monitor that was never blocked).
RSpec.describe 'Query timeout', :integration,
features: [Integration::TestEnvironmentFeatures::FAILOVER_SUPPORTED,
Integration::TestEnvironmentFeatures::NETWORK_OUTAGES_ENABLED],
deployments: [Integration::DatabaseEngineDeployment::AURORA,
Integration::DatabaseEngineDeployment::RDS_MULTI_AZ_CLUSTER],
enable_on_engines: [Integration::DatabaseEngine::PG],
disable_on_features: [Integration::TestEnvironmentFeatures::PERFORMANCE] do
# The original report's failover timeout.
let(:failover_timeout_sec) { 15 }
# The bound the monitor is expected to apply. DriverDialect::DEFAULT_MONITORING_TIMEOUT_SEC when the property is unset.
let(:query_timeout_sec) { 5 }
let(:configured_query_timeout_sec) { query_timeout_sec }
let(:plugins) { 'failover,initial_connection' }
let(:extra_props) { {} }

let(:rds_util) { Integration::RdsTestUtility.utility }
let(:proxy_info) { env.proxy_database_info }
let(:cluster_endpoint) { proxy_info.cluster_endpoint }

# The monitor refreshes about once a second; two refresh periods without a new topology entry mean it is blocked.
# This has to stay well below the shortest query timeout used here, or the monitor can recover before it is seen blocked.
let(:monitor_blocked_after_sec) { 2.0 }
let(:timeout_log_pattern) { /Wrapper query timed out after/ }

let(:timeout_props) do
props = {
AwsAdvancedRubyDriverWrapper::PropertyDefinition::PLUGINS.name => plugins,
AwsAdvancedRubyDriverWrapper::PropertyDefinition::FAILOVER_TIMEOUT_SEC.name => failover_timeout_sec,
AwsAdvancedRubyDriverWrapper::PropertyDefinition::CLUSTER_INSTANCE_HOST_PATTERN.name =>
"?.#{proxy_info.instance_endpoint_suffix}:#{proxy_info.instance_endpoint_port}",
AwsAdvancedRubyDriverWrapper::PropertyDefinition::CLUSTER_TOPOLOGY_REFRESH_RATE_SEC.name => 1.0,
connect_timeout: 10,
**extra_props,
**Integration::TelemetryHelper.wrapper_props
}
unless configured_query_timeout_sec.nil?
props[AwsAdvancedRubyDriverWrapper::PropertyDefinition::PG_QUERY_TIMEOUT_SEC.name] = configured_query_timeout_sec
end
props
end

def timeout_connect
config = Integration::DriverHelper.native_config(
drv,
host: cluster_endpoint,
port: proxy_info.cluster_endpoint_port,
user: proxy_info.username,
password: proxy_info.password,
dbname: proxy_info.default_dbname
)
conn = Integration::DriverHelper.wrapper_connect(drv, **config, **timeout_props)
expect(wait_for_full_topology).to be(true), 'Topology was not fully discovered after establishing a connection'
expect(wait_for_topology_refresh?(timeout_secs: 20)).to be(true), 'Topology monitor is not refreshing the topology'
conn
end

def wait_for_full_topology(timeout_secs: 30)
Integration::TopologyHelper.wait_for_topology(
min_instances: proxy_info.instances.size,
require_instance_hosts: false,
timeout_secs: timeout_secs,
delay_secs: 0.5
)
end

# The monitor's heartbeat: it stores a new topology entry on every refresh, so the entry's identity changes.
def topology_entry
Integration::TopologyHelper.cached_hosts(AwsAdvancedRubyDriverWrapper::PropertyDefinition::CLUSTER_ID.default_value)
end

# True once the monitor stores a topology entry newer than +since+ (default: the current one).
def wait_for_topology_refresh?(timeout_secs:, since: topology_entry)
deadline = monotonic_now + timeout_secs
sleep(0.1) until !topology_entry.equal?(since) || monotonic_now >= deadline
!topology_entry.equal?(since)
end

# True once the monitor has stored no topology entry for monitor_blocked_after_sec, i.e. it is stuck in a query.
def wait_for_monitor_blocked?(timeout_secs: 15)
deadline = monotonic_now + timeout_secs
last = topology_entry
last_change = monotonic_now
until monotonic_now >= deadline
sleep(0.1)
current = topology_entry
if current.equal?(last)
return true if monotonic_now - last_change >= monitor_blocked_after_sec
else
last = current
last_change = monotonic_now
end
end
false
end

# Collects the wrapper's log lines while the block runs. The wrapper logs a monitor query that hit its timeout.
def capture_wrapper_log
logger = AwsAdvancedRubyDriverWrapper.logger
original = logger.formatter
lines = Concurrent::Array.new
logger.formatter = proc do |severity, time, progname, msg|
lines << msg.to_s
original.call(severity, time, progname, msg)
end
yield lines
ensure
logger.formatter = original
end

def wait_for_log(lines, pattern, timeout_secs:)
deadline = monotonic_now + timeout_secs
sleep(0.2) until lines.any? { |line| line.match?(pattern) } || monotonic_now >= deadline
lines.any? { |line| line.match?(pattern) }
end

def monotonic_now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

def silence_monitor
Integration::ProxyHelper.silence_connectivity(cluster_endpoint)
expect(wait_for_monitor_blocked?).to be(true),
'Topology monitor kept refreshing after the cluster endpoint was silenced, ' \
'so the monitor is not blocked on it and this example would not exercise the timeout'
end

# The application notices the dead connection on its own, as it would with tcp_user_timeout, here by losing its
# socket, and starts a failover. Nothing in this depends on which instance is the writer or on a real failover, so it
# holds on Aurora and Multi-AZ alike. Returns the seconds the failover took.
def fail_over_from_dropped_app_connection(conn)
conn.send(:current_conn).finish
started = monotonic_now
expect { rds_util.query_instance_id(conn) }.to raise_error(AwsAdvancedRubyDriverWrapper::Errors::FailoverSuccessError)
monotonic_now - started
end

# The examples drop the application's connection themselves, and a failed failover leaves it closed.
def close_quietly(conn)
Integration::DriverHelper.close(drv, conn) if conn
rescue StandardError => e
Integration::TestUtils.logger.debug("Ignoring error closing the test connection: #{e.class}")
end

after do
Integration::ProxyHelper.restore_connectivity(cluster_endpoint)
end

# Examples where the monitor's own timeout is in force: explicit, default, or set for the monitor only.
shared_examples 'a monitor that bounds its queries' do
it 'gives up on the silent connection by itself and refreshes the topology while the writer is still silent' do
enable_on_num_instances(min_instances: 2)
conn = timeout_connect

capture_wrapper_log do |lines|
silence_monitor
stalled_entry = topology_entry
timed_out = wait_for_log(lines, timeout_log_pattern, timeout_secs: query_timeout_sec * 3)
expect(timed_out).to be(true), 'Monitor query never timed out on the silent connection'
# The monitor leaves the silent connection and refreshes through the instance endpoints, which still answer.
# Waiting for the proxy to release the old connection would pass even if the query never timed out.
resumed = wait_for_topology_refresh?(timeout_secs: 15, since: stalled_entry)
expect(resumed).to be(true), 'Monitor did not resume refreshing the topology after its query timed out'
end

Integration::ProxyHelper.restore_connectivity(cluster_endpoint)
expect(Integration::RetryHelper.verify_writer(rds_util, rds_util.query_instance_id(conn))).to be true
ensure
Integration::ProxyHelper.restore_connectivity(cluster_endpoint)
close_quietly(conn)
end

it 'completes writer failover within failover_timeout_sec when the monitor connection stops answering' do
enable_on_num_instances(min_instances: 2)
conn = timeout_connect

capture_wrapper_log do |lines|
silence_monitor
elapsed = fail_over_from_dropped_app_connection(conn)
# Recovery is driven by the monitor's query timeout, so it takes about that long, not the whole failover timeout.
expect(elapsed).to be <= query_timeout_sec + 8
expect(lines.any? { |line| line.match?(timeout_log_pattern) }).to be(true),
'Failover recovered without the monitor query timing out'
end

expect(Integration::RetryHelper.verify_writer(rds_util, rds_util.query_instance_id(conn))).to be true
ensure
Integration::ProxyHelper.restore_connectivity(cluster_endpoint)
close_quietly(conn)
end
end

context 'with pg_query_timeout_sec set' do
it_behaves_like 'a monitor that bounds its queries'
end

context 'with pg_query_timeout_sec unset (monitoring default)' do
let(:configured_query_timeout_sec) { nil }

it_behaves_like 'a monitor that bounds its queries'
end

# topology_monitoring_pg_query_timeout_sec wins for the topology monitor over pg_query_timeout_sec, including 0.
context 'with topology_monitoring_pg_query_timeout_sec overriding a disabled pg_query_timeout_sec' do
let(:configured_query_timeout_sec) { 0 }
let(:query_timeout_sec) { 4 }
let(:extra_props) { { topology_monitoring_pg_query_timeout_sec: query_timeout_sec } }

it_behaves_like 'a monitor that bounds its queries'
end

# Negative controls: the same scenario with pg_query_timeout_sec set to 0, which turns the timeout off. They pass
# only when the bug reproduces, so a failure here means the proxy is not blocking the monitor the way the examples
# above assume and those examples prove nothing.
context 'with pg_query_timeout_sec disabled (control)' do
let(:configured_query_timeout_sec) { 0 }

# With no query timeout the monitor stays blocked on the silent connection.
def release_blocked_monitor
Integration::ProxyHelper.restore_connectivity(cluster_endpoint)
Integration::ProxyHelper.disable_proxy(cluster_endpoint)
Integration::ProxyHelper.enable_proxy(cluster_endpoint)
end

it 'leaves the monitor blocked on a silent connection' do
enable_on_num_instances(min_instances: 2)
conn = timeout_connect

capture_wrapper_log do |lines|
silence_monitor
stalled_entry = topology_entry
# Several default-timeout periods later the monitor is still stuck: no refresh and no query timeout.
resumed = wait_for_topology_refresh?(timeout_secs: 10, since: stalled_entry)
expect(resumed).to be(false), 'Monitor resumed refreshing even though pg_query_timeout_sec is 0'
expect(lines.any? { |line| line.match?(timeout_log_pattern) }).to be(false),
'Monitor query timed out even though pg_query_timeout_sec is 0'
end
ensure
release_blocked_monitor
close_quietly(conn)
end

it 'fails writer failover when the monitor connection stops answering' do
enable_on_num_instances(min_instances: 2)
conn = timeout_connect

silence_monitor
conn.send(:current_conn).finish

expect { rds_util.query_instance_id(conn) }.to raise_error(
AwsAdvancedRubyDriverWrapper::Errors::FailoverFailedError
)
ensure
release_blocked_monitor
close_quietly(conn)
end
end
end
4 changes: 4 additions & 0 deletions spec/integration/container/utils/proxy_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ def disable_connectivity(instance_name)
disable_proxy(instance_name)
end

def silence_connectivity(instance_name)
disable_proxy_connectivity(TestEnvironment.current.proxy_info(instance_name))
end

def enable_all_connectivity
TestEnvironment.current.proxy_infos.each { |p| enable_proxy_instance(p) }
end
Expand Down
19 changes: 19 additions & 0 deletions spec/unit/monitoring/cluster_topology_monitor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,25 @@ def build_monitor(wrapper_props)
end
end

describe 'instance monitor resilience' do
it 'keeps monitoring after a reader topology query raises, so a restarting instance is still found as the writer' do
roles = [AwsAdvancedRubyDriverWrapper::Host::HostRole::READER, AwsAdvancedRubyDriverWrapper::Host::HostRole::WRITER]
allow(db_dialect).to receive(:host_role) { roles.size > 1 ? roles.shift : roles.first }
# The instance drops the connection mid-query while it is promoted to writer.
calls = 0
allow(topology_utils).to receive(:query_topology) do
calls += 1
raise StandardError, 'SSL error: unexpected eof while reading' if calls == 1

[writer_host, reader_host]
end

monitor.send(:instance_monitor, reader_host)

expect(monitor.instance_variable_get(:@instance_monitors_writer_info)).to eq(reader_host)
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)
Expand Down
Loading