Skip to main content

Mongrel init.d script

I’ve slightly modified Bojan Mihelac’s Mongrel init.d script to cope with the situation where there are stale PID files left from a server failure.

#!/bin/env ruby
#
# mongrel Startup script for Mongrel by Tim Morgan, modified by bmihelac and Nick Ludlam
# Originally from http://source.mihelac.org/2007/3/27/customized-mongrel-startup-script
#
# chkconfig: 2345 85 15
# description: mongrel manages Mongrel
#

apps = [
  {:app => 'app1'},
  {:app => 'app2'},
  {:app => 'app3'}
]

default_port = 8000
default_options = {
  :app_dir => '/var/www',  :environment => 'production'
}

pid_location = "log/mongrel.pid"

if ['stop', 'restart'].include? ARGV.first
  apps.each do |app|
    options = default_options.merge(app)
    path = File.join options[:app_dir], options[:app], "current"
    puts "Stopping #{path}..."
    `/usr/local/bin/mongrel_rails stop -c #{path} -P #{pid_location}`
  end
end

if ['start', 'restart'].include? ARGV.first
  apps.each do |app|
    options = default_options.merge(app)
    path = File.join options[:app_dir], options[:app], "current"
    port = options[:port] || default_port
    pid_file = File.join path, pid_location

    # Check and remove stale PID file. Platform needs "ps -p" support
    if File.exists?(pid_file)
      old_pid = File.read(pid_file)
      `ps -p #{old_pid}`
      if old_pid.to_i > 0 && $?.exitstatus == 1
        puts "Removing stale PID file"
        File.unlink(pid_file)
      end
    end

    puts "Starting #{options[:app]} on #{port}..."
    `/usr/local/bin/mongrel_rails start -d -p #{port} -e #{options[:environment]} -c #{path} -P log/mongrel.pid`
    default_port = port + 1

  end
end

unless ['start', 'stop', 'restart'].include? ARGV.first
    puts "Usage: mongrel {start|stop|restart}"
    exit
end