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