Skip to content

Instantly share code, notes, and snippets.

@wangsy
Last active December 29, 2015 09:39
Show Gist options
  • Save wangsy/7652003 to your computer and use it in GitHub Desktop.
Save wangsy/7652003 to your computer and use it in GitHub Desktop.
unicorn_rails startup script /etc/init.d/unicorn_rails rvm user install version
#!/bin/bash
### BEGIN INIT INFO
# Provides: unicorn_rails
# Required-Start: $all
# Required-Stop: $network $local_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start unicorn rails at boot
# Description: Enable unicorn_rails at boot time.
### END INIT INFO
#
# Use this as a basis for your own Unicorn init script.
# Change APPLICATION to match your app.
# Make sure that all paths are correct.
#set -u
set -e
sig () {
test -s "$PID" && kill -$1 `cat "$PID"`
}
oldsig () {
test -s "$OLD_PID" && kill -$1 `cat "$OLD_PID"`
}
cmd () {
case $1 in
start)
sig 0 && echo >&2 "Already running" && exit 0
echo "Starting"
su - $USER -c "$CMD"
;;
stop)
sig QUIT && echo "Stopping" && exit 0
echo >&2 "Not running"
;;
force-stop)
sig TERM && echo "Forcing a stop" && exit 0
echo >&2 "Not running"
;;
restart|reload)
sig USR2 && sleep 5 && oldsig QUIT && echo "Killing old master" `cat $OLD_PID` && exit 0
echo >&2 "Couldn't reload, starting '$CMD' instead"
$CMD
;;
upgrade)
sig USR2 && echo Upgraded && exit 0
echo >&2 "Couldn't upgrade, starting '$CMD' instead"
$CMD
;;
rotate)
sig USR1 && echo rotated logs OK && exit 0
echo >&2 "Couldn't rotate logs" && exit 1
;;
*)
echo >&2 "Usage: $0 <start|stop|restart|upgrade|rotate|force-stop>"
exit 1
;;
esac
}
setup () {
echo -n "$RAILS_ROOT: "
cd $RAILS_ROOT || exit 1
export PID=$RAILS_ROOT/tmp/pids/unicorn.pid
export OLD_PID="$PID.oldbin"
export USER="rails"
UNICORN_OPTS="-E $RAILS_ENV -c $RAILS_ROOT/config/unicorn/$RAILS_ENV.rb -D"
GEM_HOME="/home/$USER/.rvm/gems/$RUBY_VERSION"
SET_PATH="cd $RAILS_ROOT; rvm use $RUBY_VERSION; export GEM_HOME=$GEM_HOME"
CMD="$SET_PATH; $GEM_HOME/bin/unicorn $UNICORN_OPTS"
}
start_stop () {
# either run the start/stop/reload/etc command for every config under /etc/unicorn
# or just do it for a specific one
# $1 contains the start/stop/etc command
# $2 if it exists, should be the specific config we want to act on
if [ $2 ]; then
. $2
setup
cmd $1
else
for CONFIG in /etc/unicorn_rails/*.conf; do
# import the variables
. $CONFIG
setup
# run the start/stop/etc command
cmd $1
done
fi
}
ARGS="$1 $2"
start_stop $ARGS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment