Add early hints support
[unicorn.git] / lib / unicorn / configurator.rb
blobb0606af2cab5b0c8bcd6faefd88468f2e893ae49
1 # -*- encoding: binary -*-
2 require 'logger'
4 # Implements a simple DSL for configuring a unicorn server.
6 # See https://yhbt.net/unicorn/examples/unicorn.conf.rb and
7 # https://yhbt.net/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://yhbt.net/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 https://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 whether to enable the proposed early hints Rack API.
280   # If enabled, Rails 5.2+ will automatically send a 103 Early Hint
281   # for all the `javascript_include_tag` and `stylesheet_link_tag`
282   # in your response. See: https://api.rubyonrails.org/v5.2/classes/ActionDispatch/Request.html#method-i-send_early_hints
283   # See also https://tools.ietf.org/html/rfc8297
284   def early_hints(bool)
285     set_bool(:early_hints, bool)
286   end
288   # sets listeners to the given +addresses+, replacing or augmenting the
289   # current set.  This is for the global listener pool shared by all
290   # worker processes.  For per-worker listeners, see the after_fork example
291   # This is for internal API use only, do not use it in your Unicorn
292   # config file.  Use listen instead.
293   def listeners(addresses) # :nodoc:
294     Array === addresses or addresses = Array(addresses)
295     addresses.map! { |addr| expand_addr(addr) }
296     set[:listeners] = addresses
297   end
299   # Adds an +address+ to the existing listener set.  May be specified more
300   # than once.  +address+ may be an Integer port number for a TCP port, an
301   # "IP_ADDRESS:PORT" for TCP listeners or a pathname for UNIX domain sockets.
302   #
303   #   listen 3000 # listen to port 3000 on all TCP interfaces
304   #   listen "127.0.0.1:3000"  # listen to port 3000 on the loopback interface
305   #   listen "/path/to/.unicorn.sock" # listen on the given Unix domain socket
306   #   listen "[::1]:3000" # listen to port 3000 on the IPv6 loopback interface
307   #
308   # When using Unix domain sockets, be sure:
309   # 1) the path matches the one used by nginx
310   # 2) uses the same filesystem namespace as the nginx process
311   # For systemd users using PrivateTmp=true (for either nginx or unicorn),
312   # this means Unix domain sockets must not be placed in /tmp
313   #
314   # The following options may be specified (but are generally not needed):
315   #
316   # [:backlog => number of clients]
317   #
318   #   This is the backlog of the listen() syscall.
319   #
320   #   Some operating systems allow negative values here to specify the
321   #   maximum allowable value.  In most cases, this number is only
322   #   recommendation and there are other OS-specific tunables and
323   #   variables that can affect this number.  See the listen(2)
324   #   syscall documentation of your OS for the exact semantics of
325   #   this.
326   #
327   #   If you are running unicorn on multiple machines, lowering this number
328   #   can help your load balancer detect when a machine is overloaded
329   #   and give requests to a different machine.
330   #
331   #   Default: 1024
332   #
333   #   Note: with the Linux kernel, the net.core.somaxconn sysctl defaults
334   #   to 128, capping this value to 128.  Raising the sysctl allows a
335   #   larger backlog (which may not be desirable with multiple,
336   #   load-balanced machines).
337   #
338   # [:rcvbuf => bytes, :sndbuf => bytes]
339   #
340   #   Maximum receive and send buffer sizes (in bytes) of sockets.
341   #
342   #   These correspond to the SO_RCVBUF and SO_SNDBUF settings which
343   #   can be set via the setsockopt(2) syscall.  Some kernels
344   #   (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
345   #   there is no need (and it is sometimes detrimental) to specify them.
346   #
347   #   See the socket API documentation of your operating system
348   #   to determine the exact semantics of these settings and
349   #   other operating system-specific knobs where they can be
350   #   specified.
351   #
352   #   Defaults: operating system defaults
353   #
354   # [:tcp_nodelay => true or false]
355   #
356   #   Disables Nagle's algorithm on TCP sockets if +true+.
357   #
358   #   Setting this to +true+ can make streaming responses in Rails 3.1
359   #   appear more quickly at the cost of slightly higher bandwidth usage.
360   #   The effect of this option is most visible if nginx is not used,
361   #   but nginx remains highly recommended with unicorn.
362   #
363   #   This has no effect on UNIX sockets.
364   #
365   #   Default: +true+ (Nagle's algorithm disabled) in unicorn
366   #   This defaulted to +false+ in unicorn 3.x
367   #
368   # [:tcp_nopush => true or false]
369   #
370   #   Enables/disables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
371   #
372   #   This prevents partial TCP frames from being sent out and reduces
373   #   wakeups in nginx if it is on a different machine.  Since unicorn
374   #   is only designed for applications that send the response body
375   #   quickly without keepalive, sockets will always be flushed on close
376   #   to prevent delays.
377   #
378   #   This has no effect on UNIX sockets.
379   #
380   #   Default: +false+
381   #   This defaulted to +true+ in unicorn 3.4 - 3.7
382   #
383   # [:ipv6only => true or false]
384   #
385   #   This option makes IPv6-capable TCP listeners IPv6-only and unable
386   #   to receive IPv4 queries on dual-stack systems.  A separate IPv4-only
387   #   listener is required if this is true.
388   #
389   #   Enabling this option for the IPv6-only listener and having a
390   #   separate IPv4 listener is recommended if you wish to support IPv6
391   #   on the same TCP port.  Otherwise, the value of \env[\"REMOTE_ADDR\"]
392   #   will appear as an ugly IPv4-mapped-IPv6 address for IPv4 clients
393   #   (e.g ":ffff:10.0.0.1" instead of just "10.0.0.1").
394   #
395   #   Default: Operating-system dependent
396   #
397   # [:reuseport => true or false]
398   #
399   #   This enables multiple, independently-started unicorn instances to
400   #   bind to the same port (as long as all the processes enable this).
401   #
402   #   This option must be used when unicorn first binds the listen socket.
403   #   It cannot be enabled when a socket is inherited via SIGUSR2
404   #   (but it will remain on if inherited), and it cannot be enabled
405   #   directly via SIGHUP.
406   #
407   #   Note: there is a chance of connections being dropped if
408   #   one of the unicorn instances is stopped while using this.
409   #
410   #   This is supported on *BSD systems and Linux 3.9 or later.
411   #
412   #   ref: https://lwn.net/Articles/542629/
413   #
414   #   Default: false (unset)
415   #
416   # [:tries => Integer]
417   #
418   #   Times to retry binding a socket if it is already in use
419   #
420   #   A negative number indicates we will retry indefinitely, this is
421   #   useful for migrations and upgrades when individual workers
422   #   are binding to different ports.
423   #
424   #   Default: 5
425   #
426   # [:delay => seconds]
427   #
428   #   Seconds to wait between successive +tries+
429   #
430   #   Default: 0.5 seconds
431   #
432   # [:umask => mode]
433   #
434   #   Sets the file mode creation mask for UNIX sockets.  If specified,
435   #   this is usually in octal notation.
436   #
437   #   Typically UNIX domain sockets are created with more liberal
438   #   file permissions than the rest of the application.  By default,
439   #   we create UNIX domain sockets to be readable and writable by
440   #   all local users to give them the same accessibility as
441   #   locally-bound TCP listeners.
442   #
443   #   This has no effect on TCP listeners.
444   #
445   #   Default: 0000 (world-read/writable)
446   #
447   # [:tcp_defer_accept => Integer]
448   #
449   #   Defer accept() until data is ready (Linux-only)
450   #
451   #   For Linux 2.6.32 and later, this is the number of retransmits to
452   #   defer an accept() for if no data arrives, but the client will
453   #   eventually be accepted after the specified number of retransmits
454   #   regardless of whether data is ready.
455   #
456   #   For Linux before 2.6.32, this is a boolean option, and
457   #   accepts are _always_ deferred indefinitely if no data arrives.
458   #   This is similar to <code>:accept_filter => "dataready"</code>
459   #   under FreeBSD.
460   #
461   #   Specifying +true+ is synonymous for the default value(s) below,
462   #   and +false+ or +nil+ is synonymous for a value of zero.
463   #
464   #   A value of +1+ is a good optimization for local networks
465   #   and trusted clients.  There is no good reason to ever
466   #   disable this with a +zero+ value with unicorn.
467   #
468   #   Default: 1
469   #
470   # [:accept_filter => String]
471   #
472   #   defer accept() until data is ready (FreeBSD-only)
473   #
474   #   This enables either the "dataready" or (default) "httpready"
475   #   accept() filter under FreeBSD.  This is intended as an
476   #   optimization to reduce context switches with common GET/HEAD
477   #   requests.
478   #
479   #   There is no good reason to change from the default.
480   #
481   #   Default: "httpready"
482   def listen(address, options = {})
483     address = expand_addr(address)
484     if String === address
485       [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
486         value = options[key] or next
487         Integer === value or
488           raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
489       end
490       [ :tcp_nodelay, :tcp_nopush, :ipv6only, :reuseport ].each do |key|
491         (value = options[key]).nil? and next
492         TrueClass === value || FalseClass === value or
493           raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
494       end
495       unless (value = options[:delay]).nil?
496         Numeric === value or
497           raise ArgumentError, "not numeric: delay=#{value.inspect}"
498       end
499       set[:listener_opts][address].merge!(options)
500     end
502     set[:listeners] << address
503   end
505   # sets the +path+ for the PID file of the unicorn master process
506   def pid(path); set_path(:pid, path); end
508   # Enabling this preloads an application before forking worker
509   # processes.  This allows memory savings when using a
510   # copy-on-write-friendly GC but can cause bad things to happen when
511   # resources like sockets are opened at load time by the master
512   # process and shared by multiple children.  People enabling this are
513   # highly encouraged to look at the before_fork/after_fork hooks to
514   # properly close/reopen sockets.  Files opened for logging do not
515   # have to be reopened as (unbuffered-in-userspace) files opened with
516   # the File::APPEND flag are written to atomically on UNIX.
517   #
518   # In addition to reloading the unicorn-specific config settings,
519   # SIGHUP will reload application code in the working
520   # directory/symlink when workers are gracefully restarted when
521   # preload_app=false (the default).  As reloading the application
522   # sometimes requires RubyGems updates, +Gem.refresh+ is always
523   # called before the application is loaded (for RubyGems users).
524   #
525   # During deployments, care should _always_ be taken to ensure your
526   # applications are properly deployed and running.  Using
527   # preload_app=false (the default) means you _must_ check if
528   # your application is responding properly after a deployment.
529   # Improperly deployed applications can go into a spawn loop
530   # if the application fails to load.  While your children are
531   # in a spawn loop, it is is possible to fix an application
532   # by properly deploying all required code and dependencies.
533   # Using preload_app=true means any application load error will
534   # cause the master process to exit with an error.
536   def preload_app(bool)
537     set_bool(:preload_app, bool)
538   end
540   # Toggles making \env[\"rack.input\"] rewindable.
541   # Disabling rewindability can improve performance by lowering
542   # I/O and memory usage for applications that accept uploads.
543   # Keep in mind that the Rack 1.x spec requires
544   # \env[\"rack.input\"] to be rewindable,
545   # but the Rack 2.x spec does not.
546   #
547   # +rewindable_input+ defaults to +true+ for compatibility.
548   # Setting it to +false+ may be safe for applications and
549   # frameworks developed for Rack 2.x and later.
550   def rewindable_input(bool)
551     set_bool(:rewindable_input, bool)
552   end
554   # The maximum size (in +bytes+) to buffer in memory before
555   # resorting to a temporary file.  Default is 112 kilobytes.
556   # This option has no effect if "rewindable_input" is set to
557   # +false+.
558   def client_body_buffer_size(bytes)
559     set_int(:client_body_buffer_size, bytes, 0)
560   end
562   # When enabled, unicorn will check the client connection by writing
563   # the beginning of the HTTP headers before calling the application.
564   #
565   # This will prevent calling the application for clients who have
566   # disconnected while their connection was queued.
567   #
568   # This only affects clients connecting over Unix domain sockets
569   # and TCP via loopback (127.*.*.*).  It is unlikely to detect
570   # disconnects if the client is on a remote host (even on a fast LAN).
571   #
572   # This option cannot be used in conjunction with :tcp_nopush.
573   def check_client_connection(bool)
574     set_bool(:check_client_connection, bool)
575   end
577   # Allow redirecting $stderr to a given path.  Unlike doing this from
578   # the shell, this allows the unicorn process to know the path its
579   # writing to and rotate the file if it is used for logging.  The
580   # file will be opened with the File::APPEND flag and writes
581   # synchronized to the kernel (but not necessarily to _disk_) so
582   # multiple processes can safely append to it.
583   #
584   # If you are daemonizing and using the default +logger+, it is important
585   # to specify this as errors will otherwise be lost to /dev/null.
586   # Some applications/libraries may also triggering warnings that go to
587   # stderr, and they will end up here.
588   def stderr_path(path)
589     set_path(:stderr_path, path)
590   end
592   # Same as stderr_path, except for $stdout.  Not many Rack applications
593   # write to $stdout, but any that do will have their output written here.
594   # It is safe to point this to the same location a stderr_path.
595   # Like stderr_path, this defaults to /dev/null when daemonized.
596   def stdout_path(path)
597     set_path(:stdout_path, path)
598   end
600   # sets the working directory for Unicorn.  This ensures SIGUSR2 will
601   # start a new instance of Unicorn in this directory.  This may be
602   # a symlink, a common scenario for Capistrano users.  Unlike
603   # all other Unicorn configuration directives, this binds immediately
604   # for error checking and cannot be undone by unsetting it in the
605   # configuration file and reloading.
606   def working_directory(path)
607     # just let chdir raise errors
608     path = File.expand_path(path)
609     if config_file &&
610        ! config_file.start_with?('/') &&
611        ! File.readable?("#{path}/#{config_file}")
612       raise ArgumentError,
613             "config_file=#{config_file} would not be accessible in" \
614             " working_directory=#{path}"
615     end
616     Dir.chdir(path)
617     Unicorn::HttpServer::START_CTX[:cwd] = ENV["PWD"] = path
618   end
620   # Runs worker processes as the specified +user+ and +group+.
621   # The master process always stays running as the user who started it.
622   # This switch will occur after calling the after_fork hook, and only
623   # if the Worker#user method is not called in the after_fork hook
624   # +group+ is optional and will not change if unspecified.
625   #
626   # Do not use Configurator#user if you rely on changing users in the
627   # after_worker_ready hook.  Instead, you need to call Worker#user
628   # directly in after_worker_ready.
629   def user(user, group = nil)
630     # raises ArgumentError on invalid user/group
631     Etc.getpwnam(user)
632     Etc.getgrnam(group) if group
633     set[:user] = [ user, group ]
634   end
636   # expands "unix:path/to/foo" to a socket relative to the current path
637   # expands pathnames of sockets if relative to "~" or "~username"
638   # expands "*:port and ":port" to "0.0.0.0:port"
639   def expand_addr(address) #:nodoc:
640     return "0.0.0.0:#{address}" if Integer === address
641     return address unless String === address
643     case address
644     when %r{\Aunix:(.*)\z}
645       File.expand_path($1)
646     when %r{\A~}
647       File.expand_path(address)
648     when %r{\A(?:\*:)?(\d+)\z}
649       "0.0.0.0:#$1"
650     when %r{\A\[([a-fA-F0-9:]+)\]\z}, %r/\A((?:\d+\.){3}\d+)\z/
651       canonicalize_tcp($1, 80)
652     when %r{\A\[([a-fA-F0-9:]+)\]:(\d+)\z}, %r{\A(.*):(\d+)\z}
653       canonicalize_tcp($1, $2.to_i)
654     else
655       address
656     end
657   end
659 private
660   def set_int(var, n, min) #:nodoc:
661     Integer === n or raise ArgumentError, "not an integer: #{var}=#{n.inspect}"
662     n >= min or raise ArgumentError, "too low (< #{min}): #{var}=#{n.inspect}"
663     set[var] = n
664   end
666   def canonicalize_tcp(addr, port)
667     packed = Socket.pack_sockaddr_in(port, addr)
668     port, addr = Socket.unpack_sockaddr_in(packed)
669     addr.include?(':') ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
670   end
672   def set_path(var, path) #:nodoc:
673     case path
674     when NilClass, String
675       set[var] = path
676     else
677       raise ArgumentError
678     end
679   end
681   def check_bool(var, bool) # :nodoc:
682     case bool
683     when true, false
684       return bool
685     end
686     raise ArgumentError, "#{var}=#{bool.inspect} not a boolean"
687   end
689   def set_bool(var, bool) #:nodoc:
690     set[var] = check_bool(var, bool)
691   end
693   def set_hook(var, my_proc, req_arity = 2) #:nodoc:
694     case my_proc
695     when Proc
696       arity = my_proc.arity
697       (arity == req_arity) or \
698         raise ArgumentError,
699               "#{var}=#{my_proc.inspect} has invalid arity: " \
700               "#{arity} (need #{req_arity})"
701     when NilClass
702       my_proc = DEFAULTS[var]
703     else
704       raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
705     end
706     set[var] = my_proc
707   end
709   # this is called _after_ working_directory is bound.  This only
710   # parses the embedded switches in .ru files
711   # (for "rackup" compatibility)
712   def parse_rackup_file # :nodoc:
713     ru = RACKUP[:file] or return # we only return here in unit tests
715     # :rails means use (old) Rails autodetect
716     if ru == :rails
717       File.readable?('config.ru') or return
718       ru = 'config.ru'
719     end
721     File.readable?(ru) or
722       raise ArgumentError, "rackup file (#{ru}) not readable"
724     # it could be a .rb file, too, we don't parse those manually
725     ru.end_with?('.ru') or return
727     /^#\\(.*)/ =~ File.read(ru) or return
728     RACKUP[:optparse].parse!($1.split(/\s+/))
730     if RACKUP[:daemonize]
731       # unicorn_rails wants a default pid path, (not plain 'unicorn')
732       if after_reload
733         spid = set[:pid]
734         pid('tmp/pids/unicorn.pid') if spid.nil? || spid == :unset
735       end
736       unless RACKUP[:daemonized]
737         Unicorn::Launcher.daemonize!(RACKUP[:options])
738         RACKUP[:ready_pipe] = RACKUP[:options].delete(:ready_pipe)
739       end
740     end
741   end