Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Forked from ethier/gist:7190310
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahemoff/9401523 to your computer and use it in GitHub Desktop.
Save mahemoff/9401523 to your computer and use it in GitHub Desktop.
Update the upgrade function - it captures the old PID before it's overwritten by the upgrade (ie USR2 signal), then kills it once the upgrade has succeeded
#!/bin/sh
# forked from https://gist.github.com/ethier/7190310
# via http://uncorruptedstate.com/blog/2013/10/27/zero-downtime-deployment-with-rails-and-unicorn/
### Unicorn variables ###
TIMEOUT=${TIMEOUT-60}
APP_ROOT=/home/web/current
UNICORN=$APP_ROOT/bin/unicorn
TMP_PATH=$APP_ROOT/tmp
PID_PATH=$APP_ROOT/tmp/pids
PID=$PID_PATH/unicorn.pid
OLD_PID=$PID_PATH/unicorn.old.pid
RAILS_ENV=staging
USER=web
GROUP=pass
# See http://technology.customink.com/blog/2012/03/16/simple-garbage-collection-tuning-for-rails/
export RUBY_GC_MALLOC_LIMIT=60000000
export RUBY_GC_HEAP_INIT_SLOTS=1800000 # Slots Live + 20%
export RUBY_GC_HEAP_FREE_SLOTS=18000 # 1% of HEAP_MIN_SLOTS
export RUBY_HEAP_SLOTS_INCREMENT=144000 # 8% of HEAP_MIN_SLOTS
export RUBY_HEAP_SLOTS_GROWTH_FACTOR=1
export LD_PRELOAD=/usr/lib/libtcmalloc_minimal.so.0.1.0
CMD="$UNICORN -D -E $RAILS_ENV -c $APP_ROOT/config/unicorn.rb"
INIT_CONF=$APP_ROOT/config/unicorn.conf
action="$1"
set -u
test -f "$INIT_CONF" && . $INIT_CONF
cd $APP_ROOT || exit 1
sig () {
test -s "$PID" && kill -$1 `cat $PID`
}
oldsig () {
test -s $OLD_PID && kill -$1 `cat $OLD_PID`
}
workersig () {
workerpid=$PID_PATH/worker.$2.pid
test -s "$workerpid" && kill -$1 `cat $workerpid`
}
create_tmp_path () {
test -d $TMP_PATH || ( mkdir -p $TMP_PATH && chown $USER $TMP_PATH )
}
create_pid_path () {
test -d $PID_PATH || ( mkdir -p $PID_PATH && chown $USER $PID_PATH )
}
archive_pid () {
rm -f $OLD_PID
cp $PID $OLD_PID
}
case $action in
start)
create_tmp_path
create_pid_path
sig 0 && echo >&2 "Already running" && exit 0
$CMD
;;
stop)
sig QUIT && exit 0
echo >&2 "Not running"
;;
force-stop)
sig TERM && exit 0
echo >&2 "Not running"
;;
restart|reload)
sig HUP && echo reloaded OK && exit 0
echo >&2 "Couldn't reload, starting '$CMD' instead"
$CMD
;;
upgrade)
create_tmp_path
create_pid_path
archive_pid && sig USR2 && oldsig QUIT && exit 0
echo >&2 "Couldn't upgrade, starting '$CMD' instead"
$CMD
;;
status)
sig 0 && echo "running with pid `cat $PID`" && exit 0
echo stopped && exit 1
;;
kill_worker)
workersig QUIT $2 && exit 0
echo >&2 "Worker not running"
;;
reopen-logs)
sig USR1
;;
*)
echo >&2 "Usage: $0 <start|stop|status|restart|upgrade|status|force-stop|reopen-logs|kill_worker>"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment