Detect if application was started as HTTP server or not (rake task, rconsole etc)

前端 未结 6 1908
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 19:47

I\'m using EventMachine and Monetarily to start e TCP server along with my rails application. This is started from config/initializers/momentarily.rb.

相关标签:
6条回答
  • 2020-12-09 20:12
    unless File.basename($0) == "rake" && ARGV.include?("db:migrate")
      # you are not in rake db:migrate
    end
    
    0 讨论(0)
  • 2020-12-09 20:18

    Set an environment variable in config.ru file, and use it anywhere in the code to detect if it's executed using a rails server command only.

    For e.g.

    • File: config.ru

      ENV['server_mode'] = '1'
      

    And using it somewhere as:

    • File: config/environment.rb

      Thread.new { infinite_loop! }.join if ENV['server_mode'] = '1'
      

    Reference: Answer

    0 讨论(0)
  • 2020-12-09 20:18

    After your application launches, you could have it shell out to check ps. If ps shows that the HTTP server is running and the running HTTP server has the same pid as your application (check the pid by inspecting $$), then you could launch the TCP server.

    0 讨论(0)
  • 2020-12-09 20:24

    There's not a great way of doing this that I know of. You could copy newrelic's approach (check discover_dispatcher in local_environment.rb) which basically has a list of heuristics used to detect if it is running inside passenger, thin, etc.

    For passenger it checks

    defined?(::PhusionPassenger)
    

    for thin it checks

    if defined?(::Thin) && defined?(::Thin::Server)
    
    0 讨论(0)
  • 2020-12-09 20:28

    Maybe you can implement a switch in the initializer based on ARGV?

    Something like:

    if ARGV.join(' ').match /something/
      # your initializer code here
    end
    
    0 讨论(0)
  • 2020-12-09 20:37

    Don't start that other server from an initializer. Create a daemon in script/momentarily and start it from within your app.

    0 讨论(0)
提交回复
热议问题