Skip to content

Instantly share code, notes, and snippets.

@fabrikagency
Created April 24, 2013 16:26
Show Gist options
  • Save fabrikagency/5453473 to your computer and use it in GitHub Desktop.
Save fabrikagency/5453473 to your computer and use it in GitHub Desktop.
Rackbox runit script for unicorn
#!/bin/bash --login
#
# Supervises unicorn; stopping this service prompts a graceful shutdown of the
# current unicorn instance. Sending HUP to this service causes unicorn to re-exec
# itself for upgrades etc.
#
function is_pid_running() {
set +e
if [ -n $1 ] && kill -0 $1 >/dev/null 2>&1; then
echo "yes"
fi
set -e
}
echo "My pid: $$"
APP_DIR=<%= @options[:working_directory] %>
CUR_PID_FILE=$APP_DIR/../shared/pids/unicorn.pid
OLD_PID_FILE=$CUR_PID_FILE.oldbin
if [ -e $OLD_PID_FILE ]; then
OLD_PID=$(cat $OLD_PID_FILE)
echo "Unicorn appears to be restarting: waiting for old master ($OLD_PID) to exit"
while [ -n "$(is_pid_running $OLD_PID)" ]; do
/bin/echo -n '.'
sleep 2
done
fi
if [ -e $CUR_PID_FILE ]; then
CUR_PID=$(cat $CUR_PID_FILE)
if [ -n "$(is_pid_running $CUR_PID)" ]; then
echo "Already running as $CUR_PID"
RUNNING=true
fi
fi
if [ ! $RUNNING ]; then
echo "Starting unicorn"
exec 2>&1
exec <%= File.join(@options[:working_directory], 'bin', (@options[:smells_like_rack] ? 'unicorn' : 'unicorn_rails')) %> -E <%= @options[:rack_env] %> -c <%= @options[:unicorn_config_file] %>
sleep 2
CUR_PID=$(cat $CUR_PID_FILE)
fi
function restart() {
# TODO: regenerate config if this file has changed
# Tell unicorn to re-exec itself
echo "Asking unicorn to re-exec itself with USR2"
kill -USR2 $CUR_PID
# Wait and then exit -- after runit restarts the script, we'll
# wait for the re-exec'd process
sleep 2
echo "Restarting to supervise new unicorn"
exit
}
function graceful_shutdown() {
echo "Requesting graceful shutdown"
kill -QUIT $CUR_PID
}
trap restart HUP QUIT
trap graceful_shutdown INT TERM
echo "Watching for unicorn ($CUR_PID) exiting"
while [ -n "$(is_pid_running $CUR_PID)" ]; do
/bin/echo -n '.'
sleep 2
done
echo "Unicorn has exited."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment