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