#!/usr/local/bin/ruby require 'etc' require 'digest/md5' ROOT_PATH="<%= @deploy[:deploy_to] %>" APP_NAME="<%= @application %>" PID_PATH="<%= @deploy[:deploy_to] %>/shared/pids/unicorn.pid" def run_and_print_command(command) puts command system(command) || exit(1) end def run_and_ignore_exitcode_and_print_command(command) puts command system(command) end def unicorn_running? if File.exists?(PID_PATH) && (pid = File.read(PID_PATH).chomp) && system("ps aux | grep #{pid} | grep -v grep > /dev/null") pid else false end end def different_gemfile? if File.exists?("#{ROOT_PATH}/current/Gemfile") dir = Dir["#{ROOT_PATH}/releases/*"] previous_release_path = dir.sort[dir.size-2] if !previous_release_path.nil? && File.exists?("#{previous_release_path}/Gemfile") return Digest::MD5.hexdigest(File.read("#{ROOT_PATH}/current/Gemfile")) != Digest::MD5.hexdigest(File.read("#{previous_release_path}/Gemfile")) end end false end def start_unicorn if File.exists?("#{ROOT_PATH}/current/Gemfile") puts "OpsWorks: Gemfile detected - running Unicorn with bundle exec" run_and_ignore_exitcode_and_print_command "cd #{ROOT_PATH}/current && /usr/local/bin/bundle exec unicorn_rails --env <%= @deploy[:rails_env] %> --daemonize -c #{ROOT_PATH}/shared/config/unicorn.conf" else puts "OpsWorks: no Gemfile detected - running plain Unicorn" run_and_ignore_exitcode_and_print_command "cd #{ROOT_PATH}/current && unicorn_rails --env <%= @deploy[:rails_env] %> --daemonize -c #{ROOT_PATH}/shared/config/unicorn.conf" end end def stop_unicorn if unicorn_running? if run_and_ignore_exitcode_and_print_command "kill -QUIT `cat #{PID_PATH}`" `rm #{PID_PATH}` end else puts "You can't stop unicorn, because it's not running" end end def restart_unicorn if unicorn_running? run_and_ignore_exitcode_and_print_command "kill -USR2 `cat #{PID_PATH}`" else start_unicorn end end def clean_restart if different_gemfile? puts "Found a previous version with a different Gemfile: Doing a stop & start" stop_unicorn if unicorn_running? start_unicorn else puts "No previous version with a different Gemfile found. Assuming a quick restart without re-loading gems is save" restart_unicorn end end def status_unicorn if pid = unicorn_running? puts "Unicorn <%= @application %> running with PID #{pid}" return true else puts "Unicorn <%= @application %> not running" return false end end Process::Sys.setuid(uid = Etc.getpwnam("<%= @deploy[:user] %>").uid) puts "Set Unicorn process UID to #{uid}" case ARGV[0] when "start" puts "Starting Unicorn #{APP_NAME}" start_unicorn when "stop" puts "Stopping Unicorn #{APP_NAME}" stop_unicorn when "status" status_unicorn when "restart" restart_unicorn when "clean-restart" clean_restart else puts "Usage: {start|stop|status|restart|clean-restart}" exit 1 end exit 0