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
12 changes: 5 additions & 7 deletions lib/aws_advanced_ruby_driver_wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ class << self
attr_reader :config
end

# Gracefully tears down all background resources. Invoked by the at_exit hook (and thus
# indirectly by the TERM/INT signal traps, which just exit). Safe to call more than once.
# Gracefully tears down all background resources. Invoked by the at_exit hook. Safe to call more
# than once.
def self.shutdown(grace_period_sec: 10)
Plugins::BlueGreen::BlueGreenPlugin.clean_up_providers
release_resources(grace_period_sec: grace_period_sec)
Expand Down Expand Up @@ -114,11 +114,9 @@ def self.release_resources(grace_period_sec: 5)
end
end

# Register signal traps and at_exit hook for graceful shutdown. The traps only exit — the real
# teardown runs in the at_exit hook, since acquiring locks / joining threads inside a signal-trap
# context is unsafe in Ruby and can deadlock.
%w[TERM INT].each { |signal| trap(signal) { exit(0) } }

# Tear down background resources when the process exits. at_exit hooks also run when the process is
# ended by INT or TERM under Ruby's default handlers, so the gem deliberately installs no signal
# handlers of its own: doing so would replace the application's handlers and change its exit status.
at_exit { AwsAdvancedRubyDriverWrapper.shutdown }

Process.singleton_class.prepend(AwsAdvancedRubyDriverWrapper::ForkHook)
Expand Down
166 changes: 166 additions & 0 deletions spec/unit/shutdown_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
# limitations under the License.

require 'rspec'
require 'open3'
require 'prism'
require 'rbconfig'
require 'timeout'
require 'aws_advanced_ruby_driver_wrapper'
require 'aws_advanced_ruby_driver_wrapper/monitoring/monitor'
require 'aws_advanced_ruby_driver_wrapper/services/service_utility'
Expand Down Expand Up @@ -47,3 +51,165 @@ def monitor
described_class.shutdown
end
end

# Signal handlers are process-wide, so these checks run in a fresh Ruby process rather than in the
# RSpec process.
RSpec.describe 'Signal handling after requiring the gem' do
lib_dir = File.expand_path('../../lib', __dir__)

it 'keeps the TERM and INT handlers the application registered before the require' do
script = <<~RUBY
term_handler = proc {}
int_handler = proc {}
Signal.trap('TERM', term_handler)
Signal.trap('INT', int_handler)
require 'aws_advanced_ruby_driver_wrapper'
# Signal.trap returns the handler it replaces, so this prints whether each handler registered
# above is still the one installed after the require.
{ 'TERM' => term_handler, 'INT' => int_handler }.each do |signal, handler|
puts "\#{signal} handler kept: \#{Signal.trap(signal, 'DEFAULT').equal?(handler)}"
end
RUBY

# Pass/fail depends only on stdout, so a warning Ruby prints to stderr cannot fail the test. Stderr is
# still shown in the failure message to help debug a real failure.
stdout, stderr, status = Open3.capture3(RbConfig.ruby, '-I', lib_dir, '-e', script)

expect(status).to be_success, stderr
expect(stdout).to eq("TERM handler kept: true\nINT handler kept: true\n"), stderr
end

# Starts a process that requires the gem, runs +setup+, and sleeps, then sends it +signal+. Returns
# the process's output, its exit status, and the seconds between the signal and the exit. The
# process prints a marker once the wrapper's at_exit shutdown has completed, followed by the state
# of the monitor in $signal_test_monitor, and whether its loop finished, if +setup+ started one.
def run_until_signaled(lib_dir, signal, setup: '')
script = <<~RUBY
$stdout.sync = true
require 'aws_advanced_ruby_driver_wrapper'
AwsAdvancedRubyDriverWrapper.singleton_class.prepend(Module.new do
def shutdown(...)
super
puts 'shutdown ran'
if $signal_test_monitor
puts "monitor state: \#{$signal_test_monitor.state}"
puts "monitor finished: \#{$signal_test_monitor_finished == true}"
end
end
end)
#{setup}
begin
puts 'ready'
sleep
rescue Interrupt
puts 'rescued Interrupt'
raise
end
RUBY

Open3.popen3(RbConfig.ruby, '-I', lib_dir, '-e', script) do |_stdin, out, err, wait_thread|
err_reader = Thread.new { err.read }
Timeout.timeout(30) do
# Wait for the exact line on stdout so the signal is never sent while the gem is still loading.
line = out.gets
line = out.gets until line.nil? || line.chomp == 'ready'
raise "child exited before it was ready: #{out.read}#{err_reader.value}" if line.nil?

signaled_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
Process.kill(signal, wait_thread.pid)
status = wait_thread.value
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - signaled_at
[out.read + err_reader.value, status, elapsed]
end
ensure
# Open3 waits for the child when the block ends, so kill it if it is still running (for example
# after a timeout) instead of letting the suite hang.
begin
Process.kill('KILL', wait_thread.pid) if wait_thread.alive?
rescue Errno::ESRCH
# The child exited between the check and the kill.
end
end
end

it 'is terminated by TERM and still runs the wrapper shutdown' do
output, status = run_until_signaled(lib_dir, 'TERM')

expect(status.termsig).to eq(Signal.list['TERM']), output
expect(output).to include('shutdown ran')
end

it 'raises Interrupt on INT, is terminated by INT, and still runs the wrapper shutdown' do
output, status = run_until_signaled(lib_dir, 'INT')

expect(status.termsig).to eq(Signal.list['INT']), output
expect(output).to include('rescued Interrupt')
expect(output).to include('shutdown ran')
end

it 'stops background monitors from the at_exit shutdown when terminated by TERM' do
# Monitor#stop kills a monitor thread that does not finish within its termination timeout and still
# reports the monitor as stopped, so the monitor records when its loop finishes on its own. The
# short timeout only keeps a monitor that ignores the stop request from delaying the test by the
# 30 second default.
setup = <<~RUBY
require 'aws_advanced_ruby_driver_wrapper/monitoring/monitor'
require 'aws_advanced_ruby_driver_wrapper/services/service_utility'
monitor_class = Class.new(AwsAdvancedRubyDriverWrapper::Monitoring::Monitor) do
def monitor
sleep(0.01) until stopped?
$signal_test_monitor_finished = true
end
end
monitor_service = AwsAdvancedRubyDriverWrapper::Services::CoreServices.monitor_service
monitor_service.register_type(:signal_test_monitor, expiration_timeout_sec: 60)
$signal_test_monitor = monitor_service.run_if_absent(:signal_test_monitor, 'k1', Object.new) do |_|
monitor_class.new(termination_timeout_sec: 2)
end
raise "monitor did not start: \#{$signal_test_monitor.state}" unless $signal_test_monitor.state == :running
RUBY

output, status, elapsed = run_until_signaled(lib_dir, 'TERM', setup: setup)

expect(status.termsig).to eq(Signal.list['TERM']), output
expect(output).to include('shutdown ran')
expect(output).to include('monitor state: stopped')
expect(output).to include('monitor finished: true')
# Shutdown wakes the monitor service's cleanup thread from its 60 second sleep and waits up to 5
# seconds for it to exit. If the wakeup stopped working, every shutdown would take the full 5 seconds,
# which only this timing check would notice.
expect(elapsed).to be < 5, output
end
end

# The gem must never install signal handlers, since doing so replaces the application's handlers.
# Many files under lib/ are only loaded once a connection uses them, so checking the handlers after
# requiring the gem cannot cover them. This parses every file instead and flags any call to a method
# named trap (Signal.trap, Kernel.trap or a bare trap). Indirect calls such as send(:trap) are not
# detected.
RSpec.describe 'Signal handlers in the gem source' do
trap_call_finder = Class.new(Prism::Visitor) do
attr_reader :lines

def initialize
super
@lines = []
end

def visit_call_node(node)
@lines << node.location.start_line if node.name == :trap
super
end
end

it 'does not register a signal handler in any file under lib/' do
lib_dir = File.expand_path('../../lib', __dir__)
offenders = Dir.glob('**/*.rb', base: lib_dir).flat_map do |relative_path|
finder = trap_call_finder.new
Prism.parse_file(File.join(lib_dir, relative_path)).value.accept(finder)
finder.lines.map { |line| "#{relative_path}:#{line}" }
end

expect(offenders).to be_empty, "signal handlers registered at: #{offenders.join(', ')}"
end
end