1 # Copyright (c) 2005 Zed A. Shaw
2 # You can redistribute it and/or modify it under the same terms as Ruby.
4 # Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
5 # for more information.
12 require 'rails/mongrel_server/handler'
16 def self.send_signal(signal
, pid_file
)
17 pid
= open(pid_file
).read
.to_i
18 print
"Sending #{signal} to Mongrel at PID #{pid}..."
20 Process
.kill(signal
, pid
)
22 puts
"Process does not exist. Not running."
28 class RailsConfigurator
< Mongrel
::Configurator
32 if defaults
[:mime_map]
33 Mongrel
.log("Loading additional MIME types from #{defaults[:mime_map]}")
34 mime
= load_mime_map(defaults
[:mime_map], mime
)
37 mime
.each
{|k
,v
| Mongrel
::DirHandler::add_mime_type(k
,v
) }
40 def mount_rails(prefix
)
41 ENV['RAILS_ENV'] = defaults
[:environment]
42 ::RAILS_ENV.replace(defaults
[:environment]) if defined?(::RAILS_ENV)
44 env_location
= "#{defaults[:cwd]}/config/environment"
47 ActionController
::Base.relative_url_root
= defaults
[:prefix]
48 uri prefix
, :handler => Rails
::MongrelServer::RailsHandler.new
52 class Start
< GemPlugin
::Plugin "/commands"
53 include Mongrel
::Command::Base
57 ["-e", "--environment ENV", "Rails environment to run as", :@environment, ENV['RAILS_ENV'] || "development"],
58 ["-d", "--daemonize", "Run daemonized in the background", :@daemon, false],
59 ['-p', '--port PORT', "Which port to bind to", :@port, 3000],
60 ['-a', '--address ADDR', "Address to bind to", :@address, "0.0.0.0"],
61 ['-l', '--log FILE', "Where to write log messages", :@log_file, "log/mongrel.log"],
62 ['-P', '--pid FILE', "Where to write the PID", :@pid_file, "tmp/pids/mongrel.pid"],
63 ['-n', '--num-procs INT', "Number of processors active before clients denied", :@num_procs, 1024],
64 ['-o', '--timeout TIME', "Time to wait (in seconds) before killing a stalled thread", :@timeout, 60],
65 ['-t', '--throttle TIME', "Time to pause (in hundredths of a second) between accepting clients", :@throttle, 0],
66 ['-m', '--mime PATH', "A YAML file that lists additional MIME types", :@mime_map, nil],
67 ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, RAILS_ROOT
],
68 ['-r', '--root PATH', "Set the document root (default 'public')", :@docroot, "public"],
69 ['-B', '--debug', "Enable debugging mode", :@debug, false],
70 ['-C', '--config PATH', "Use a config file", :@config_file, nil],
71 ['-S', '--script PATH', "Load the given file as an extra config script", :@config_script, nil],
72 ['-G', '--generate PATH', "Generate a config file for use with -C", :@generate, nil],
73 ['', '--user USER', "User to run as", :@user, nil],
74 ['', '--group GROUP', "Group to run as", :@group, nil],
75 ['', '--prefix PATH', "URL prefix for Rails app", :@prefix, nil],
77 ['-b', '--binding ADDR', "Address to bind to (deprecated, use -a)", :@address, "0.0.0.0"],
78 ['-u', '--debugger', "Enable debugging mode (deprecated, use -B)", :@debug, false]
84 valid_exists
?(@config_file, "Config file not there: #@config_file")
85 return false unless @valid
86 @config_file = File
.expand_path(@config_file)
88 return false unless @valid
91 @cwd = File
.expand_path(@cwd)
92 valid_dir
? @cwd, "Invalid path to change to during daemon mode: #@cwd"
94 # Change there to start, then we'll have to come back after daemonize
97 valid
?(@prefix[0] == ?/ && @prefix[-1] != ?/, "Prefix must begin with / and not end in /") if @prefix
98 valid_dir
? File
.dirname(@log_file), "Path to log file not valid: #@log_file"
99 valid_dir
? File
.dirname(@pid_file), "Path to pid file not valid: #@pid_file"
100 valid_dir
? @docroot, "Path to docroot not valid: #@docroot"
101 valid_exists
? @mime_map, "MIME mapping file does not exist: #@mime_map" if @mime_map
102 valid_exists
? @config_file, "Config file not there: #@config_file" if @config_file
103 valid_dir
? File
.dirname(@generate), "Problem accessing directory to #@generate" if @generate
104 valid_user
? @user if @user
105 valid_group
? @group if @group
112 @generate = File
.expand_path(@generate)
113 Mongrel
.log(:error, "** Writing config to \"#@generate\".")
114 open(@generate, "w") {|f
| f
.write(settings
.to_yaml
) }
115 Mongrel
.log(:error, "** Finished. Run \"mongrel_rails start -C #@generate\" to use the config file.")
119 config
= RailsConfigurator
.new(settings
) do
120 defaults
[:log] = $stdout if defaults
[:environment] == 'development'
122 Mongrel
.log("=> Rails #{Rails.version} application starting on http://#{defaults[:host]}:#{defaults[:port]}")
124 unless defaults
[:daemon]
125 Mongrel
.log("=> Call with -d to detach")
126 Mongrel
.log("=> Ctrl-C to shutdown server")
127 start_debugger
if defaults
[:debug]
131 if File
.exist
? defaults
[:pid_file]
132 Mongrel
.log(:error, "!!! PID file #{defaults[:pid_file]} already exists. Mongrel could be running already. Check your #{defaults[:log_file]} for errors.")
133 Mongrel
.log(:error, "!!! Exiting with error. You must stop mongrel and clear the .pid before I'll attempt a start.")
139 Mongrel
.log("Daemonized, any open files are closed. Look at #{defaults[:pid_file]} and #{defaults[:log_file]} for info.")
140 Mongrel
.log("Settings loaded from #{@config_file} (they override command line).") if @config_file
143 Mongrel
.log("Starting Mongrel listening at #{defaults[:host]}:#{defaults[:port]}, further information can be found in log/mongrel-#{defaults[:host]}-#{defaults[:port]}.log")
146 prefix
= defaults
[:prefix] || '/'
149 Mongrel
.log("Installing debugging prefixed filters. Look in log/mongrel_debug for the files.")
154 dir_handler
= Mongrel
::DirHandler.new(defaults
[:docroot], false)
155 dir_handler
.passthrough_missing_files
= true
157 unless defaults
[:environment] == 'production'
158 Mongrel
.log("Mounting DirHandler at #{prefix}...")
159 uri prefix
, :handler => dir_handler
163 Mongrel
.log("Starting Rails with #{defaults[:environment]} environment...")
164 Mongrel
.log("Mounting Rails at #{prefix}...")
166 Mongrel
.log("Rails loaded.")
169 Mongrel
.log("Loading any Rails specific GemPlugins" )
172 if defaults
[:config_script]
173 Mongrel
.log("Loading #{defaults[:config_script]} external config script")
174 run_config(defaults
[:config_script])
182 Mongrel
.log("Mongrel #{Mongrel::Const::MONGREL_VERSION} available at #{@address}:#{@port}")
184 if config
.defaults
[:daemon]
185 config
.write_pid_file
187 Mongrel
.log("Use CTRL-C to stop.")
188 tail
"log/#{config.defaults[:environment]}.log"
193 if config
.needs_restart
194 unless RUBY_PLATFORM =~
/djgpp|(cyg|ms|bcc)win|mingw/
195 cmd
= "ruby #{__FILE__} start #{original_args.join(' ')}"
196 Mongrel
.log("Restarting with arguments: #{cmd}")
197 config
.stop(false, true)
198 config
.remove_pid_file
200 if config
.defaults
[:daemon]
203 Mongrel
.log(:error, "Can't restart unless in daemon mode.")
207 Mongrel
.log("Win32 does not support restarts. Exiting.")
215 settings
= YAML
.load_file(@config_file)
217 Mongrel
.log(:error, "** Loading settings from #{@config_file} (they override command line).") unless @daemon || settings
[:daemon]
220 settings
[:includes] ||= ["mongrel"]
222 # Config file settings will override command line settings
223 settings
.each
do |key
, value
|
225 if config_keys
.include?(key
)
226 key
= 'address' if key
== 'host'
227 self.instance_variable_set("@#{key}", value
)
229 failure
"Unknown configuration setting: #{key}"
237 %w(address host port cwd log_file pid_file environment docroot mime_map daemon debug includes config_script num_processors timeout throttle user group prefix
)
241 config_keys
.inject({}) do |hash
, key
|
242 value
= self.instance_variable_get("@#{key}")
243 key
= 'host' if key
== 'address'
244 hash
[key
.to_sym
] ||= value
250 require_library_or_gem
'ruby-debug'
252 Debugger
.settings
[:autoeval] = true if Debugger
.respond_to
?(:settings)
253 Mongrel
.log("=> Debugger enabled")
255 Mongrel
.log(:error, "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'")
260 cursor
= File
.size(log_file
)
261 last_checked
= Time
.now
262 tail_thread
= Thread
.new
do
263 File
.open(log_file
, 'r') do |f
|
266 if f
.mtime
> last_checked
267 last_checked
= f
.mtime
269 cursor
+= contents
.length
280 class Stop
< GemPlugin
::Plugin "/commands"
281 include Mongrel
::Command::Base
285 ['-c', '--chdir PATH', "Change to dir before starting (will be expanded).", :@cwd, "."],
286 ['-f', '--force', "Force the shutdown (kill -9).", :@force, false],
287 ['-w', '--wait SECONDS', "Wait SECONDS before forcing shutdown", :@wait, "0"],
288 ['-P', '--pid FILE', "Where the PID file is located.", :@pid_file, "log/mongrel.pid"]
293 @cwd = File
.expand_path(@cwd)
294 valid_dir
? @cwd, "Invalid path to change to during daemon mode: #@cwd"
298 valid_exists
? @pid_file, "PID file #@pid_file does not exist. Not running?"
304 @wait.to_i
.times
do |waiting
|
305 exit(0) if not File
.exist
? @pid_file
309 Mongrel
::send_signal("KILL", @pid_file) if File
.exist
? @pid_file
311 Mongrel
::send_signal("TERM", @pid_file)
317 class Restart
< GemPlugin
::Plugin "/commands"
318 include Mongrel
::Command::Base
322 ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, '.'],
323 ['-P', '--pid FILE', "Where the PID file is located", :@pid_file, "log/mongrel.pid"]
328 @cwd = File
.expand_path(@cwd)
329 valid_dir
? @cwd, "Invalid path to change to during daemon mode: #@cwd"
333 valid_exists
? @pid_file, "PID file #@pid_file does not exist. Not running?"
338 MongrelServer
::send_signal("USR2", @pid_file)