1 # -*- encoding: binary -*-
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
16 include Unicorn::SSLConfigurator
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...
26 :host => Unicorn::Const::DEFAULT_HOST,
27 :port => Unicorn::Const::DEFAULT_PORT,
28 :set_listener => false,
29 :options => { :listeners => [] }
32 # Default settings for Unicorn
35 :logger => Logger.new($stderr),
36 :worker_processes => 1,
37 :after_fork => lambda { |server, worker|
38 server.logger.info("worker=#{worker.nr} spawned pid=#{$$}")
40 :before_fork => lambda { |server, worker|
41 server.logger.info("worker=#{worker.nr} spawning...")
43 :before_exec => lambda { |server|
44 server.logger.info("forked child re-executing...")
47 :preload_app => false,
48 :check_client_connection => false,
49 :rewindable_input => true, # for Rack 2.x: (Rack::VERSION[0] <= 1),
50 :client_body_buffer_size => Unicorn::Const::MAX_BODY,
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] = []
70 def reload(merge_defaults = true) #:nodoc:
71 if merge_defaults && @use_defaults
72 set.merge!(DEFAULTS) if @use_defaults
74 instance_eval(File.read(config_file), config_file) if config_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"
94 def commit!(server, options = {}) #:nodoc:
95 skip = options[:skip] || []
96 if ready_pipe = RACKUP.delete(:ready_pipe)
97 server.ready_pipe = ready_pipe
99 if set[:check_client_connection]
100 set[:listeners].each do |address|
101 if set[:listener_opts][address][:tcp_nopush] == true
103 "check_client_connection is incompatible with tcp_nopush:true"
107 set.each do |key, value|
108 value == :unset and next
109 skip.include?(key) and next
110 server.__send__("#{key}=", value)
114 def [](key) # :nodoc:
118 # sets object to the +obj+ Logger-like object. The new Logger-like
119 # object must respond to the following methods:
125 # The default Logger will log its output to the path specified
126 # by +stderr_path+. If you're running Unicorn daemonized, then
127 # you must specify a path to prevent error messages from going
130 %w(debug info warn error fatal).each do |m|
131 obj.respond_to?(m) and next
132 raise ArgumentError, "logger=#{obj} does not respond to method=#{m}"
138 # sets after_fork hook to a given block. This block will be called by
139 # the worker after forking. The following is an example hook which adds
140 # a per-process listener to every worker:
142 # after_fork do |server,worker|
143 # # per-process listener ports for debugging/admin:
144 # addr = "127.0.0.1:#{9293 + worker.nr}"
146 # # the negative :tries parameter indicates we will retry forever
147 # # waiting on the existing process to exit with a 5 second :delay
148 # # Existing options for Unicorn::Configurator#listen such as
149 # # :backlog, :rcvbuf, :sndbuf are available here as well.
150 # server.listen(addr, :tries => -1, :delay => 5, :backlog => 128)
152 def after_fork(*args, &block)
153 set_hook(:after_fork, block_given? ? block : args[0])
156 # sets before_fork got be a given Proc object. This Proc
157 # object will be called by the master process before forking
159 def before_fork(*args, &block)
160 set_hook(:before_fork, block_given? ? block : args[0])
163 # sets the before_exec hook to a given Proc object. This
164 # Proc object will be called by the master process right
165 # before exec()-ing the new unicorn binary. This is useful
166 # for freeing certain OS resources that you do NOT wish to
167 # share with the reexeced child process.
168 # There is no corresponding after_exec hook (for obvious reasons).
169 def before_exec(*args, &block)
170 set_hook(:before_exec, block_given? ? block : args[0], 1)
173 # sets the timeout of worker processes to +seconds+. Workers
174 # handling the request/app.call/response cycle taking longer than
175 # this time period will be forcibly killed (via SIGKILL). This
176 # timeout is enforced by the master process itself and not subject
177 # to the scheduling limitations by the worker process. Due the
178 # low-complexity, low-overhead implementation, timeouts of less
179 # than 3.0 seconds can be considered inaccurate and unsafe.
181 # For running Unicorn behind nginx, it is recommended to set
182 # "fail_timeout=0" for in your nginx configuration like this
183 # to have nginx always retry backends that may have had workers
184 # SIGKILL-ed due to timeouts.
186 # # See http://wiki.nginx.org/NginxHttpUpstreamModule for more details
187 # # on nginx upstream configuration:
188 # upstream unicorn_backend {
189 # # for UNIX domain socket setups:
190 # server unix:/path/to/.unicorn.sock fail_timeout=0;
193 # server 192.168.0.7:8080 fail_timeout=0;
194 # server 192.168.0.8:8080 fail_timeout=0;
195 # server 192.168.0.9:8080 fail_timeout=0;
198 set_int(:timeout, seconds, 3)
199 # POSIX says 31 days is the smallest allowed maximum timeout for select()
200 max = 30 * 60 * 60 * 24
201 set[:timeout] = seconds > max ? max : seconds
204 # sets the current number of worker_processes to +nr+. Each worker
205 # process will serve exactly one client at a time. You can
206 # increment or decrement this value at runtime by sending SIGTTIN
207 # or SIGTTOU respectively to the master process without reloading
208 # the rest of your Unicorn configuration. See the SIGNALS document
209 # for more information.
210 def worker_processes(nr)
211 set_int(:worker_processes, nr, 1)
214 # sets listeners to the given +addresses+, replacing or augmenting the
215 # current set. This is for the global listener pool shared by all
216 # worker processes. For per-worker listeners, see the after_fork example
217 # This is for internal API use only, do not use it in your Unicorn
218 # config file. Use listen instead.
219 def listeners(addresses) # :nodoc:
220 Array === addresses or addresses = Array(addresses)
221 addresses.map! { |addr| expand_addr(addr) }
222 set[:listeners] = addresses
225 # Adds an +address+ to the existing listener set. May be specified more
226 # than once. +address+ may be an Integer port number for a TCP port, an
227 # "IP_ADDRESS:PORT" for TCP listeners or a pathname for UNIX domain sockets.
229 # listen 3000 # listen to port 3000 on all TCP interfaces
230 # listen "127.0.0.1:3000" # listen to port 3000 on the loopback interface
231 # listen "/path/to/.unicorn.sock" # listen on the given Unix domain socket
232 # listen "[::1]:3000" # listen to port 3000 on the IPv6 loopback interface
234 # When using Unix domain sockets, be sure:
235 # 1) the path matches the one used by nginx
236 # 2) uses the same filesystem namespace as the nginx process
237 # For systemd users using PrivateTmp=true (for either nginx or unicorn),
238 # this means Unix domain sockets must not be placed in /tmp
240 # The following options may be specified (but are generally not needed):
242 # [:backlog => number of clients]
244 # This is the backlog of the listen() syscall.
246 # Some operating systems allow negative values here to specify the
247 # maximum allowable value. In most cases, this number is only
248 # recommendation and there are other OS-specific tunables and
249 # variables that can affect this number. See the listen(2)
250 # syscall documentation of your OS for the exact semantics of
253 # If you are running unicorn on multiple machines, lowering this number
254 # can help your load balancer detect when a machine is overloaded
255 # and give requests to a different machine.
259 # [:rcvbuf => bytes, :sndbuf => bytes]
261 # Maximum receive and send buffer sizes (in bytes) of sockets.
263 # These correspond to the SO_RCVBUF and SO_SNDBUF settings which
264 # can be set via the setsockopt(2) syscall. Some kernels
265 # (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
266 # there is no need (and it is sometimes detrimental) to specify them.
268 # See the socket API documentation of your operating system
269 # to determine the exact semantics of these settings and
270 # other operating system-specific knobs where they can be
273 # Defaults: operating system defaults
275 # [:tcp_nodelay => true or false]
277 # Disables Nagle's algorithm on TCP sockets if +true+.
279 # Setting this to +true+ can make streaming responses in Rails 3.1
280 # appear more quickly at the cost of slightly higher bandwidth usage.
281 # The effect of this option is most visible if nginx is not used,
282 # but nginx remains highly recommended with \Unicorn.
284 # This has no effect on UNIX sockets.
286 # Default: +true+ (Nagle's algorithm disabled) in \Unicorn,
287 # +true+ in Rainbows! This defaulted to +false+ in \Unicorn
290 # [:tcp_nopush => true or false]
292 # Enables/disables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
294 # This prevents partial TCP frames from being sent out and reduces
295 # wakeups in nginx if it is on a different machine. Since \Unicorn
296 # is only designed for applications that send the response body
297 # quickly without keepalive, sockets will always be flushed on close
300 # This has no effect on UNIX sockets.
303 # This defaulted to +true+ in \Unicorn 3.4 - 3.7
305 # [:ipv6only => true or false]
307 # This option makes IPv6-capable TCP listeners IPv6-only and unable
308 # to receive IPv4 queries on dual-stack systems. A separate IPv4-only
309 # listener is required if this is true.
311 # This option is only available for Ruby 1.9.2 and later.
313 # Enabling this option for the IPv6-only listener and having a
314 # separate IPv4 listener is recommended if you wish to support IPv6
315 # on the same TCP port. Otherwise, the value of \env[\"REMOTE_ADDR\"]
316 # will appear as an ugly IPv4-mapped-IPv6 address for IPv4 clients
317 # (e.g ":ffff:10.0.0.1" instead of just "10.0.0.1").
319 # Default: Operating-system dependent
321 # [:reuseport => true or false]
323 # This enables multiple, independently-started unicorn instances to
324 # bind to the same port (as long as all the processes enable this).
326 # This option must be used when unicorn first binds the listen socket.
327 # It cannot be enabled when a socket is inherited via SIGUSR2
328 # (but it will remain on if inherited), and it cannot be enabled
329 # directly via SIGHUP.
331 # Note: there is a chance of connections being dropped if
332 # one of the unicorn instances is stopped while using this.
334 # This is supported on *BSD systems and Linux 3.9 or later.
336 # ref: https://lwn.net/Articles/542629/
338 # Default: false (unset)
340 # [:tries => Integer]
342 # Times to retry binding a socket if it is already in use
344 # A negative number indicates we will retry indefinitely, this is
345 # useful for migrations and upgrades when individual workers
346 # are binding to different ports.
350 # [:delay => seconds]
352 # Seconds to wait between successive +tries+
354 # Default: 0.5 seconds
358 # Sets the file mode creation mask for UNIX sockets. If specified,
359 # this is usually in octal notation.
361 # Typically UNIX domain sockets are created with more liberal
362 # file permissions than the rest of the application. By default,
363 # we create UNIX domain sockets to be readable and writable by
364 # all local users to give them the same accessibility as
365 # locally-bound TCP listeners.
367 # This has no effect on TCP listeners.
369 # Default: 0000 (world-read/writable)
371 # [:tcp_defer_accept => Integer]
373 # Defer accept() until data is ready (Linux-only)
375 # For Linux 2.6.32 and later, this is the number of retransmits to
376 # defer an accept() for if no data arrives, but the client will
377 # eventually be accepted after the specified number of retransmits
378 # regardless of whether data is ready.
380 # For Linux before 2.6.32, this is a boolean option, and
381 # accepts are _always_ deferred indefinitely if no data arrives.
382 # This is similar to <code>:accept_filter => "dataready"</code>
385 # Specifying +true+ is synonymous for the default value(s) below,
386 # and +false+ or +nil+ is synonymous for a value of zero.
388 # A value of +1+ is a good optimization for local networks
389 # and trusted clients. For Rainbows! and Zbatery users, a higher
390 # value (e.g. +60+) provides more protection against some
391 # denial-of-service attacks. There is no good reason to ever
392 # disable this with a +zero+ value when serving HTTP.
394 # Default: 1 retransmit for \Unicorn, 60 for Rainbows! 0.95.0\+
396 # [:accept_filter => String]
398 # defer accept() until data is ready (FreeBSD-only)
400 # This enables either the "dataready" or (default) "httpready"
401 # accept() filter under FreeBSD. This is intended as an
402 # optimization to reduce context switches with common GET/HEAD
403 # requests. For Rainbows! and Zbatery users, this provides
404 # some protection against certain denial-of-service attacks, too.
406 # There is no good reason to change from the default.
408 # Default: "httpready"
409 def listen(address, options = {})
410 address = expand_addr(address)
411 if String === address
412 [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
413 value = options[key] or next
415 raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
417 [ :tcp_nodelay, :tcp_nopush, :ipv6only, :reuseport ].each do |key|
418 (value = options[key]).nil? and next
419 TrueClass === value || FalseClass === value or
420 raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
422 unless (value = options[:delay]).nil?
424 raise ArgumentError, "not numeric: delay=#{value.inspect}"
426 set[:listener_opts][address].merge!(options)
429 set[:listeners] << address
432 # sets the +path+ for the PID file of the unicorn master process
433 def pid(path); set_path(:pid, path); end
435 # Enabling this preloads an application before forking worker
436 # processes. This allows memory savings when using a
437 # copy-on-write-friendly GC but can cause bad things to happen when
438 # resources like sockets are opened at load time by the master
439 # process and shared by multiple children. People enabling this are
440 # highly encouraged to look at the before_fork/after_fork hooks to
441 # properly close/reopen sockets. Files opened for logging do not
442 # have to be reopened as (unbuffered-in-userspace) files opened with
443 # the File::APPEND flag are written to atomically on UNIX.
445 # In addition to reloading the unicorn-specific config settings,
446 # SIGHUP will reload application code in the working
447 # directory/symlink when workers are gracefully restarted when
448 # preload_app=false (the default). As reloading the application
449 # sometimes requires RubyGems updates, +Gem.refresh+ is always
450 # called before the application is loaded (for RubyGems users).
452 # During deployments, care should _always_ be taken to ensure your
453 # applications are properly deployed and running. Using
454 # preload_app=false (the default) means you _must_ check if
455 # your application is responding properly after a deployment.
456 # Improperly deployed applications can go into a spawn loop
457 # if the application fails to load. While your children are
458 # in a spawn loop, it is is possible to fix an application
459 # by properly deploying all required code and dependencies.
460 # Using preload_app=true means any application load error will
461 # cause the master process to exit with an error.
463 def preload_app(bool)
464 set_bool(:preload_app, bool)
467 # Toggles making \env[\"rack.input\"] rewindable.
468 # Disabling rewindability can improve performance by lowering
469 # I/O and memory usage for applications that accept uploads.
470 # Keep in mind that the Rack 1.x spec requires
471 # \env[\"rack.input\"] to be rewindable, so this allows
472 # intentionally violating the current Rack 1.x spec.
474 # +rewindable_input+ defaults to +true+ when used with Rack 1.x for
475 # Rack conformance. When Rack 2.x is finalized, this will most
476 # likely default to +false+ while still conforming to the newer
477 # (less demanding) spec.
478 def rewindable_input(bool)
479 set_bool(:rewindable_input, bool)
482 # The maximum size (in +bytes+) to buffer in memory before
483 # resorting to a temporary file. Default is 112 kilobytes.
484 # This option has no effect if "rewindable_input" is set to
486 def client_body_buffer_size(bytes)
487 set_int(:client_body_buffer_size, bytes, 0)
490 # When enabled, unicorn will check the client connection by writing
491 # the beginning of the HTTP headers before calling the application.
493 # This will prevent calling the application for clients who have
494 # disconnected while their connection was queued.
496 # This only affects clients connecting over Unix domain sockets
497 # and TCP via loopback (127.*.*.*). It is unlikely to detect
498 # disconnects if the client is on a remote host (even on a fast LAN).
500 # This option cannot be used in conjunction with :tcp_nopush.
501 def check_client_connection(bool)
502 set_bool(:check_client_connection, bool)
505 # Allow redirecting $stderr to a given path. Unlike doing this from
506 # the shell, this allows the unicorn process to know the path its
507 # writing to and rotate the file if it is used for logging. The
508 # file will be opened with the File::APPEND flag and writes
509 # synchronized to the kernel (but not necessarily to _disk_) so
510 # multiple processes can safely append to it.
512 # If you are daemonizing and using the default +logger+, it is important
513 # to specify this as errors will otherwise be lost to /dev/null.
514 # Some applications/libraries may also triggering warnings that go to
515 # stderr, and they will end up here.
516 def stderr_path(path)
517 set_path(:stderr_path, path)
520 # Same as stderr_path, except for $stdout. Not many Rack applications
521 # write to $stdout, but any that do will have their output written here.
522 # It is safe to point this to the same location a stderr_path.
523 # Like stderr_path, this defaults to /dev/null when daemonized.
524 def stdout_path(path)
525 set_path(:stdout_path, path)
528 # sets the working directory for Unicorn. This ensures SIGUSR2 will
529 # start a new instance of Unicorn in this directory. This may be
530 # a symlink, a common scenario for Capistrano users. Unlike
531 # all other Unicorn configuration directives, this binds immediately
532 # for error checking and cannot be undone by unsetting it in the
533 # configuration file and reloading.
534 def working_directory(path)
535 # just let chdir raise errors
536 path = File.expand_path(path)
538 config_file[0] != ?/ &&
539 ! File.readable?("#{path}/#{config_file}")
541 "config_file=#{config_file} would not be accessible in" \
542 " working_directory=#{path}"
545 Unicorn::HttpServer::START_CTX[:cwd] = ENV["PWD"] = path
548 # Runs worker processes as the specified +user+ and +group+.
549 # The master process always stays running as the user who started it.
550 # This switch will occur after calling the after_fork hook, and only
551 # if the Worker#user method is not called in the after_fork hook
552 # +group+ is optional and will not change if unspecified.
553 def user(user, group = nil)
554 # raises ArgumentError on invalid user/group
556 Etc.getgrnam(group) if group
557 set[:user] = [ user, group ]
560 # expands "unix:path/to/foo" to a socket relative to the current path
561 # expands pathnames of sockets if relative to "~" or "~username"
562 # expands "*:port and ":port" to "0.0.0.0:port"
563 def expand_addr(address) #:nodoc:
564 return "0.0.0.0:#{address}" if Integer === address
565 return address unless String === address
568 when %r{\Aunix:(.*)\z}
571 File.expand_path(address)
572 when %r{\A(?:\*:)?(\d+)\z}
574 when %r{\A\[([a-fA-F0-9:]+)\]\z}, %r/\A((?:\d+\.){3}\d+)\z/
575 canonicalize_tcp($1, 80)
576 when %r{\A\[([a-fA-F0-9:]+)\]:(\d+)\z}, %r{\A(.*):(\d+)\z}
577 canonicalize_tcp($1, $2.to_i)
584 def set_int(var, n, min) #:nodoc:
585 Integer === n or raise ArgumentError, "not an integer: #{var}=#{n.inspect}"
586 n >= min or raise ArgumentError, "too low (< #{min}): #{var}=#{n.inspect}"
590 def canonicalize_tcp(addr, port)
591 packed = Socket.pack_sockaddr_in(port, addr)
592 port, addr = Socket.unpack_sockaddr_in(packed)
593 /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
596 def set_path(var, path) #:nodoc:
598 when NilClass, String
605 def check_bool(var, bool) # :nodoc:
610 raise ArgumentError, "#{var}=#{bool.inspect} not a boolean"
613 def set_bool(var, bool) #:nodoc:
614 set[var] = check_bool(var, bool)
617 def set_hook(var, my_proc, req_arity = 2) #:nodoc:
620 arity = my_proc.arity
621 (arity == req_arity) or \
623 "#{var}=#{my_proc.inspect} has invalid arity: " \
624 "#{arity} (need #{req_arity})"
626 my_proc = DEFAULTS[var]
628 raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
633 # this is called _after_ working_directory is bound. This only
634 # parses the embedded switches in .ru files
635 # (for "rackup" compatibility)
636 def parse_rackup_file # :nodoc:
637 ru = RACKUP[:file] or return # we only return here in unit tests
639 # :rails means use (old) Rails autodetect
641 File.readable?('config.ru') or return
645 File.readable?(ru) or
646 raise ArgumentError, "rackup file (#{ru}) not readable"
648 # it could be a .rb file, too, we don't parse those manually
649 ru =~ /\.ru\z/ or return
651 /^#\\(.*)/ =~ File.read(ru) or return
652 RACKUP[:optparse].parse!($1.split(/\s+/))
654 if RACKUP[:daemonize]
655 # unicorn_rails wants a default pid path, (not plain 'unicorn')
658 pid('tmp/pids/unicorn.pid') if spid.nil? || spid == :unset
660 unless RACKUP[:daemonized]
661 Unicorn::Launcher.daemonize!(RACKUP[:options])
662 RACKUP[:ready_pipe] = RACKUP[:options].delete(:ready_pipe)