Skip to content

Instantly share code, notes, and snippets.

@Sutto
Created February 15, 2011 12:07
Show Gist options
  • Save Sutto/827438 to your computer and use it in GitHub Desktop.
Save Sutto/827438 to your computer and use it in GitHub Desktop.
#!/bin/bash
### BEGIN INIT INFO
# Provides: unicorn
# Required-Start: $local_fs $remote_fs $network $syslog nginx
# Required-Stop: $local_fs $remote_fs $network $syslog nginx
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts unicorn
# Description: starts unicorn web app servers
### END INIT INFO
signal_app() {
[[ -s "/opt/$2/$3/current/tmp/pids/unicorn.pid" ]] && kill -$1 `cat "/opt/$2/$3/current/tmp/pids/unicorn.pid"`
}
stop_app() {
signal_app "QUIT" "$1" "$2"
}
start_app() {
mkdir -p /var/run/unicorn
chmod 777 /var/run/unicorn
local app_root="/opt/$1/$2/current"
if [[ -d "$app_root" ]]; then
local inner_command="cd \"$app_root\" && bundle exec unicorn_rails -D -E $2 -c \"$app_root/config/unicorn.rb\""
nohup sudo -H -u "$1" -i "rvm-shell ree@$1 -c '$inner_command'" >/dev/null 2>&1 &
fi
}
restart_app() {
signal_app "USR2" "$1" "$2"
}
action_for_env() {
"${1}_app" "$2" "$3"
}
default_app_names() {
if [[ -f "/etc/unicorn.default" ]]; then
cat "/etc/unicorn.default"
fi
}
envs_for_app() {
local action="$1"; shift
local app_name="$1"; shift
if [[ "$#" -gt 0 ]]; then
for env in "$@"; do
action_for_env "$action" "$app_name" "$env"
done
else
if [[ -d "/opt/$app_name" ]]; then
for dir in $(\ls "/opt/$app_name"); do
if [[ -L "/opt/$app_name/$dir/current" && -s "/opt/$app_name/$dir/current/config/unicorn.rb" ]]; then
action_for_env "$action" "$app_name" "$dir"
fi
done
fi
fi
}
for_apps() {
local action="$1"; shift
users="${1:-"$(default_app_names)"}"; shift
for user in $users; do
envs_for_app "$action" "$user" "$@"
done
}
usage() {
echo 'Usage: /etc/init.d/unicorn {start,stop,restart} [app] [env]' >&2
exit 1
}
action="$1"; shift
case "$action" in
start|stop|restart) for_apps "$action" "$@" ;;
*) usage ;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment