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