#!/bin/bash # # This file is managed by salt, using the unicorn formula template. # Editing this file by hand is highly discouraged! # exec 2>&1 # # Since unicorn creates a new pid on restart/reload, it needs a little extra # love to manage with runit. Instead of managing unicorn directly, we simply # trap signal calls to the service and redirect them to unicorn directly. # RUNIT_PID=$$ APPLICATION_NAME={{ unicorn_application }} APPLICATION_PATH=/var/www/{{ unicorn_application }}/current UNICORN_CMD={{ unicorn_command }} CUR_PID_FILE=/var/www/{{ unicorn_application }}/shared/pids/unicorn.pid OLD_PID_FILE=$CUR_PID_FILE.oldbin echo "Runit service restarted (PID: $RUNIT_PID)" function is_unicorn_alive { set +e if [ -n $1 ] && kill -0 $1 >/dev/null 2>&1; then echo "yes" fi set -e } if [ -e $OLD_PID_FILE ]; then OLD_PID=$(cat $OLD_PID_FILE) echo "Old master detected (PID: $OLD_PID), waiting for it to quit" while [ -n "$(is_unicorn_alive $OLD_PID)" ]; do sleep 5 done fi if [ -e $CUR_PID_FILE ]; then CUR_PID=$(cat $CUR_PID_FILE) if [ -n "$(is_unicorn_alive $CUR_PID)" ]; then echo "Detected running Unicorn instance (PID: $CUR_PID)" RUNNING=true fi fi function start { unset ACTION if [ $RUNNING ]; then restart else echo 'Starting new unicorn instance' RUNASUID=$(getent passwd {{ user }} | cut -d: -f3) RUNASGROUPS=$(id -G {{ group }} | tr ' ' ':') ulimit -n 65535 export HOME={{ home }} export PATH={{ virtualenv_home }}/.virtualenvs/{{ unicorn_application }}/bin:$PATH source {{ virtualenv_home }}/.virtualenvs/{{ unicorn_application }}/bin/activate cd $APPLICATION_PATH exec chpst -u :$RUNASUID:$RUNASGROUPS $UNICORN_CMD -c /var/www/{{ unicorn_application }}/current/config/gunicorn.py wsgi:app sleep 3 CUR_PID=$(cat $CUR_PID_FILE) fi } function stop { unset ACTION echo 'Initializing graceful shutdown' kill -QUIT $CUR_PID while [ -n "$(is_unicorn_alive $CUR_PID)" ]; do echo '.' sleep 2 done echo 'Unicorn stopped, exiting Runit process' kill -9 $RUNIT_PID } function restart { unset ACTION echo "Restart request captured, swapping old master (PID: $CUR_PID) for new master with USR2" kill -USR2 $CUR_PID sleep 2 echo 'Restarting Runit service to capture new master PID' exit } function alarm { unset ACTION echo 'Unicorn process interrupted' } trap 'ACTION=stop' STOP TERM KILL trap 'ACTION=restart' QUIT USR2 INT trap 'ACTION=alarm' ALRM [ $RUNNING ] || ACTION=start if [ $ACTION ]; then echo "Performing \"$ACTION\" action and going into sleep mode until new signal captured" elif [ $RUNNING ]; then echo "Going into sleep mode until new signal captured" fi if [ $ACTION ] || [ $RUNNING ]; then while true; do [ "$ACTION" == 'start' ] && start [ "$ACTION" == 'stop' ] && stop [ "$ACTION" == 'restart' ] && restart [ "$ACTION" == 'alarm' ] && alarm sleep 2 done fi