Parent

Unicorn::Configurator

Implements a simple DSL for configuring a Unicorn server.

See unicorn.bogomips.org/examples/unicorn.conf.rb for an example config file. An example config file for use with nginx is also available at unicorn.bogomips.org/examples/nginx.conf

Constants

DEFAULTS

Default settings for Unicorn

Public Instance Methods

after_fork(*args, &block) click to toggle source

sets after_fork hook to a given block. This block will be called by the worker after forking. The following is an example hook which adds a per-process listener to every worker:

 after_fork do |server,worker|
   # per-process listener ports for debugging/admin:
   addr = "127.0.0.1:#{9293 + worker.nr}"

   # the negative :tries parameter indicates we will retry forever
   # waiting on the existing process to exit with a 5 second :delay
   # Existing options for Unicorn::Configurator#listen such as
   # :backlog, :rcvbuf, :sndbuf are available here as well.
   server.listen(addr, :tries => -1, :delay => 5, :backlog => 128)

   # drop permissions to "www-data" in the worker
   # generally there's no reason to start Unicorn as a priviledged user
   # as it is not recommended to expose Unicorn to public clients.
   worker.user('www-data', 'www-data') if Process.euid == 0
 end
     # File lib/unicorn/configurator.rb, line 102
102:     def after_fork(*args, &block)
103:       set_hook(:after_fork, block_given? ? block : args[0])
104:     end
before_exec(*args, &block) click to toggle source

sets the before_exec hook to a given Proc object. This Proc object will be called by the master process right before exec()-ing the new unicorn binary. This is useful for freeing certain OS resources that you do NOT wish to share with the reexeced child process. There is no corresponding after_exec hook (for obvious reasons).

     # File lib/unicorn/configurator.rb, line 119
119:     def before_exec(*args, &block)
120:       set_hook(:before_exec, block_given? ? block : args[0], 1)
121:     end
before_fork(*args, &block) click to toggle source

sets before_fork got be a given Proc object. This Proc object will be called by the master process before forking each worker.

     # File lib/unicorn/configurator.rb, line 109
109:     def before_fork(*args, &block)
110:       set_hook(:before_fork, block_given? ? block : args[0])
111:     end
expand_addr(address) click to toggle source

expands “unix:path/to/foo“ to a socket relative to the current path expands pathnames of sockets if relative to “~” or “~username” expands “*:port and “:port” to “0.0.0.0:port“

     # File lib/unicorn/configurator.rb, line 335
335:     def expand_addr(address) #:nodoc
336:       return "0.0.0.0:#{address}" if Integer === address
337:       return address unless String === address
338: 
339:       case address
340:       when %r{\Aunix:(.*)\z}
341:         File.expand_path($1)
342:       when %r{\A~}
343:         File.expand_path(address)
344:       when %r{\A(?:\*:)?(\d+)\z}
345:         "0.0.0.0:#$1"
346:       when %r{\A(.*):(\d+)\z}
347:         # canonicalize the name
348:         packed = Socket.pack_sockaddr_in($2.to_i, $1)
349:         Socket.unpack_sockaddr_in(packed).reverse!.join(':')
350:       else
351:         address
352:       end
353:     end
listen(address, opt = {}) click to toggle source

adds an address to the existing listener set.

The following options may be specified (but are generally not needed):

:backlog: this is the backlog of the listen() syscall.

Some operating systems allow negative values here to specify the maximum allowable value. In most cases, this number is only recommendation and there are other OS-specific tunables and variables that can affect this number. See the listen(2) syscall documentation of your OS for the exact semantics of this.

If you are running unicorn on multiple machines, lowering this number can help your load balancer detect when a machine is overloaded and give requests to a different machine.

Default: 1024

:rcvbuf, :sndbuf: maximum receive and send buffer sizes of sockets

These correspond to the SO_RCVBUF and SO_SNDBUF settings which can be set via the setsockopt(2) syscall. Some kernels (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and there is no need (and it is sometimes detrimental) to specify them.

See the socket API documentation of your operating system to determine the exact semantics of these settings and other operating system-specific knobs where they can be specified.

Defaults: operating system defaults

:tcp_nodelay: disables Nagle’s algorithm on TCP sockets

This has no effect on UNIX sockets.

Default: operating system defaults (usually Nagle’s algorithm enabled)

:tcp_nopush: enables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD

This will prevent partial TCP frames from being sent out. Enabling tcp_nopush is generally not needed or recommended as controlling tcp_nodelay already provides sufficient latency reduction whereas Unicorn does not know when the best times are for flushing corked sockets.

This has no effect on UNIX sockets.

:tries: times to retry binding a socket if it is already in use

A negative number indicates we will retry indefinitely, this is useful for migrations and upgrades when individual workers are binding to different ports.

Default: 5

:delay: seconds to wait between successive tries

Default: 0.5 seconds

:umask: sets the file mode creation mask for UNIX sockets

Typically UNIX domain sockets are created with more liberal file permissions than the rest of the application. By default, we create UNIX domain sockets to be readable and writable by all local users to give them the same accessibility as locally-bound TCP listeners.

This has no effect on TCP listeners.

Default: 0 (world read/writable)

     # File lib/unicorn/configurator.rb, line 252
252:     def listen(address, opt = {})
253:       address = expand_addr(address)
254:       if String === address
255:         [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
256:           value = opt[key] or next
257:           Integer === value or
258:             raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
259:         end
260:         [ :tcp_nodelay, :tcp_nopush ].each do |key|
261:           (value = opt[key]).nil? and next
262:           TrueClass === value || FalseClass === value or
263:             raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
264:         end
265:         unless (value = opt[:delay]).nil?
266:           Numeric === value or
267:             raise ArgumentError, "not numeric: delay=#{value.inspect}"
268:         end
269:         set[:listener_opts][address].merge!(opt)
270:       end
271: 
272:       set[:listeners] << address
273:     end
logger(new) click to toggle source

sets object to the new Logger-like object. The new logger-like object must respond to the following methods:

 +debug+, +info+, +warn+, +error+, +fatal+, +close+
    # File lib/unicorn/configurator.rb, line 74
74:     def logger(new)
75:       %w(debug info warn error fatal close).each do |m|
76:         new.respond_to?(m) and next
77:         raise ArgumentError, "logger=#{new} does not respond to method=#{m}"
78:       end
79: 
80:       set[:logger] = new
81:     end
pid(path) click to toggle source

sets the path for the PID file of the unicorn master process

     # File lib/unicorn/configurator.rb, line 276
276:     def pid(path); set_path(:pid, path); end
preload_app(bool) click to toggle source

Enabling this preloads an application before forking worker processes. This allows memory savings when using a copy-on-write-friendly GC but can cause bad things to happen when resources like sockets are opened at load time by the master process and shared by multiple children. People enabling this are highly encouraged to look at the before_fork/after_fork hooks to properly close/reopen sockets. Files opened for logging do not have to be reopened as (unbuffered-in-userspace) files opened with the File::APPEND flag are written to atomically on UNIX.

In addition to reloading the unicorn-specific config settings, SIGHUP will reload application code in the working directory/symlink when workers are gracefully restarted.

     # File lib/unicorn/configurator.rb, line 291
291:     def preload_app(bool)
292:       case bool
293:       when TrueClass, FalseClass
294:         set[:preload_app] = bool
295:       else
296:         raise ArgumentError, "preload_app=#{bool.inspect} not a boolean"
297:       end
298:     end
stderr_path(path) click to toggle source

Allow redirecting $stderr to a given path. Unlike doing this from the shell, this allows the unicorn process to know the path its writing to and rotate the file if it is used for logging. The file will be opened with the File::APPEND flag and writes synchronized to the kernel (but not necessarily to disk) so multiple processes can safely append to it.

     # File lib/unicorn/configurator.rb, line 306
306:     def stderr_path(path)
307:       set_path(:stderr_path, path)
308:     end
stdout_path(path) click to toggle source

Same as stderr_path, except for $stdout

     # File lib/unicorn/configurator.rb, line 311
311:     def stdout_path(path)
312:       set_path(:stdout_path, path)
313:     end
timeout(seconds) click to toggle source

sets the timeout of worker processes to seconds. Workers handling the request/app.call/response cycle taking longer than this time period will be forcibly killed (via SIGKILL). This timeout is enforced by the master process itself and not subject to the scheduling limitations by the worker process. Due the low-complexity, low-overhead implementation, timeouts of less than 3.0 seconds can be considered inaccurate and unsafe.

For running Unicorn behind nginx, it is recommended to set “fail_timeout=0” for in your nginx configuration like this to have nginx always retry backends that may have had workers SIGKILL-ed due to timeouts.

   # See http://wiki.nginx.org/NginxHttpUpstreamModule for more details
   # on nginx upstream configuration:
   upstream unicorn_backend {
     # for UNIX domain socket setups:
     server unix:/path/to/unicorn.sock fail_timeout=0;

     # for TCP setups
     server 192.168.0.7:8080 fail_timeout=0;
     server 192.168.0.8:8080 fail_timeout=0;
     server 192.168.0.9:8080 fail_timeout=0;
   }
     # File lib/unicorn/configurator.rb, line 147
147:     def timeout(seconds)
148:       Numeric === seconds or raise ArgumentError,
149:                                   "not numeric: timeout=#{seconds.inspect}"
150:       seconds >= 3 or raise ArgumentError,
151:                                   "too low: timeout=#{seconds.inspect}"
152:       set[:timeout] = seconds
153:     end
worker_processes(nr) click to toggle source

sets the current number of worker_processes to nr. Each worker process will serve exactly one client at a time. You can increment or decrement this value at runtime by sending SIGTTIN or SIGTTOU respectively to the master process without reloading the rest of your Unicorn configuration. See the SIGNALS document for more information.

     # File lib/unicorn/configurator.rb, line 161
161:     def worker_processes(nr)
162:       Integer === nr or raise ArgumentError,
163:                              "not an integer: worker_processes=#{nr.inspect}"
164:       nr >= 0 or raise ArgumentError,
165:                              "not non-negative: worker_processes=#{nr.inspect}"
166:       set[:worker_processes] = nr
167:     end
working_directory(path) click to toggle source

sets the working directory for Unicorn. This ensures USR2 will start a new instance of Unicorn in this directory. This may be a symlink.

     # File lib/unicorn/configurator.rb, line 318
318:     def working_directory(path)
319:       # just let chdir raise errors
320:       path = File.expand_path(path)
321:       if config_file &&
322:          config_file[0] != ?/ &&
323:          ! test(?r, "#{path}/#{config_file}")
324:         raise ArgumentError,
325:               "config_file=#{config_file} would not be accessible in" \
326:               " working_directory=#{path}"
327:       end
328:       Dir.chdir(path)
329:       HttpServer::START_CTX[:cwd] = ENV["PWD"] = path
330:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.