Class | Mongrel::Configurator |
In: |
lib/mongrel/configurator.rb
lib/mongrel/configurator.rb |
Parent: | Object |
Implements a simple DSL for configuring a Mongrel server for your purposes. More used by framework implementers to setup Mongrel how they like, but could be used by regular folks to add more things to an existing mongrel configuration.
It is used like this:
require 'mongrel' config = Mongrel::Configurator.new :host => "127.0.0.1" do listener :port => 3000 do uri "/app", :handler => Mongrel::DirHandler.new(".", load_mime_map("mime.yaml")) end run end
This will setup a simple DirHandler at the current directory and load additional mime types from mimy.yaml. The :host => "127.0.0.1" is actually not specific to the servers but just a hash of default parameters that all server or uri calls receive.
When you are inside the block after Mongrel::Configurator.new you can simply call functions that are part of Configurator (like server, uri, daemonize, etc) without having to refer to anything else. You can also call these functions on the resulting object directly for additional configuration.
A major thing about Configurator is that it actually lets you configure multiple listeners for any hosts and ports you want. These are kept in a map config.listeners so you can get to them.
defaults | [R] | |
defaults | [R] | |
listeners | [R] | |
listeners | [R] | |
needs_restart | [R] | |
needs_restart | [R] |
You pass in initial defaults and then a block to continue configuring.
# File lib/mongrel/configurator.rb, line 41 41: def initialize(defaults={}, &block) 42: @listener = nil 43: @listener_name = nil 44: @listeners = {} 45: @defaults = defaults 46: @needs_restart = false 47: @pid_file = defaults[:pid_file] 48: 49: if block 50: cloaker(&block).bind(self).call 51: end 52: end
You pass in initial defaults and then a block to continue configuring.
# File lib/mongrel/configurator.rb, line 41 41: def initialize(defaults={}, &block) 42: @listener = nil 43: @listener_name = nil 44: @listeners = {} 45: @defaults = defaults 46: @needs_restart = false 47: @pid_file = defaults[:pid_file] 48: 49: if block 50: cloaker(&block).bind(self).call 51: end 52: end
Change privileges of the process to specified user and group.
# File lib/mongrel/configurator.rb, line 55 55: def change_privilege(user, group) 56: begin 57: uid, gid = Process.euid, Process.egid 58: target_uid = Etc.getpwnam(user).uid if user 59: target_gid = Etc.getgrnam(group).gid if group 60: 61: if uid != target_uid or gid != target_gid 62: log "Initiating groups for #{user.inspect}:#{group.inspect}." 63: Process.initgroups(user, target_gid) 64: 65: log "Changing group to #{group.inspect}." 66: Process::GID.change_privilege(target_gid) 67: 68: log "Changing user to #{user.inspect}." 69: Process::UID.change_privilege(target_uid) 70: end 71: rescue Errno::EPERM => e 72: log "Couldn't change user and group to #{user.inspect}:#{group.inspect}: #{e.to_s}." 73: log "Mongrel failed to start." 74: exit 1 75: end 76: end
Change privileges of the process to specified user and group.
# File lib/mongrel/configurator.rb, line 55 55: def change_privilege(user, group) 56: begin 57: uid, gid = Process.euid, Process.egid 58: target_uid = Etc.getpwnam(user).uid if user 59: target_gid = Etc.getgrnam(group).gid if group 60: 61: if uid != target_uid or gid != target_gid 62: log "Initiating groups for #{user.inspect}:#{group.inspect}." 63: Process.initgroups(user, target_gid) 64: 65: log "Changing group to #{group.inspect}." 66: Process::GID.change_privilege(target_gid) 67: 68: log "Changing user to #{user.inspect}." 69: Process::UID.change_privilege(target_uid) 70: end 71: rescue Errno::EPERM => e 72: log "Couldn't change user and group to #{user.inspect}:#{group.inspect}: #{e.to_s}." 73: log "Mongrel failed to start." 74: exit 1 75: end 76: end
Do not call this. You were warned.
# File lib/mongrel/configurator.rb, line 102 102: def cloaker(&block) 103: cloaking_class.class_eval do 104: define_method :cloaker_, &block 105: meth = instance_method( :cloaker_ ) 106: remove_method :cloaker_ 107: meth 108: end 109: end
Do not call this. You were warned.
# File lib/mongrel/configurator.rb, line 102 102: def cloaker(&block) 103: cloaking_class.class_eval do 104: define_method :cloaker_, &block 105: meth = instance_method( :cloaker_ ) 106: remove_method :cloaker_ 107: meth 108: end 109: end
Generates a class for cloaking the current self and making the DSL nicer.
# File lib/mongrel/configurator.rb, line 95 95: def cloaking_class 96: class << self 97: self 98: end 99: end
Generates a class for cloaking the current self and making the DSL nicer.
# File lib/mongrel/configurator.rb, line 95 95: def cloaking_class 96: class << self 97: self 98: end 99: end
Daemonizes the current Ruby script turning all the listeners into an actual "server" or detached process. You must call this before frameworks that open files as otherwise the files will be closed by this function.
Does not work for Win32 systems (the call is silently ignored).
Requires the following options or defaults:
It is safe to call this on win32 as it will only require the daemons gem/library if NOT win32.
# File lib/mongrel/configurator.rb, line 185 185: def daemonize(options={}) 186: ops = resolve_defaults(options) 187: # save this for later since daemonize will hose it 188: if RUBY_PLATFORM !~ /mswin/ 189: require 'daemons/daemonize' 190: 191: logfile = ops[:log_file] 192: if logfile[0].chr != "/" 193: logfile = File.join(ops[:cwd],logfile) 194: if not File.exist?(File.dirname(logfile)) 195: log "!!! Log file directory not found at full path #{File.dirname(logfile)}. Update your configuration to use a full path." 196: exit 1 197: end 198: end 199: 200: Daemonize.daemonize(logfile) 201: 202: # change back to the original starting directory 203: Dir.chdir(ops[:cwd]) 204: 205: else 206: log "WARNING: Win32 does not support daemon mode." 207: end 208: end
Daemonizes the current Ruby script turning all the listeners into an actual "server" or detached process. You must call this before frameworks that open files as otherwise the files will be closed by this function.
Does not work for Win32 systems (the call is silently ignored).
Requires the following options or defaults:
It is safe to call this on win32 as it will only require the daemons gem/library if NOT win32.
# File lib/mongrel/configurator.rb, line 185 185: def daemonize(options={}) 186: ops = resolve_defaults(options) 187: # save this for later since daemonize will hose it 188: if RUBY_PLATFORM !~ /mswin/ 189: require 'daemons/daemonize' 190: 191: logfile = ops[:log_file] 192: if logfile[0].chr != "/" 193: logfile = File.join(ops[:cwd],logfile) 194: if not File.exist?(File.dirname(logfile)) 195: log "!!! Log file directory not found at full path #{File.dirname(logfile)}. Update your configuration to use a full path." 196: exit 1 197: end 198: end 199: 200: Daemonize.daemonize(logfile) 201: 202: # change back to the original starting directory 203: Dir.chdir(ops[:cwd]) 204: 205: else 206: log "WARNING: Win32 does not support daemon mode." 207: end 208: end
Calling this before you register your URIs to the given location will setup a set of handlers that log open files, objects, and the parameters for each request. This helps you track common problems found in Rails applications that are either slow or become unresponsive after a little while.
You can pass an extra parameter what to indicate what you want to debug. For example, if you just want to dump rails stuff then do:
debug "/", what = [:rails]
And it will only produce the log/mongrel_debug/rails.log file. Available options are: :access, :files, :objects, :threads, :rails
NOTE: Use [:files] to get accesses dumped to stderr like with WEBrick.
# File lib/mongrel/configurator.rb, line 322 322: def debug(location, what = [:access, :files, :objects, :threads, :rails]) 323: require 'mongrel/debug' 324: handlers = { 325: :access => "/handlers/requestlog::access", 326: :files => "/handlers/requestlog::files", 327: :objects => "/handlers/requestlog::objects", 328: :threads => "/handlers/requestlog::threads", 329: :rails => "/handlers/requestlog::params" 330: } 331: 332: # turn on the debugging infrastructure, and ObjectTracker is a pig 333: MongrelDbg.configure 334: 335: # now we roll through each requested debug type, turn it on and load that plugin 336: what.each do |type| 337: MongrelDbg.begin_trace type 338: uri location, :handler => plugin(handlers[type]) 339: end 340: end
Calling this before you register your URIs to the given location will setup a set of handlers that log open files, objects, and the parameters for each request. This helps you track common problems found in Rails applications that are either slow or become unresponsive after a little while.
You can pass an extra parameter what to indicate what you want to debug. For example, if you just want to dump rails stuff then do:
debug "/", what = [:rails]
And it will only produce the log/mongrel_debug/rails.log file. Available options are: :access, :files, :objects, :threads, :rails
NOTE: Use [:files] to get accesses dumped to stderr like with WEBrick.
# File lib/mongrel/configurator.rb, line 322 322: def debug(location, what = [:access, :files, :objects, :threads, :rails]) 323: require 'mongrel/debug' 324: handlers = { 325: :access => "/handlers/requestlog::access", 326: :files => "/handlers/requestlog::files", 327: :objects => "/handlers/requestlog::objects", 328: :threads => "/handlers/requestlog::threads", 329: :rails => "/handlers/requestlog::params" 330: } 331: 332: # turn on the debugging infrastructure, and ObjectTracker is a pig 333: MongrelDbg.configure 334: 335: # now we roll through each requested debug type, turn it on and load that plugin 336: what.each do |type| 337: MongrelDbg.begin_trace type 338: uri location, :handler => plugin(handlers[type]) 339: end 340: end
This method should actually be called outside of the Configurator block so that you can control it. In other words do it like: config.join.
# File lib/mongrel/configurator.rb, line 302 302: def join 303: @listeners.values.each {|s| s.acceptor.join } 304: end
This method should actually be called outside of the Configurator block so that you can control it. In other words do it like: config.join.
# File lib/mongrel/configurator.rb, line 302 302: def join 303: @listeners.values.each {|s| s.acceptor.join } 304: end
Starts a listener block. This is the only one that actually takes a block and then you make Configurator.uri calls in order to setup your URIs and handlers. If you write your Handlers as GemPlugins then you can use load_plugins and plugin to load them.
It expects the following options (or defaults):
# File lib/mongrel/configurator.rb, line 132 132: def listener(options={},&block) 133: raise "Cannot call listener inside another listener block." if (@listener or @listener_name) 134: ops = resolve_defaults(options) 135: ops[:num_processors] ||= 950 136: ops[:throttle] ||= 0 137: ops[:timeout] ||= 60 138: 139: @listener = Mongrel::HttpServer.new(ops[:host], ops[:port].to_i, ops[:num_processors].to_i, ops[:throttle].to_i, ops[:timeout].to_i) 140: @listener_name = "#{ops[:host]}:#{ops[:port]}" 141: @listeners[@listener_name] = @listener 142: 143: if ops[:user] and ops[:group] 144: change_privilege(ops[:user], ops[:group]) 145: end 146: 147: # Does the actual cloaking operation to give the new implicit self. 148: if block 149: cloaker(&block).bind(self).call 150: end 151: 152: # all done processing this listener setup, reset implicit variables 153: @listener = nil 154: @listener_name = nil 155: end
Starts a listener block. This is the only one that actually takes a block and then you make Configurator.uri calls in order to setup your URIs and handlers. If you write your Handlers as GemPlugins then you can use load_plugins and plugin to load them.
It expects the following options (or defaults):
# File lib/mongrel/configurator.rb, line 132 132: def listener(options={},&block) 133: raise "Cannot call listener inside another listener block." if (@listener or @listener_name) 134: ops = resolve_defaults(options) 135: ops[:num_processors] ||= 950 136: ops[:throttle] ||= 0 137: ops[:timeout] ||= 60 138: 139: @listener = Mongrel::HttpServer.new(ops[:host], ops[:port].to_i, ops[:num_processors].to_i, ops[:throttle].to_i, ops[:timeout].to_i) 140: @listener_name = "#{ops[:host]}:#{ops[:port]}" 141: @listeners[@listener_name] = @listener 142: 143: if ops[:user] and ops[:group] 144: change_privilege(ops[:user], ops[:group]) 145: end 146: 147: # Does the actual cloaking operation to give the new implicit self. 148: if block 149: cloaker(&block).bind(self).call 150: end 151: 152: # all done processing this listener setup, reset implicit variables 153: @listener = nil 154: @listener_name = nil 155: end
Loads the MIME map file and checks that it is correct on loading. This is commonly passed to Mongrel::DirHandler or any framework handler that uses DirHandler to serve files. You can also include a set of default MIME types as additional settings. See Mongrel::DirHandler for how the MIME types map is organized.
# File lib/mongrel/configurator.rb, line 247 247: def load_mime_map(file, mime={}) 248: # configure any requested mime map 249: mime = load_yaml(file, mime) 250: 251: # check all the mime types to make sure they are the right format 252: mime.each {|k,v| log "WARNING: MIME type #{k} must start with '.'" if k.index(".") != 0 } 253: 254: return mime 255: end
Loads the MIME map file and checks that it is correct on loading. This is commonly passed to Mongrel::DirHandler or any framework handler that uses DirHandler to serve files. You can also include a set of default MIME types as additional settings. See Mongrel::DirHandler for how the MIME types map is organized.
# File lib/mongrel/configurator.rb, line 247 247: def load_mime_map(file, mime={}) 248: # configure any requested mime map 249: mime = load_yaml(file, mime) 250: 251: # check all the mime types to make sure they are the right format 252: mime.each {|k,v| log "WARNING: MIME type #{k} must start with '.'" if k.index(".") != 0 } 253: 254: return mime 255: end
Uses the GemPlugin system to easily load plugins based on their gem dependencies. You pass in either an :includes => [] or :excludes => [] setting listing the names of plugins to include or exclude from the determining the dependencies.
# File lib/mongrel/configurator.rb, line 215 215: def load_plugins(options={}) 216: ops = resolve_defaults(options) 217: 218: load_settings = {} 219: if ops[:includes] 220: ops[:includes].each do |plugin| 221: load_settings[plugin] = GemPlugin::INCLUDE 222: end 223: end 224: 225: if ops[:excludes] 226: ops[:excludes].each do |plugin| 227: load_settings[plugin] = GemPlugin::EXCLUDE 228: end 229: end 230: 231: GemPlugin::Manager.instance.load(load_settings) 232: end
Uses the GemPlugin system to easily load plugins based on their gem dependencies. You pass in either an :includes => [] or :excludes => [] setting listing the names of plugins to include or exclude from the determining the dependencies.
# File lib/mongrel/configurator.rb, line 215 215: def load_plugins(options={}) 216: ops = resolve_defaults(options) 217: 218: load_settings = {} 219: if ops[:includes] 220: ops[:includes].each do |plugin| 221: load_settings[plugin] = GemPlugin::INCLUDE 222: end 223: end 224: 225: if ops[:excludes] 226: ops[:excludes].each do |plugin| 227: load_settings[plugin] = GemPlugin::EXCLUDE 228: end 229: end 230: 231: GemPlugin::Manager.instance.load(load_settings) 232: end
Easy way to load a YAML file and apply default settings.
# File lib/mongrel/configurator.rb, line 236 236: def load_yaml(file, default={}) 237: default.merge(YAML.load_file(file)) 238: end
Easy way to load a YAML file and apply default settings.
# File lib/mongrel/configurator.rb, line 236 236: def load_yaml(file, default={}) 237: default.merge(YAML.load_file(file)) 238: end
Loads and creates a plugin for you based on the given name and configured with the selected options. The options are merged with the defaults prior to passing them in.
# File lib/mongrel/configurator.rb, line 261 261: def plugin(name, options={}) 262: ops = resolve_defaults(options) 263: GemPlugin::Manager.instance.create(name, ops) 264: end
Loads and creates a plugin for you based on the given name and configured with the selected options. The options are merged with the defaults prior to passing them in.
# File lib/mongrel/configurator.rb, line 261 261: def plugin(name, options={}) 262: ops = resolve_defaults(options) 263: GemPlugin::Manager.instance.create(name, ops) 264: end
Lets you do redirects easily as described in Mongrel::RedirectHandler. You use it inside the configurator like this:
redirect("/test", "/to/there") # simple redirect("/to", /t/, 'w') # regexp redirect("/hey", /(w+)/) {|match| ...} # block
# File lib/mongrel/configurator.rb, line 273 273: def redirect(from, pattern, replacement = nil, &block) 274: uri from, :handler => Mongrel::RedirectHandler.new(pattern, replacement, &block) 275: end
Lets you do redirects easily as described in Mongrel::RedirectHandler. You use it inside the configurator like this:
redirect("/test", "/to/there") # simple redirect("/to", /t/, 'w') # regexp redirect("/hey", /(w+)/) {|match| ...} # block
# File lib/mongrel/configurator.rb, line 273 273: def redirect(from, pattern, replacement = nil, &block) 274: uri from, :handler => Mongrel::RedirectHandler.new(pattern, replacement, &block) 275: end
# File lib/mongrel/configurator.rb, line 78 78: def remove_pid_file 79: File.unlink(@pid_file) if @pid_file and File.exists?(@pid_file) 80: end
# File lib/mongrel/configurator.rb, line 78 78: def remove_pid_file 79: File.unlink(@pid_file) if @pid_file and File.exists?(@pid_file) 80: end
This will resolve the given options against the defaults. Normally just used internally.
# File lib/mongrel/configurator.rb, line 113 113: def resolve_defaults(options) 114: options.merge(@defaults) 115: end
This will resolve the given options against the defaults. Normally just used internally.
# File lib/mongrel/configurator.rb, line 113 113: def resolve_defaults(options) 114: options.merge(@defaults) 115: end
Works like a meta run method which goes through all the configured listeners. Use the Configurator.join method to prevent Ruby from exiting until each one is done.
# File lib/mongrel/configurator.rb, line 280 280: def run 281: @listeners.each {|name,s| 282: s.run 283: } 284: 285: $mongrel_sleeper_thread = Thread.new { loop { sleep 1 } } 286: end
Works like a meta run method which goes through all the configured listeners. Use the Configurator.join method to prevent Ruby from exiting until each one is done.
# File lib/mongrel/configurator.rb, line 280 280: def run 281: @listeners.each {|name,s| 282: s.run 283: } 284: 285: $mongrel_sleeper_thread = Thread.new { loop { sleep 1 } } 286: end
Used to allow you to let users specify their own configurations inside your Configurator setup. You pass it a script name and it reads it in and does an eval on the contents passing in the right binding so they can put their own Configurator statements.
# File lib/mongrel/configurator.rb, line 346 346: def run_config(script) 347: open(script) {|f| eval(f.read, proc {self}) } 348: end
Used to allow you to let users specify their own configurations inside your Configurator setup. You pass it a script name and it reads it in and does an eval on the contents passing in the right binding so they can put their own Configurator statements.
# File lib/mongrel/configurator.rb, line 346 346: def run_config(script) 347: open(script) {|f| eval(f.read, proc {self}) } 348: end
Sets up the standard signal handlers that are used on most Ruby It only configures if the platform is not win32 and doesn‘t do a HUP signal since this is typically framework specific.
Requires a :pid_file option given to Configurator.new to indicate a file to delete. It sets the MongrelConfig.needs_restart attribute if the start command should reload. It‘s up to you to detect this and do whatever is needed for a "restart".
This command is safely ignored if the platform is win32 (with a warning)
# File lib/mongrel/configurator.rb, line 360 360: def setup_signals(options={}) 361: ops = resolve_defaults(options) 362: 363: # forced shutdown, even if previously restarted (actually just like TERM but for CTRL-C) 364: trap("INT") { log "INT signal received."; stop(false) } 365: 366: # clean up the pid file always 367: at_exit { remove_pid_file } 368: 369: if RUBY_PLATFORM !~ /mswin/ 370: # graceful shutdown 371: trap("TERM") { log "TERM signal received."; stop } 372: trap("USR1") { log "USR1 received, toggling $mongrel_debug_client to #{!$mongrel_debug_client}"; $mongrel_debug_client = !$mongrel_debug_client } 373: # restart 374: trap("USR2") { log "USR2 signal received."; stop(true) } 375: 376: log "Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart)." 377: else 378: log "Signals ready. INT => stop (no restart)." 379: end 380: end
Sets up the standard signal handlers that are used on most Ruby It only configures if the platform is not win32 and doesn‘t do a HUP signal since this is typically framework specific.
Requires a :pid_file option given to Configurator.new to indicate a file to delete. It sets the MongrelConfig.needs_restart attribute if the start command should reload. It‘s up to you to detect this and do whatever is needed for a "restart".
This command is safely ignored if the platform is win32 (with a warning)
# File lib/mongrel/configurator.rb, line 360 360: def setup_signals(options={}) 361: ops = resolve_defaults(options) 362: 363: # forced shutdown, even if previously restarted (actually just like TERM but for CTRL-C) 364: trap("INT") { log "INT signal received."; stop(false) } 365: 366: # clean up the pid file always 367: at_exit { remove_pid_file } 368: 369: if RUBY_PLATFORM !~ /mswin/ 370: # graceful shutdown 371: trap("TERM") { log "TERM signal received."; stop } 372: trap("USR1") { log "USR1 received, toggling $mongrel_debug_client to #{!$mongrel_debug_client}"; $mongrel_debug_client = !$mongrel_debug_client } 373: # restart 374: trap("USR2") { log "USR2 signal received."; stop(true) } 375: 376: log "Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart)." 377: else 378: log "Signals ready. INT => stop (no restart)." 379: end 380: end
Calls .stop on all the configured listeners so they stop processing requests (gracefully). By default it assumes that you don‘t want to restart.
# File lib/mongrel/configurator.rb, line 291 291: def stop(needs_restart=false, synchronous=false) 292: @listeners.each do |name,s| 293: s.stop(synchronous) 294: end 295: @needs_restart = needs_restart 296: end
Calls .stop on all the configured listeners so they stop processing requests (gracefully). By default it assumes that you don‘t want to restart.
# File lib/mongrel/configurator.rb, line 291 291: def stop(needs_restart=false, synchronous=false) 292: @listeners.each do |name,s| 293: s.stop(synchronous) 294: end 295: @needs_restart = needs_restart 296: end
Called inside a Configurator.listener block in order to add URI->handler mappings for that listener. Use this as many times as you like. It expects the following options or defaults:
# File lib/mongrel/configurator.rb, line 165 165: def uri(location, options={}) 166: ops = resolve_defaults(options) 167: @listener.register(location, ops[:handler], ops[:in_front]) 168: end
Called inside a Configurator.listener block in order to add URI->handler mappings for that listener. Use this as many times as you like. It expects the following options or defaults:
# File lib/mongrel/configurator.rb, line 165 165: def uri(location, options={}) 166: ops = resolve_defaults(options) 167: @listener.register(location, ops[:handler], ops[:in_front]) 168: end
Writes the PID file if we‘re not on Windows.
# File lib/mongrel/configurator.rb, line 83 83: def write_pid_file 84: if RUBY_PLATFORM !~ /mswin/ 85: log "Writing PID file to #{@pid_file}" 86: open(@pid_file,"w") {|f| f.write(Process.pid) } 87: open(@pid_file,"w") do |f| 88: f.write(Process.pid) 89: File.chmod(0644, @pid_file) 90: end 91: end 92: end
Writes the PID file if we‘re not on Windows.
# File lib/mongrel/configurator.rb, line 83 83: def write_pid_file 84: if RUBY_PLATFORM !~ /mswin/ 85: log "Writing PID file to #{@pid_file}" 86: open(@pid_file,"w") {|f| f.write(Process.pid) } 87: open(@pid_file,"w") do |f| 88: f.write(Process.pid) 89: File.chmod(0644, @pid_file) 90: end 91: end 92: end