configurator: truncate timeouts to 32-bit LONG_MAX
[unicorn.git] / lib / unicorn / configurator.rb
blob2c5fe86ccd6700efd090fe7fbb55720c880259b5
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     max = 0x7fffffff
190     set[:timeout] = seconds > max ? max : seconds
191   end
193   # sets the current number of worker_processes to +nr+.  Each worker
194   # process will serve exactly one client at a time.  You can
195   # increment or decrement this value at runtime by sending SIGTTIN
196   # or SIGTTOU respectively to the master process without reloading
197   # the rest of your Unicorn configuration.  See the SIGNALS document
198   # for more information.
199   def worker_processes(nr)
200     set_int(:worker_processes, nr, 1)
201   end
203   # sets listeners to the given +addresses+, replacing or augmenting the
204   # current set.  This is for the global listener pool shared by all
205   # worker processes.  For per-worker listeners, see the after_fork example
206   # This is for internal API use only, do not use it in your Unicorn
207   # config file.  Use listen instead.
208   def listeners(addresses) # :nodoc:
209     Array === addresses or addresses = Array(addresses)
210     addresses.map! { |addr| expand_addr(addr) }
211     set[:listeners] = addresses
212   end
214   # Adds an +address+ to the existing listener set.  May be specified more
215   # than once.  +address+ may be an Integer port number for a TCP port, an
216   # "IP_ADDRESS:PORT" for TCP listeners or a pathname for UNIX domain sockets.
217   #
218   #   listen 3000 # listen to port 3000 on all TCP interfaces
219   #   listen "127.0.0.1:3000"  # listen to port 3000 on the loopback interface
220   #   listen "/tmp/.unicorn.sock" # listen on the given Unix domain socket
221   #   listen "[::1]:3000" # listen to port 3000 on the IPv6 loopback interface
222   #
223   # The following options may be specified (but are generally not needed):
224   #
225   # [:backlog => number of clients]
226   #
227   #   This is the backlog of the listen() syscall.
228   #
229   #   Some operating systems allow negative values here to specify the
230   #   maximum allowable value.  In most cases, this number is only
231   #   recommendation and there are other OS-specific tunables and
232   #   variables that can affect this number.  See the listen(2)
233   #   syscall documentation of your OS for the exact semantics of
234   #   this.
235   #
236   #   If you are running unicorn on multiple machines, lowering this number
237   #   can help your load balancer detect when a machine is overloaded
238   #   and give requests to a different machine.
239   #
240   #   Default: 1024
241   #
242   # [:rcvbuf => bytes, :sndbuf => bytes]
243   #
244   #   Maximum receive and send buffer sizes (in bytes) of sockets.
245   #
246   #   These correspond to the SO_RCVBUF and SO_SNDBUF settings which
247   #   can be set via the setsockopt(2) syscall.  Some kernels
248   #   (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
249   #   there is no need (and it is sometimes detrimental) to specify them.
250   #
251   #   See the socket API documentation of your operating system
252   #   to determine the exact semantics of these settings and
253   #   other operating system-specific knobs where they can be
254   #   specified.
255   #
256   #   Defaults: operating system defaults
257   #
258   # [:tcp_nodelay => true or false]
259   #
260   #   Disables Nagle's algorithm on TCP sockets if +true+.
261   #
262   #   Setting this to +true+ can make streaming responses in Rails 3.1
263   #   appear more quickly at the cost of slightly higher bandwidth usage.
264   #   The effect of this option is most visible if nginx is not used,
265   #   but nginx remains highly recommended with \Unicorn.
266   #
267   #   This has no effect on UNIX sockets.
268   #
269   #   Default: +true+ (Nagle's algorithm disabled) in \Unicorn,
270   #   +true+ in Rainbows!  This defaulted to +false+ in \Unicorn
271   #   3.x
272   #
273   # [:tcp_nopush => true or false]
274   #
275   #   Enables/disables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
276   #
277   #   This prevents partial TCP frames from being sent out and reduces
278   #   wakeups in nginx if it is on a different machine.  Since \Unicorn
279   #   is only designed for applications that send the response body
280   #   quickly without keepalive, sockets will always be flushed on close
281   #   to prevent delays.
282   #
283   #   This has no effect on UNIX sockets.
284   #
285   #   Default: +false+
286   #   This defaulted to +true+ in \Unicorn 3.4 - 3.7
287   #
288   # [:ipv6only => true or false]
289   #
290   #   This option makes IPv6-capable TCP listeners IPv6-only and unable
291   #   to receive IPv4 queries on dual-stack systems.  A separate IPv4-only
292   #   listener is required if this is true.
293   #
294   #   This option is only available for Ruby 1.9.2 and later.
295   #
296   #   Enabling this option for the IPv6-only listener and having a
297   #   separate IPv4 listener is recommended if you wish to support IPv6
298   #   on the same TCP port.  Otherwise, the value of \env[\"REMOTE_ADDR\"]
299   #   will appear as an ugly IPv4-mapped-IPv6 address for IPv4 clients
300   #   (e.g ":ffff:10.0.0.1" instead of just "10.0.0.1").
301   #
302   #   Default: Operating-system dependent
303   #
304   # [:tries => Integer]
305   #
306   #   Times to retry binding a socket if it is already in use
307   #
308   #   A negative number indicates we will retry indefinitely, this is
309   #   useful for migrations and upgrades when individual workers
310   #   are binding to different ports.
311   #
312   #   Default: 5
313   #
314   # [:delay => seconds]
315   #
316   #   Seconds to wait between successive +tries+
317   #
318   #   Default: 0.5 seconds
319   #
320   # [:umask => mode]
321   #
322   #   Sets the file mode creation mask for UNIX sockets.  If specified,
323   #   this is usually in octal notation.
324   #
325   #   Typically UNIX domain sockets are created with more liberal
326   #   file permissions than the rest of the application.  By default,
327   #   we create UNIX domain sockets to be readable and writable by
328   #   all local users to give them the same accessibility as
329   #   locally-bound TCP listeners.
330   #
331   #   This has no effect on TCP listeners.
332   #
333   #   Default: 0000 (world-read/writable)
334   #
335   # [:tcp_defer_accept => Integer]
336   #
337   #   Defer accept() until data is ready (Linux-only)
338   #
339   #   For Linux 2.6.32 and later, this is the number of retransmits to
340   #   defer an accept() for if no data arrives, but the client will
341   #   eventually be accepted after the specified number of retransmits
342   #   regardless of whether data is ready.
343   #
344   #   For Linux before 2.6.32, this is a boolean option, and
345   #   accepts are _always_ deferred indefinitely if no data arrives.
346   #   This is similar to <code>:accept_filter => "dataready"</code>
347   #   under FreeBSD.
348   #
349   #   Specifying +true+ is synonymous for the default value(s) below,
350   #   and +false+ or +nil+ is synonymous for a value of zero.
351   #
352   #   A value of +1+ is a good optimization for local networks
353   #   and trusted clients.  For Rainbows! and Zbatery users, a higher
354   #   value (e.g. +60+) provides more protection against some
355   #   denial-of-service attacks.  There is no good reason to ever
356   #   disable this with a +zero+ value when serving HTTP.
357   #
358   #   Default: 1 retransmit for \Unicorn, 60 for Rainbows! 0.95.0\+
359   #
360   # [:accept_filter => String]
361   #
362   #   defer accept() until data is ready (FreeBSD-only)
363   #
364   #   This enables either the "dataready" or (default) "httpready"
365   #   accept() filter under FreeBSD.  This is intended as an
366   #   optimization to reduce context switches with common GET/HEAD
367   #   requests.  For Rainbows! and Zbatery users, this provides
368   #   some protection against certain denial-of-service attacks, too.
369   #
370   #   There is no good reason to change from the default.
371   #
372   #   Default: "httpready"
373   def listen(address, options = {})
374     address = expand_addr(address)
375     if String === address
376       [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
377         value = options[key] or next
378         Integer === value or
379           raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
380       end
381       [ :tcp_nodelay, :tcp_nopush, :ipv6only ].each do |key|
382         (value = options[key]).nil? and next
383         TrueClass === value || FalseClass === value or
384           raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
385       end
386       unless (value = options[:delay]).nil?
387         Numeric === value or
388           raise ArgumentError, "not numeric: delay=#{value.inspect}"
389       end
390       set[:listener_opts][address].merge!(options)
391     end
393     set[:listeners] << address
394   end
396   # sets the +path+ for the PID file of the unicorn master process
397   def pid(path); set_path(:pid, path); end
399   # Enabling this preloads an application before forking worker
400   # processes.  This allows memory savings when using a
401   # copy-on-write-friendly GC but can cause bad things to happen when
402   # resources like sockets are opened at load time by the master
403   # process and shared by multiple children.  People enabling this are
404   # highly encouraged to look at the before_fork/after_fork hooks to
405   # properly close/reopen sockets.  Files opened for logging do not
406   # have to be reopened as (unbuffered-in-userspace) files opened with
407   # the File::APPEND flag are written to atomically on UNIX.
408   #
409   # In addition to reloading the unicorn-specific config settings,
410   # SIGHUP will reload application code in the working
411   # directory/symlink when workers are gracefully restarted when
412   # preload_app=false (the default).  As reloading the application
413   # sometimes requires RubyGems updates, +Gem.refresh+ is always
414   # called before the application is loaded (for RubyGems users).
415   #
416   # During deployments, care should _always_ be taken to ensure your
417   # applications are properly deployed and running.  Using
418   # preload_app=false (the default) means you _must_ check if
419   # your application is responding properly after a deployment.
420   # Improperly deployed applications can go into a spawn loop
421   # if the application fails to load.  While your children are
422   # in a spawn loop, it is is possible to fix an application
423   # by properly deploying all required code and dependencies.
424   # Using preload_app=true means any application load error will
425   # cause the master process to exit with an error.
427   def preload_app(bool)
428     set_bool(:preload_app, bool)
429   end
431   # Toggles making \env[\"rack.input\"] rewindable.
432   # Disabling rewindability can improve performance by lowering
433   # I/O and memory usage for applications that accept uploads.
434   # Keep in mind that the Rack 1.x spec requires
435   # \env[\"rack.input\"] to be rewindable, so this allows
436   # intentionally violating the current Rack 1.x spec.
437   #
438   # +rewindable_input+ defaults to +true+ when used with Rack 1.x for
439   # Rack conformance.  When Rack 2.x is finalized, this will most
440   # likely default to +false+ while still conforming to the newer
441   # (less demanding) spec.
442   def rewindable_input(bool)
443     set_bool(:rewindable_input, bool)
444   end
446   # The maximum size (in +bytes+) to buffer in memory before
447   # resorting to a temporary file.  Default is 112 kilobytes.
448   # This option has no effect if "rewindable_input" is set to
449   # +false+.
450   def client_body_buffer_size(bytes)
451     set_int(:client_body_buffer_size, bytes, 0)
452   end
454   # Allow redirecting $stderr to a given path.  Unlike doing this from
455   # the shell, this allows the unicorn process to know the path its
456   # writing to and rotate the file if it is used for logging.  The
457   # file will be opened with the File::APPEND flag and writes
458   # synchronized to the kernel (but not necessarily to _disk_) so
459   # multiple processes can safely append to it.
460   #
461   # If you are daemonizing and using the default +logger+, it is important
462   # to specify this as errors will otherwise be lost to /dev/null.
463   # Some applications/libraries may also triggering warnings that go to
464   # stderr, and they will end up here.
465   def stderr_path(path)
466     set_path(:stderr_path, path)
467   end
469   # Same as stderr_path, except for $stdout.  Not many Rack applications
470   # write to $stdout, but any that do will have their output written here.
471   # It is safe to point this to the same location a stderr_path.
472   # Like stderr_path, this defaults to /dev/null when daemonized.
473   def stdout_path(path)
474     set_path(:stdout_path, path)
475   end
477   # sets the working directory for Unicorn.  This ensures SIGUSR2 will
478   # start a new instance of Unicorn in this directory.  This may be
479   # a symlink, a common scenario for Capistrano users.  Unlike
480   # all other Unicorn configuration directives, this binds immediately
481   # for error checking and cannot be undone by unsetting it in the
482   # configuration file and reloading.
483   def working_directory(path)
484     # just let chdir raise errors
485     path = File.expand_path(path)
486     if config_file &&
487        config_file[0] != ?/ &&
488        ! File.readable?("#{path}/#{config_file}")
489       raise ArgumentError,
490             "config_file=#{config_file} would not be accessible in" \
491             " working_directory=#{path}"
492     end
493     Dir.chdir(path)
494     Unicorn::HttpServer::START_CTX[:cwd] = ENV["PWD"] = path
495   end
497   # Runs worker processes as the specified +user+ and +group+.
498   # The master process always stays running as the user who started it.
499   # This switch will occur after calling the after_fork hook, and only
500   # if the Worker#user method is not called in the after_fork hook
501   # +group+ is optional and will not change if unspecified.
502   def user(user, group = nil)
503     # raises ArgumentError on invalid user/group
504     Etc.getpwnam(user)
505     Etc.getgrnam(group) if group
506     set[:user] = [ user, group ]
507   end
509   # Sets whether or not the parser will trust X-Forwarded-Proto and
510   # X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
511   # Rainbows!/Zbatery installations facing untrusted clients directly
512   # should set this to +false+.  This is +true+ by default as Unicorn
513   # is designed to only sit behind trusted nginx proxies.
514   #
515   # This has never been publically documented and is subject to removal
516   # in future releases.
517   def trust_x_forwarded(bool) # :nodoc:
518     set_bool(:trust_x_forwarded, bool)
519   end
521   # expands "unix:path/to/foo" to a socket relative to the current path
522   # expands pathnames of sockets if relative to "~" or "~username"
523   # expands "*:port and ":port" to "0.0.0.0:port"
524   def expand_addr(address) #:nodoc:
525     return "0.0.0.0:#{address}" if Integer === address
526     return address unless String === address
528     case address
529     when %r{\Aunix:(.*)\z}
530       File.expand_path($1)
531     when %r{\A~}
532       File.expand_path(address)
533     when %r{\A(?:\*:)?(\d+)\z}
534       "0.0.0.0:#$1"
535     when %r{\A\[([a-fA-F0-9:]+)\]\z}, %r/\A((?:\d+\.){3}\d+)\z/
536       canonicalize_tcp($1, 80)
537     when %r{\A\[([a-fA-F0-9:]+)\]:(\d+)\z}, %r{\A(.*):(\d+)\z}
538       canonicalize_tcp($1, $2.to_i)
539     else
540       address
541     end
542   end
544 private
545   def set_int(var, n, min) #:nodoc:
546     Integer === n or raise ArgumentError, "not an integer: #{var}=#{n.inspect}"
547     n >= min or raise ArgumentError, "too low (< #{min}): #{var}=#{n.inspect}"
548     set[var] = n
549   end
551   def canonicalize_tcp(addr, port)
552     packed = Socket.pack_sockaddr_in(port, addr)
553     port, addr = Socket.unpack_sockaddr_in(packed)
554     /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
555   end
557   def set_path(var, path) #:nodoc:
558     case path
559     when NilClass, String
560       set[var] = path
561     else
562       raise ArgumentError
563     end
564   end
566   def set_bool(var, bool) #:nodoc:
567     case bool
568     when true, false
569       set[var] = bool
570     else
571       raise ArgumentError, "#{var}=#{bool.inspect} not a boolean"
572     end
573   end
575   def set_hook(var, my_proc, req_arity = 2) #:nodoc:
576     case my_proc
577     when Proc
578       arity = my_proc.arity
579       (arity == req_arity) or \
580         raise ArgumentError,
581               "#{var}=#{my_proc.inspect} has invalid arity: " \
582               "#{arity} (need #{req_arity})"
583     when NilClass
584       my_proc = DEFAULTS[var]
585     else
586       raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
587     end
588     set[var] = my_proc
589   end
591   # this is called _after_ working_directory is bound.  This only
592   # parses the embedded switches in .ru files
593   # (for "rackup" compatibility)
594   def parse_rackup_file # :nodoc:
595     ru = RACKUP[:file] or return # we only return here in unit tests
597     # :rails means use (old) Rails autodetect
598     if ru == :rails
599       File.readable?('config.ru') or return
600       ru = 'config.ru'
601     end
603     File.readable?(ru) or
604       raise ArgumentError, "rackup file (#{ru}) not readable"
606     # it could be a .rb file, too, we don't parse those manually
607     ru =~ /\.ru\z/ or return
609     /^#\\(.*)/ =~ File.read(ru) or return
610     RACKUP[:optparse].parse!($1.split(/\s+/))
612     if RACKUP[:daemonize]
613       # unicorn_rails wants a default pid path, (not plain 'unicorn')
614       if after_reload
615         spid = set[:pid]
616         pid('tmp/pids/unicorn.pid') if spid.nil? || spid == :unset
617       end
618       unless RACKUP[:daemonized]
619         Unicorn::Launcher.daemonize!(RACKUP[:options])
620         RACKUP[:ready_pipe] = RACKUP[:options].delete(:ready_pipe)
621       end
622     end
623   end