A while ago I wrote a pilot project for a real-time twitter analysis tool using eventmachine and websockets. It worked perfectly, but there were questions how to deploy it to production. Specifically, how to handle process management, logging, configuration, deployment, and monitoring. This post describes how I handled process management.
Process management is a facility to support starting and stopping of long running processes as well as inquire if a process is running. Generally, only one instance of the process should be running, so support for checking for a running process is needed.
Starting and stopping the process can easily be handled by the Daemons Gem. From their webpage: “Daemons provides an easy way to wrap existing ruby scripts (for example a self-written server) to be run as a daemon and to be controlled by simple start/stop/restart commands.”
In the code example below, we wrap our websocket.rb file located in the ./lib/websockets directory.
#!/usr/bin/env ruby
APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__) + '/..'))
APP_ENV = ENV["APP_ENV"] || "development"
$LOAD_PATH.unshift(APP_ROOT + '/lib') unless $LOAD_PATH.include?(APP_ROOT + '/lib')
require 'rubygems'
require 'daemons'
require 'websockets'
def stop_and_exit
# Do something useful here....
exit 0
end
Signal.trap('INT') { stop_and_exit }
Signal.trap('TERM'){ stop_and_exit }
options = {
:app_name => 'Websocket',
:multiple => false,
:log_output => true,
:dir_mode => :normal,
:dir => File.join(APP_ROOT, 'log')
}
Daemons.run(File.join(APP_ROOT, 'lib', 'websockets', 'websocket.rb'), options)
Running ./websocket -h yields:
websocket -h
Usage: Websocket <command> <options> -- <application options>
* where <command> is one of:
start start an instance of the application
stop stop all instances of the application
restart stop all instances and restart them afterwards
reload send a SIGHUP to all instances of the application
run start the application and stay on top
zap set the application to a stopped state
status show status (PID) of application instances
* and where <options> may contain several of the following:
-t, --ontop Stay on top (does not daemonize)
-f, --force Force operation
-n, --no_wait Do not wait for processes to stop
Common options:
-h, --help Show this message
--version Show version
References