6 # Implements a simple DSL for configuring a unicorn server.
8 # Example (when used with the unicorn config file):
10 # listen '/tmp/my_app.sock', :backlog => 1
11 # listen '0.0.0.0:9292'
13 # pid "/tmp/my_app.pid"
14 # after_fork do |server,worker|
15 # server.listen("127.0.0.1:#{9293 + worker.nr}") rescue nil
18 # The default logger writes its output to $stderr
19 DEFAULT_LOGGER = Logger.new($stderr) unless defined?(DEFAULT_LOGGER)
21 # Default settings for Unicorn
25 :logger => DEFAULT_LOGGER,
26 :worker_processes => 1,
27 :after_fork => lambda { |server, worker|
28 server.logger.info("worker=#{worker.nr} spawned pid=#{$$}")
30 # per-process listener ports for debugging/admin:
31 # "rescue nil" statement is needed because USR2 will
32 # cause the master process to reexecute itself and the
33 # per-worker ports can be taken, necessitating another
34 # HUP after QUIT-ing the original master:
35 # server.listen("127.0.0.1:#{8081 + worker.nr}") rescue nil
37 :before_fork => lambda { |server, worker|
38 server.logger.info("worker=#{worker.nr} spawning...")
40 :before_exec => lambda { |server|
41 server.logger.info("forked child re-executing...")
44 :preload_app => false,
49 attr_reader :config_file #:nodoc:
51 def initialize(defaults = {}) #:nodoc:
52 @set = Hash.new(:unset)
53 use_defaults = defaults.delete(:use_defaults)
54 @config_file = defaults.delete(:config_file)
56 @set.merge!(DEFAULTS) if use_defaults
57 defaults.each { |key, value| self.send(key, value) }
62 instance_eval(File.read(@config_file)) if @config_file
65 def commit!(server, options = {}) #:nodoc:
66 skip = options[:skip] || []
67 @set.each do |key, value|
68 (Symbol === value && value == :unset) and next
69 skip.include?(key) and next
71 if server.respond_to?(setter)
72 server.send(setter, value)
74 server.instance_variable_set("@#{key}", value)
83 # sets object to the +new+ Logger-like object. The new logger-like
84 # object must respond to the following methods:
85 # +debug+, +info+, +warn+, +error+, +fatal+, +close+
87 %w(debug info warn error fatal close).each do |m|
88 new.respond_to?(m) and next
89 raise ArgumentError, "logger=#{new} does not respond to method=#{m}"
95 # sets after_fork hook to a given block. This block will be called by
96 # the worker after forking. The following is an example hook which adds
97 # a per-process listener to every worker:
99 # after_fork do |server,worker|
100 # # per-process listener ports for debugging/admin:
101 # # "rescue nil" statement is needed because USR2 will
102 # # cause the master process to reexecute itself and the
103 # # per-worker ports can be taken, necessitating another
104 # # HUP after QUIT-ing the original master:
105 # server.listen("127.0.0.1:#{9293 + worker.nr}") rescue nil
107 # # drop permissions to "www-data" in the worker
108 # # generally there's no reason to start Unicorn as a priviledged user
109 # # as it is not recommended to expose Unicorn to public clients.
110 # uid, gid = Process.euid, Process.egid
111 # user, group = 'www-data', 'www-data'
112 # target_uid = Etc.getpwnam(user).uid
113 # target_gid = Etc.getgrnam(group).gid
114 # worker.tempfile.chown(target_uid, target_gid)
115 # if uid != target_uid || gid != target_gid
116 # Process.initgroups(user, target_gid)
117 # Process::GID.change_privilege(target_gid)
118 # Process::UID.change_privilege(target_uid)
121 def after_fork(*args, &block)
122 set_hook(:after_fork, block_given? ? block : args[0])
125 # sets before_fork got be a given Proc object. This Proc
126 # object will be called by the master process before forking
128 def before_fork(*args, &block)
129 set_hook(:before_fork, block_given? ? block : args[0])
132 # sets the before_exec hook to a given Proc object. This
133 # Proc object will be called by the master process right
134 # before exec()-ing the new unicorn binary. This is useful
135 # for freeing certain OS resources that you do NOT wish to
136 # share with the reexeced child process.
137 # There is no corresponding after_exec hook (for obvious reasons).
138 def before_exec(*args, &block)
139 set_hook(:before_exec, block_given? ? block : args[0], 1)
142 # sets the timeout of worker processes to +seconds+. Workers
143 # handling the request/app.call/response cycle taking longer than
144 # this time period will be forcibly killed (via SIGKILL). This
145 # timeout is enforced by the master process itself and not subject
146 # to the scheduling limitations by the worker process.
148 Numeric === seconds or raise ArgumentError,
149 "not numeric: timeout=#{seconds.inspect}"
150 seconds > 0 or raise ArgumentError,
151 "not positive: timeout=#{seconds.inspect}"
152 @set[:timeout] = seconds
155 # sets the current number of worker_processes to +nr+. Each worker
156 # process will serve exactly one client at a time.
157 def worker_processes(nr)
158 Integer === nr or raise ArgumentError,
159 "not an integer: worker_processes=#{nr.inspect}"
160 nr >= 0 or raise ArgumentError,
161 "not non-negative: worker_processes=#{nr.inspect}"
162 @set[:worker_processes] = nr
165 # sets listeners to the given +addresses+, replacing or augmenting the
166 # current set. This is for the global listener pool shared by all
167 # worker processes. For per-worker listeners, see the after_fork example
168 # This is for internal API use only, do not use it in your Unicorn
169 # config file. Use listen instead.
170 def listeners(addresses) # :nodoc:
171 Array === addresses or addresses = Array(addresses)
172 addresses.map! { |addr| expand_addr(addr) }
173 @set[:listeners] = addresses
176 # adds an +address+ to the existing listener set.
178 # The following options may be specified (but are generally not needed):
180 # +backlog+: this is the backlog of the listen() syscall.
182 # Some operating systems allow negative values here to specify the
183 # maximum allowable value. In most cases, this number is only
184 # recommendation and there are other OS-specific tunables and
185 # variables that can affect this number. See the listen(2)
186 # syscall documentation of your OS for the exact semantics of
189 # If you are running unicorn on multiple machines, lowering this number
190 # can help your load balancer detect when a machine is overloaded
191 # and give requests to a different machine.
195 # +rcvbuf+, +sndbuf+: maximum send and receive buffer sizes of sockets
197 # These correspond to the SO_RCVBUF and SO_SNDBUF settings which
198 # can be set via the setsockopt(2) syscall. Some kernels
199 # (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
200 # there is no need (and it is sometimes detrimental) to specify them.
202 # See the socket API documentation of your operating system
203 # to determine the exact semantics of these settings and
204 # other operating system-specific knobs where they can be
207 # Defaults: operating system defaults
208 def listen(address, opt = { :backlog => 1024 })
209 address = expand_addr(address)
210 if String === address
211 Hash === @set[:listener_opts] or
212 @set[:listener_opts] = Hash.new { |hash,key| hash[key] = {} }
213 [ :backlog, :sndbuf, :rcvbuf ].each do |key|
214 value = opt[key] or next
216 raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
218 @set[:listener_opts][address].merge!(opt)
221 @set[:listeners] = [] unless Array === @set[:listeners]
222 @set[:listeners] << address
225 # sets the +path+ for the PID file of the unicorn master process
226 def pid(path); set_path(:pid, path); end
228 # Enabling this preloads an application before forking worker
229 # processes. This allows memory savings when using a
230 # copy-on-write-friendly GC but can cause bad things to happen when
231 # resources like sockets are opened at load time by the master
232 # process and shared by multiple children. People enabling this are
233 # highly encouraged to look at the before_fork/after_fork hooks to
234 # properly close/reopen sockets. Files opened for logging do not
235 # have to be reopened as (unbuffered-in-userspace) files opened with
236 # the File::APPEND flag are written to atomically on UNIX.
238 # In addition to reloading the unicorn-specific config settings,
239 # SIGHUP will reload application code in the working
240 # directory/symlink when workers are gracefully restarted.
241 def preload_app(bool)
243 when TrueClass, FalseClass
244 @set[:preload_app] = bool
246 raise ArgumentError, "preload_app=#{bool.inspect} not a boolean"
250 # Allow redirecting $stderr to a given path. Unlike doing this from
251 # the shell, this allows the unicorn process to know the path its
252 # writing to and rotate the file if it is used for logging. The
253 # file will be opened with the File::APPEND flag and writes
254 # synchronized to the kernel (but not necessarily to _disk_) so
255 # multiple processes can safely append to it.
256 def stderr_path(path)
257 set_path(:stderr_path, path)
260 # Same as stderr_path, except for $stdout
261 def stdout_path(path)
262 set_path(:stdout_path, path)
267 def set_path(var, path) #:nodoc:
271 path = File.expand_path(path)
272 File.writable?(File.dirname(path)) or \
273 raise ArgumentError, "directory for #{var}=#{path} not writable"
280 def set_hook(var, my_proc, req_arity = 2) #:nodoc:
283 arity = my_proc.arity
284 (arity == req_arity) or \
286 "#{var}=#{my_proc.inspect} has invalid arity: " \
287 "#{arity} (need #{req_arity})"
289 my_proc = DEFAULTS[var]
291 raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
296 # expands "unix:path/to/foo" to a socket relative to the current path
297 # expands pathnames of sockets if relative to "~" or "~username"
298 # expands "*:port and ":port" to "0.0.0.0:port"
299 def expand_addr(address) #:nodoc
300 return address unless String === address
303 when %r{\Aunix:(.*)\z}
306 File.expand_path(address)
307 when %r{\A\*:(\d+)\z}
309 when %r{\A(.*):(\d+)\z}
310 # canonicalize the name
311 packed = Socket.pack_sockaddr_in($2.to_i, $1)
312 Socket.unpack_sockaddr_in(packed).reverse!.join(':')