Begin writing HTTP request headers early to detect disconnected clients
[unicorn.git] / lib / unicorn / configurator.rb
blob9752cddca40301e3424f97c1df6e74fd3daacc5b
1 # -*- encoding: binary -*-
2 require 'logger'
3 require 'unicorn/ssl_configurator'
5 # Implements a simple DSL for configuring a \Unicorn server.
7 # See http://unicorn.bogomips.org/examples/unicorn.conf.rb and
8 # http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
9 # example configuration files.  An example config file for use with
10 # nginx is also available at
11 # http://unicorn.bogomips.org/examples/nginx.conf
13 # See the link:/TUNING.html document for more information on tuning unicorn.
14 class Unicorn::Configurator
15   include Unicorn
16   include Unicorn::SSLConfigurator
18   # :stopdoc:
19   attr_accessor :set, :config_file, :after_reload
21   # used to stash stuff for deferred processing of cli options in
22   # config.ru after "working_directory" is bound.  Do not rely on
23   # this being around later on...
24   RACKUP = {
25     :daemonize => false,
26     :host => Unicorn::Const::DEFAULT_HOST,
27     :port => Unicorn::Const::DEFAULT_PORT,
28     :set_listener => false,
29     :options => { :listeners => [] }
30   }
32   # Default settings for Unicorn
33   DEFAULTS = {
34     :timeout => 60,
35     :logger => Logger.new($stderr),
36     :worker_processes => 1,
37     :after_fork => lambda { |server, worker|
38         server.logger.info("worker=#{worker.nr} spawned pid=#{$$}")
39       },
40     :before_fork => lambda { |server, worker|
41         server.logger.info("worker=#{worker.nr} spawning...")
42       },
43     :before_exec => lambda { |server|
44         server.logger.info("forked child re-executing...")
45       },
46     :pid => nil,
47     :preload_app => false,
48     :check_client_connection => false,
49     :rewindable_input => true, # for Rack 2.x: (Rack::VERSION[0] <= 1),
50     :client_body_buffer_size => Unicorn::Const::MAX_BODY,
51     :trust_x_forwarded => true,
52   }
53   #:startdoc:
55   def initialize(defaults = {}) #:nodoc:
56     self.set = Hash.new(:unset)
57     @use_defaults = defaults.delete(:use_defaults)
58     self.config_file = defaults.delete(:config_file)
60     # after_reload is only used by unicorn_rails, unsupported otherwise
61     self.after_reload = defaults.delete(:after_reload)
63     set.merge!(DEFAULTS) if @use_defaults
64     defaults.each { |key, value| self.__send__(key, value) }
65     Hash === set[:listener_opts] or
66         set[:listener_opts] = Hash.new { |hash,key| hash[key] = {} }
67     Array === set[:listeners] or set[:listeners] = []
68     reload(false)
69   end
71   def reload(merge_defaults = true) #:nodoc:
72     if merge_defaults && @use_defaults
73       set.merge!(DEFAULTS) if @use_defaults
74     end
75     instance_eval(File.read(config_file), config_file) if config_file
77     parse_rackup_file
79     RACKUP[:set_listener] and
80       set[:listeners] << "#{RACKUP[:host]}:#{RACKUP[:port]}"
82     # unicorn_rails creates dirs here after working_directory is bound
83     after_reload.call if after_reload
85     # working_directory binds immediately (easier error checking that way),
86     # now ensure any paths we changed are correctly set.
87     [ :pid, :stderr_path, :stdout_path ].each do |var|
88       String === (path = set[var]) or next
89       path = File.expand_path(path)
90       File.writable?(path) || File.writable?(File.dirname(path)) or \
91             raise ArgumentError, "directory for #{var}=#{path} not writable"
92     end
93   end
95   def commit!(server, options = {}) #:nodoc:
96     skip = options[:skip] || []
97     if ready_pipe = RACKUP.delete(:ready_pipe)
98       server.ready_pipe = ready_pipe
99     end
100     if set[:check_client_connection]
101       set[:listeners].each do |address|
102         if set[:listener_opts][address][:tcp_nopush] == true
103           raise ArgumentError,
104             "check_client_connection is incompatible with tcp_nopush:true"
105         end
106         if set[:listener_opts][address][:tcp_nodelay] == true
107           raise ArgumentError,
108             "check_client_connection is incompatible with tcp_nodelay:true"
109         end
110       end
111     end
112     set.each do |key, value|
113       value == :unset and next
114       skip.include?(key) and next
115       server.__send__("#{key}=", value)
116     end
117   end
119   def [](key) # :nodoc:
120     set[key]
121   end
123   # sets object to the +obj+ Logger-like object.  The new Logger-like
124   # object must respond to the following methods:
125   # * debug
126   # * info
127   # * warn
128   # * error
129   # * fatal
130   # The default Logger will log its output to the path specified
131   # by +stderr_path+.  If you're running Unicorn daemonized, then
132   # you must specify a path to prevent error messages from going
133   # to /dev/null.
134   def logger(obj)
135     %w(debug info warn error fatal).each do |m|
136       obj.respond_to?(m) and next
137       raise ArgumentError, "logger=#{obj} does not respond to method=#{m}"
138     end
140     set[:logger] = obj
141   end
143   # sets after_fork hook to a given block.  This block will be called by
144   # the worker after forking.  The following is an example hook which adds
145   # a per-process listener to every worker:
146   #
147   #  after_fork do |server,worker|
148   #    # per-process listener ports for debugging/admin:
149   #    addr = "127.0.0.1:#{9293 + worker.nr}"
150   #
151   #    # the negative :tries parameter indicates we will retry forever
152   #    # waiting on the existing process to exit with a 5 second :delay
153   #    # Existing options for Unicorn::Configurator#listen such as
154   #    # :backlog, :rcvbuf, :sndbuf are available here as well.
155   #    server.listen(addr, :tries => -1, :delay => 5, :backlog => 128)
156   #  end
157   def after_fork(*args, &block)
158     set_hook(:after_fork, block_given? ? block : args[0])
159   end
161   # sets before_fork got be a given Proc object.  This Proc
162   # object will be called by the master process before forking
163   # each worker.
164   def before_fork(*args, &block)
165     set_hook(:before_fork, block_given? ? block : args[0])
166   end
168   # sets the before_exec hook to a given Proc object.  This
169   # Proc object will be called by the master process right
170   # before exec()-ing the new unicorn binary.  This is useful
171   # for freeing certain OS resources that you do NOT wish to
172   # share with the reexeced child process.
173   # There is no corresponding after_exec hook (for obvious reasons).
174   def before_exec(*args, &block)
175     set_hook(:before_exec, block_given? ? block : args[0], 1)
176   end
178   # sets the timeout of worker processes to +seconds+.  Workers
179   # handling the request/app.call/response cycle taking longer than
180   # this time period will be forcibly killed (via SIGKILL).  This
181   # timeout is enforced by the master process itself and not subject
182   # to the scheduling limitations by the worker process.  Due the
183   # low-complexity, low-overhead implementation, timeouts of less
184   # than 3.0 seconds can be considered inaccurate and unsafe.
185   #
186   # For running Unicorn behind nginx, it is recommended to set
187   # "fail_timeout=0" for in your nginx configuration like this
188   # to have nginx always retry backends that may have had workers
189   # SIGKILL-ed due to timeouts.
190   #
191   #    # See http://wiki.nginx.org/NginxHttpUpstreamModule for more details
192   #    # on nginx upstream configuration:
193   #    upstream unicorn_backend {
194   #      # for UNIX domain socket setups:
195   #      server unix:/path/to/unicorn.sock fail_timeout=0;
196   #
197   #      # for TCP setups
198   #      server 192.168.0.7:8080 fail_timeout=0;
199   #      server 192.168.0.8:8080 fail_timeout=0;
200   #      server 192.168.0.9:8080 fail_timeout=0;
201   #    }
202   def timeout(seconds)
203     set_int(:timeout, seconds, 3)
204     # POSIX says 31 days is the smallest allowed maximum timeout for select()
205     max = 30 * 60 * 60 * 24
206     set[:timeout] = seconds > max ? max : seconds
207   end
209   # sets the current number of worker_processes to +nr+.  Each worker
210   # process will serve exactly one client at a time.  You can
211   # increment or decrement this value at runtime by sending SIGTTIN
212   # or SIGTTOU respectively to the master process without reloading
213   # the rest of your Unicorn configuration.  See the SIGNALS document
214   # for more information.
215   def worker_processes(nr)
216     set_int(:worker_processes, nr, 1)
217   end
219   # sets listeners to the given +addresses+, replacing or augmenting the
220   # current set.  This is for the global listener pool shared by all
221   # worker processes.  For per-worker listeners, see the after_fork example
222   # This is for internal API use only, do not use it in your Unicorn
223   # config file.  Use listen instead.
224   def listeners(addresses) # :nodoc:
225     Array === addresses or addresses = Array(addresses)
226     addresses.map! { |addr| expand_addr(addr) }
227     set[:listeners] = addresses
228   end
230   # Adds an +address+ to the existing listener set.  May be specified more
231   # than once.  +address+ may be an Integer port number for a TCP port, an
232   # "IP_ADDRESS:PORT" for TCP listeners or a pathname for UNIX domain sockets.
233   #
234   #   listen 3000 # listen to port 3000 on all TCP interfaces
235   #   listen "127.0.0.1:3000"  # listen to port 3000 on the loopback interface
236   #   listen "/tmp/.unicorn.sock" # listen on the given Unix domain socket
237   #   listen "[::1]:3000" # listen to port 3000 on the IPv6 loopback interface
238   #
239   # The following options may be specified (but are generally not needed):
240   #
241   # [:backlog => number of clients]
242   #
243   #   This is the backlog of the listen() syscall.
244   #
245   #   Some operating systems allow negative values here to specify the
246   #   maximum allowable value.  In most cases, this number is only
247   #   recommendation and there are other OS-specific tunables and
248   #   variables that can affect this number.  See the listen(2)
249   #   syscall documentation of your OS for the exact semantics of
250   #   this.
251   #
252   #   If you are running unicorn on multiple machines, lowering this number
253   #   can help your load balancer detect when a machine is overloaded
254   #   and give requests to a different machine.
255   #
256   #   Default: 1024
257   #
258   # [:rcvbuf => bytes, :sndbuf => bytes]
259   #
260   #   Maximum receive and send buffer sizes (in bytes) of sockets.
261   #
262   #   These correspond to the SO_RCVBUF and SO_SNDBUF settings which
263   #   can be set via the setsockopt(2) syscall.  Some kernels
264   #   (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
265   #   there is no need (and it is sometimes detrimental) to specify them.
266   #
267   #   See the socket API documentation of your operating system
268   #   to determine the exact semantics of these settings and
269   #   other operating system-specific knobs where they can be
270   #   specified.
271   #
272   #   Defaults: operating system defaults
273   #
274   # [:tcp_nodelay => true or false]
275   #
276   #   Disables Nagle's algorithm on TCP sockets if +true+.
277   #
278   #   Setting this to +true+ can make streaming responses in Rails 3.1
279   #   appear more quickly at the cost of slightly higher bandwidth usage.
280   #   The effect of this option is most visible if nginx is not used,
281   #   but nginx remains highly recommended with \Unicorn.
282   #
283   #   This has no effect on UNIX sockets.
284   #
285   #   Default: +true+ (Nagle's algorithm disabled) in \Unicorn,
286   #   +true+ in Rainbows!  This defaulted to +false+ in \Unicorn
287   #   3.x
288   #
289   # [:tcp_nopush => true or false]
290   #
291   #   Enables/disables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
292   #
293   #   This prevents partial TCP frames from being sent out and reduces
294   #   wakeups in nginx if it is on a different machine.  Since \Unicorn
295   #   is only designed for applications that send the response body
296   #   quickly without keepalive, sockets will always be flushed on close
297   #   to prevent delays.
298   #
299   #   This has no effect on UNIX sockets.
300   #
301   #   Default: +false+
302   #   This defaulted to +true+ in \Unicorn 3.4 - 3.7
303   #
304   # [:ipv6only => true or false]
305   #
306   #   This option makes IPv6-capable TCP listeners IPv6-only and unable
307   #   to receive IPv4 queries on dual-stack systems.  A separate IPv4-only
308   #   listener is required if this is true.
309   #
310   #   This option is only available for Ruby 1.9.2 and later.
311   #
312   #   Enabling this option for the IPv6-only listener and having a
313   #   separate IPv4 listener is recommended if you wish to support IPv6
314   #   on the same TCP port.  Otherwise, the value of \env[\"REMOTE_ADDR\"]
315   #   will appear as an ugly IPv4-mapped-IPv6 address for IPv4 clients
316   #   (e.g ":ffff:10.0.0.1" instead of just "10.0.0.1").
317   #
318   #   Default: Operating-system dependent
319   #
320   # [:tries => Integer]
321   #
322   #   Times to retry binding a socket if it is already in use
323   #
324   #   A negative number indicates we will retry indefinitely, this is
325   #   useful for migrations and upgrades when individual workers
326   #   are binding to different ports.
327   #
328   #   Default: 5
329   #
330   # [:delay => seconds]
331   #
332   #   Seconds to wait between successive +tries+
333   #
334   #   Default: 0.5 seconds
335   #
336   # [:umask => mode]
337   #
338   #   Sets the file mode creation mask for UNIX sockets.  If specified,
339   #   this is usually in octal notation.
340   #
341   #   Typically UNIX domain sockets are created with more liberal
342   #   file permissions than the rest of the application.  By default,
343   #   we create UNIX domain sockets to be readable and writable by
344   #   all local users to give them the same accessibility as
345   #   locally-bound TCP listeners.
346   #
347   #   This has no effect on TCP listeners.
348   #
349   #   Default: 0000 (world-read/writable)
350   #
351   # [:tcp_defer_accept => Integer]
352   #
353   #   Defer accept() until data is ready (Linux-only)
354   #
355   #   For Linux 2.6.32 and later, this is the number of retransmits to
356   #   defer an accept() for if no data arrives, but the client will
357   #   eventually be accepted after the specified number of retransmits
358   #   regardless of whether data is ready.
359   #
360   #   For Linux before 2.6.32, this is a boolean option, and
361   #   accepts are _always_ deferred indefinitely if no data arrives.
362   #   This is similar to <code>:accept_filter => "dataready"</code>
363   #   under FreeBSD.
364   #
365   #   Specifying +true+ is synonymous for the default value(s) below,
366   #   and +false+ or +nil+ is synonymous for a value of zero.
367   #
368   #   A value of +1+ is a good optimization for local networks
369   #   and trusted clients.  For Rainbows! and Zbatery users, a higher
370   #   value (e.g. +60+) provides more protection against some
371   #   denial-of-service attacks.  There is no good reason to ever
372   #   disable this with a +zero+ value when serving HTTP.
373   #
374   #   Default: 1 retransmit for \Unicorn, 60 for Rainbows! 0.95.0\+
375   #
376   # [:accept_filter => String]
377   #
378   #   defer accept() until data is ready (FreeBSD-only)
379   #
380   #   This enables either the "dataready" or (default) "httpready"
381   #   accept() filter under FreeBSD.  This is intended as an
382   #   optimization to reduce context switches with common GET/HEAD
383   #   requests.  For Rainbows! and Zbatery users, this provides
384   #   some protection against certain denial-of-service attacks, too.
385   #
386   #   There is no good reason to change from the default.
387   #
388   #   Default: "httpready"
389   def listen(address, options = {})
390     address = expand_addr(address)
391     if String === address
392       [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
393         value = options[key] or next
394         Integer === value or
395           raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
396       end
397       [ :tcp_nodelay, :tcp_nopush, :ipv6only ].each do |key|
398         (value = options[key]).nil? and next
399         TrueClass === value || FalseClass === value or
400           raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
401       end
402       unless (value = options[:delay]).nil?
403         Numeric === value or
404           raise ArgumentError, "not numeric: delay=#{value.inspect}"
405       end
406       set[:listener_opts][address].merge!(options)
407     end
409     set[:listeners] << address
410   end
412   # sets the +path+ for the PID file of the unicorn master process
413   def pid(path); set_path(:pid, path); end
415   # Enabling this preloads an application before forking worker
416   # processes.  This allows memory savings when using a
417   # copy-on-write-friendly GC but can cause bad things to happen when
418   # resources like sockets are opened at load time by the master
419   # process and shared by multiple children.  People enabling this are
420   # highly encouraged to look at the before_fork/after_fork hooks to
421   # properly close/reopen sockets.  Files opened for logging do not
422   # have to be reopened as (unbuffered-in-userspace) files opened with
423   # the File::APPEND flag are written to atomically on UNIX.
424   #
425   # In addition to reloading the unicorn-specific config settings,
426   # SIGHUP will reload application code in the working
427   # directory/symlink when workers are gracefully restarted when
428   # preload_app=false (the default).  As reloading the application
429   # sometimes requires RubyGems updates, +Gem.refresh+ is always
430   # called before the application is loaded (for RubyGems users).
431   #
432   # During deployments, care should _always_ be taken to ensure your
433   # applications are properly deployed and running.  Using
434   # preload_app=false (the default) means you _must_ check if
435   # your application is responding properly after a deployment.
436   # Improperly deployed applications can go into a spawn loop
437   # if the application fails to load.  While your children are
438   # in a spawn loop, it is is possible to fix an application
439   # by properly deploying all required code and dependencies.
440   # Using preload_app=true means any application load error will
441   # cause the master process to exit with an error.
443   def preload_app(bool)
444     set_bool(:preload_app, bool)
445   end
447   # Toggles making \env[\"rack.input\"] rewindable.
448   # Disabling rewindability can improve performance by lowering
449   # I/O and memory usage for applications that accept uploads.
450   # Keep in mind that the Rack 1.x spec requires
451   # \env[\"rack.input\"] to be rewindable, so this allows
452   # intentionally violating the current Rack 1.x spec.
453   #
454   # +rewindable_input+ defaults to +true+ when used with Rack 1.x for
455   # Rack conformance.  When Rack 2.x is finalized, this will most
456   # likely default to +false+ while still conforming to the newer
457   # (less demanding) spec.
458   def rewindable_input(bool)
459     set_bool(:rewindable_input, bool)
460   end
462   # The maximum size (in +bytes+) to buffer in memory before
463   # resorting to a temporary file.  Default is 112 kilobytes.
464   # This option has no effect if "rewindable_input" is set to
465   # +false+.
466   def client_body_buffer_size(bytes)
467     set_int(:client_body_buffer_size, bytes, 0)
468   end
470   # When enabled, unicorn will check the client connection by writing
471   # the beginning of the HTTP headers before calling the application.
472   #
473   # This will prevent calling the application for clients who have
474   # disconnected while their connection was queued.
475   #
476   # This option cannot be used in conjunction with tcp_nodelay or
477   # tcp_nopush.
478   def check_client_connection(bool)
479     set_bool(:check_client_connection, bool)
480   end
482   # Allow redirecting $stderr to a given path.  Unlike doing this from
483   # the shell, this allows the unicorn process to know the path its
484   # writing to and rotate the file if it is used for logging.  The
485   # file will be opened with the File::APPEND flag and writes
486   # synchronized to the kernel (but not necessarily to _disk_) so
487   # multiple processes can safely append to it.
488   #
489   # If you are daemonizing and using the default +logger+, it is important
490   # to specify this as errors will otherwise be lost to /dev/null.
491   # Some applications/libraries may also triggering warnings that go to
492   # stderr, and they will end up here.
493   def stderr_path(path)
494     set_path(:stderr_path, path)
495   end
497   # Same as stderr_path, except for $stdout.  Not many Rack applications
498   # write to $stdout, but any that do will have their output written here.
499   # It is safe to point this to the same location a stderr_path.
500   # Like stderr_path, this defaults to /dev/null when daemonized.
501   def stdout_path(path)
502     set_path(:stdout_path, path)
503   end
505   # sets the working directory for Unicorn.  This ensures SIGUSR2 will
506   # start a new instance of Unicorn in this directory.  This may be
507   # a symlink, a common scenario for Capistrano users.  Unlike
508   # all other Unicorn configuration directives, this binds immediately
509   # for error checking and cannot be undone by unsetting it in the
510   # configuration file and reloading.
511   def working_directory(path)
512     # just let chdir raise errors
513     path = File.expand_path(path)
514     if config_file &&
515        config_file[0] != ?/ &&
516        ! File.readable?("#{path}/#{config_file}")
517       raise ArgumentError,
518             "config_file=#{config_file} would not be accessible in" \
519             " working_directory=#{path}"
520     end
521     Dir.chdir(path)
522     Unicorn::HttpServer::START_CTX[:cwd] = ENV["PWD"] = path
523   end
525   # Runs worker processes as the specified +user+ and +group+.
526   # The master process always stays running as the user who started it.
527   # This switch will occur after calling the after_fork hook, and only
528   # if the Worker#user method is not called in the after_fork hook
529   # +group+ is optional and will not change if unspecified.
530   def user(user, group = nil)
531     # raises ArgumentError on invalid user/group
532     Etc.getpwnam(user)
533     Etc.getgrnam(group) if group
534     set[:user] = [ user, group ]
535   end
537   # Sets whether or not the parser will trust X-Forwarded-Proto and
538   # X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
539   # Rainbows!/Zbatery installations facing untrusted clients directly
540   # should set this to +false+.  This is +true+ by default as Unicorn
541   # is designed to only sit behind trusted nginx proxies.
542   #
543   # This has never been publically documented and is subject to removal
544   # in future releases.
545   def trust_x_forwarded(bool) # :nodoc:
546     set_bool(:trust_x_forwarded, bool)
547   end
549   # expands "unix:path/to/foo" to a socket relative to the current path
550   # expands pathnames of sockets if relative to "~" or "~username"
551   # expands "*:port and ":port" to "0.0.0.0:port"
552   def expand_addr(address) #:nodoc:
553     return "0.0.0.0:#{address}" if Integer === address
554     return address unless String === address
556     case address
557     when %r{\Aunix:(.*)\z}
558       File.expand_path($1)
559     when %r{\A~}
560       File.expand_path(address)
561     when %r{\A(?:\*:)?(\d+)\z}
562       "0.0.0.0:#$1"
563     when %r{\A\[([a-fA-F0-9:]+)\]\z}, %r/\A((?:\d+\.){3}\d+)\z/
564       canonicalize_tcp($1, 80)
565     when %r{\A\[([a-fA-F0-9:]+)\]:(\d+)\z}, %r{\A(.*):(\d+)\z}
566       canonicalize_tcp($1, $2.to_i)
567     else
568       address
569     end
570   end
572 private
573   def set_int(var, n, min) #:nodoc:
574     Integer === n or raise ArgumentError, "not an integer: #{var}=#{n.inspect}"
575     n >= min or raise ArgumentError, "too low (< #{min}): #{var}=#{n.inspect}"
576     set[var] = n
577   end
579   def canonicalize_tcp(addr, port)
580     packed = Socket.pack_sockaddr_in(port, addr)
581     port, addr = Socket.unpack_sockaddr_in(packed)
582     /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
583   end
585   def set_path(var, path) #:nodoc:
586     case path
587     when NilClass, String
588       set[var] = path
589     else
590       raise ArgumentError
591     end
592   end
594   def check_bool(var, bool) # :nodoc:
595     case bool
596     when true, false
597       return bool
598     end
599     raise ArgumentError, "#{var}=#{bool.inspect} not a boolean"
600   end
602   def set_bool(var, bool) #:nodoc:
603     set[var] = check_bool(var, bool)
604   end
606   def set_hook(var, my_proc, req_arity = 2) #:nodoc:
607     case my_proc
608     when Proc
609       arity = my_proc.arity
610       (arity == req_arity) or \
611         raise ArgumentError,
612               "#{var}=#{my_proc.inspect} has invalid arity: " \
613               "#{arity} (need #{req_arity})"
614     when NilClass
615       my_proc = DEFAULTS[var]
616     else
617       raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
618     end
619     set[var] = my_proc
620   end
622   # this is called _after_ working_directory is bound.  This only
623   # parses the embedded switches in .ru files
624   # (for "rackup" compatibility)
625   def parse_rackup_file # :nodoc:
626     ru = RACKUP[:file] or return # we only return here in unit tests
628     # :rails means use (old) Rails autodetect
629     if ru == :rails
630       File.readable?('config.ru') or return
631       ru = 'config.ru'
632     end
634     File.readable?(ru) or
635       raise ArgumentError, "rackup file (#{ru}) not readable"
637     # it could be a .rb file, too, we don't parse those manually
638     ru =~ /\.ru\z/ or return
640     /^#\\(.*)/ =~ File.read(ru) or return
641     RACKUP[:optparse].parse!($1.split(/\s+/))
643     if RACKUP[:daemonize]
644       # unicorn_rails wants a default pid path, (not plain 'unicorn')
645       if after_reload
646         spid = set[:pid]
647         pid('tmp/pids/unicorn.pid') if spid.nil? || spid == :unset
648       end
649       unless RACKUP[:daemonized]
650         Unicorn::Launcher.daemonize!(RACKUP[:options])
651         RACKUP[:ready_pipe] = RACKUP[:options].delete(:ready_pipe)
652       end
653     end
654   end