Q:

Right way of stopping a Ruby service

I am using AirBnb Nerve service. It's service code looks like this:

require 'logger'
require 'json'
require 'timeout'

require 'nerve/version'
require 'nerve/utils'
require 'nerve/log'
require 'nerve/ring_buffer'
require 'nerve/reporter'
require 'nerve/service_watcher'

module Nerve
  class Nerve

    include Logging

    def initialize(opts={})
      log.info 'nerve: starting up!'

      # set global variable for exit signal
      $EXIT = false

      ...some code...

      # Any exceptions in the watcher threads should wake the main thread so
      # that we can fail fast.
      Thread.abort_on_exception = true

      log.debug 'nerve: completed init'
    end

    def run
      log.info 'nerve: starting run'

      @services.each do |name, config|
        launch_watcher(name, config)
      end

      begin
        sleep
      rescue StandardError => e
        log.error "nerve: encountered unexpected exception #{e.inspect} in main thread"
        raise e
      ensure
        $EXIT = true
        log.warn 'nerve: reaping all watchers'
        @watchers.each do |name, watcher_thread|
          reap_watcher(name)
        end
      end

      log.info 'nerve: exiting'
    ensure
      $EXIT = true
    end

    def launch_watcher(name, config)
... some code ...
    end

    def reap_watcher(name)
... some code ...
    end
  end
end

I do not see any stop method. What is the right way of stopping such a service? I am using JRuby and intend to write a JSVC adapter for this service.

A:

There is no way to do this via the current API, short of sending it a signal.
If sending a signal isn't going to work and you want to handle stop explicitly, it looks like you will need to change the following things:

Add a #stop method to Nerve that sets $EXIT = true.
Modify #run so that rather than sleeping forever (sleep) it wakes up and checks $EXIT.

