traday
traday

Reputation: 1151

Gracefully terminate Rails Application from within

I have a Rails 5 application (API) and a postgres DB that run on separate docker containers, all on the same AWS EC2 instance, and are controlled by an external manager (manage). manage needs to be able to make a request to the API and tell it to exit. I don't want to just kill the API externally or the docker container, as I want all API requests to complete. I want the API to exit gracefully and only it knows how to do that.
Ruby has exit, exit! and abort. All of them seem to be handled by Rails as exceptions and Rails just continues motoring on.

How can I terminate my rails application from within? Is there some sort of unhandleable exception that I can raise?

Upvotes: 3

Views: 1298

Answers (1)

stuartpalmer
stuartpalmer

Reputation: 156

Most likely the ApplicationController is rescuing the SystemExit. Looking at the Rails source, there is a rescue Exception in ActionController, which includes ActiveSupport::Rescuable. That's where the controller methods like rescue_from are defined.

I tested this in a controller in a Rails API app, sent it a request, and Rails did indeed exit immediately, with an empty response to the caller:

class ProcessesController < ApplicationController
  rescue_from SystemExit, with: :my_exit

  def destroy
    CleanupClass.method_that_exits
    render json: { status: :ok }
  end

  def my_exit
    exit!
  end
end

class CleanupClass
  def self.method_that_exits
    exit
  end
end

Upvotes: 2

Related Questions