Rails initializer (using JRuby, Puma) at_exit is occasionally not executed

Viewed 282

I'm trying to make a little library that wraps over march_hare and is used as part of our Rails app. It needs to connect on app startup and disconnect on shutdown.

I'am aiming to something similar to the ruby-kafka Rails integration via initializer:

  • configure my service
  • run it
  • specify shutdown procedure

The problem is my at_exit blocks are sometimes not executed. What may be the cause of this issue? Is there a way to fix it and ensure my at_exit blocks are called?

Investigating the issue, I created a blank demo app with the following initializer:

class SomeClass
  def self.shutdown(reason)
    msg = "#{Time.now} SHUTDOWN via #{reason}!"

    puts msg
    open('log/development.log', 'a') do |f|
      f.puts msg
    end
  end
end

at_exit { SomeClass.shutdown(:at_exit1) }
at_exit { SomeClass.shutdown(:at_exit2) }
at_exit { SomeClass.shutdown(:at_exit3) }

puts "#{Time.now} INITIALIZED!"

In 9 out of 10 run + terminate cycles I get:

$ rails s
=> Booting Puma
=> Rails 4.2.7.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
2017-05-22 15:29:16 +0300 INITIALIZED!
Puma starting in single mode...
* Version 3.4.0 (jruby 9.1.2.0 - ruby 2.3.0), codename: Owl Bowl Brawl
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
^C- Gracefully stopping, waiting for requests to finish
Exiting
=== puma shutdown: 2017-05-22 15:29:30 +0300 ===
- Goodbye!
2017-05-22 15:29:30 +0300 SHUTDOWN via at_exit3!
2017-05-22 15:29:30 +0300 SHUTDOWN via at_exit2!
2017-05-22 15:29:30 +0300 SHUTDOWN via at_exit1!

But once in a while the result is:

$ rails s
=> Booting Puma
=> Rails 4.2.7.1 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
2017-05-22 15:29:45 +0300 INITIALIZED!
Puma starting in single mode...
* Version 3.4.0 (jruby 9.1.2.0 - ruby 2.3.0), codename: Owl Bowl Brawl
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
^C- Gracefully stopping, waiting for requests to finish
Exiting
=== puma shutdown: 2017-05-22 15:30:17 +0300 ===
- Goodbye!
2017-05-22 15:30:17 +0300 SHUTDOWN via at_exit2!
2017-05-22 15:30:17 +0300 SHUTDOWN via at_exit1!
  • My Gemfile has only gem 'puma' added.
  • Ruby version: jruby 9.1.2.0
  • Rails version: Rails 4.2.7.1
  • System Version: macOS 10.12.4
1 Answers
Related