Force streaming input onto apps by default
[unicorn.git] / lib / unicorn / configurator.rb
blobbd0a198982037205f8f290d34fbf8c06ea1d88e8
1 require 'socket'
2 require 'logger'
4 module Unicorn
6   # Implements a simple DSL for configuring a unicorn server.
7   #
8   # Example (when used with the unicorn config file):
9   #   worker_processes 4
10   #   listen '/tmp/my_app.sock', :backlog => 1
11   #   listen '0.0.0.0:9292'
12   #   timeout 10
13   #   pid "/tmp/my_app.pid"
14   #   after_fork do |server,worker|
15   #     server.listen("127.0.0.1:#{9293 + worker.nr}") rescue nil
16   #   end
17   class Configurator
18     # The default logger writes its output to $stderr
19     DEFAULT_LOGGER = Logger.new($stderr) unless defined?(DEFAULT_LOGGER)
21     # Default settings for Unicorn
22     DEFAULTS = {
23       :timeout => 60,
24       :listeners => [],
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
36         },
37       :before_fork => lambda { |server, worker|
38           server.logger.info("worker=#{worker.nr} spawning...")
39         },
40       :before_exec => lambda { |server|
41           server.logger.info("forked child re-executing...")
42         },
43       :pid => nil,
44       :preload_app => false,
45       :stderr_path => nil,
46       :stdout_path => nil,
47     }
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)
55       @config_file.freeze
56       @set.merge!(DEFAULTS) if use_defaults
57       defaults.each { |key, value| self.send(key, value) }
58       reload
59     end
61     def reload #:nodoc:
62       instance_eval(File.read(@config_file)) if @config_file
63     end
65     def commit!(server, options = {}) #:nodoc:
66       skip = options[:skip] || []
67       @set.each do |key, value|
68         value == :unset and next
69         skip.include?(key) and next
70         setter = "#{key}="
71         if server.respond_to?(setter)
72           server.send(setter, value)
73         else
74           server.instance_variable_set("@#{key}", value)
75         end
76       end
77     end
79     def [](key) # :nodoc:
80       @set[key]
81     end
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+
86     def logger(new)
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}"
90       end
92       @set[:logger] = new
93     end
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:
98     #
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
106     #
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)
119     #    end
120     #  end
121     def after_fork(*args, &block)
122       set_hook(:after_fork, block_given? ? block : args[0])
123     end
125     # sets before_fork got be a given Proc object.  This Proc
126     # object will be called by the master process before forking
127     # each worker.
128     def before_fork(*args, &block)
129       set_hook(:before_fork, block_given? ? block : args[0])
130     end
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)
140     end
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.  Due the
147     # low-complexity, low-overhead implementation, timeouts of less
148     # than 3.0 seconds can be considered inaccurate and unsafe.
149     def timeout(seconds)
150       Numeric === seconds or raise ArgumentError,
151                                   "not numeric: timeout=#{seconds.inspect}"
152       seconds >= 3 or raise ArgumentError,
153                                   "too low: timeout=#{seconds.inspect}"
154       @set[:timeout] = seconds
155     end
157     # sets the current number of worker_processes to +nr+.  Each worker
158     # process will serve exactly one client at a time.
159     def worker_processes(nr)
160       Integer === nr or raise ArgumentError,
161                              "not an integer: worker_processes=#{nr.inspect}"
162       nr >= 0 or raise ArgumentError,
163                              "not non-negative: worker_processes=#{nr.inspect}"
164       @set[:worker_processes] = nr
165     end
167     # sets listeners to the given +addresses+, replacing or augmenting the
168     # current set.  This is for the global listener pool shared by all
169     # worker processes.  For per-worker listeners, see the after_fork example
170     # This is for internal API use only, do not use it in your Unicorn
171     # config file.  Use listen instead.
172     def listeners(addresses) # :nodoc:
173       Array === addresses or addresses = Array(addresses)
174       addresses.map! { |addr| expand_addr(addr) }
175       @set[:listeners] = addresses
176     end
178     # adds an +address+ to the existing listener set.
179     #
180     # The following options may be specified (but are generally not needed):
181     #
182     # +backlog+: this is the backlog of the listen() syscall.
183     #
184     # Some operating systems allow negative values here to specify the
185     # maximum allowable value.  In most cases, this number is only
186     # recommendation and there are other OS-specific tunables and
187     # variables that can affect this number.  See the listen(2)
188     # syscall documentation of your OS for the exact semantics of
189     # this.
190     #
191     # If you are running unicorn on multiple machines, lowering this number
192     # can help your load balancer detect when a machine is overloaded
193     # and give requests to a different machine.
194     #
195     # Default: 1024
196     #
197     # +rcvbuf+, +sndbuf+: maximum send and receive buffer sizes of sockets
198     #
199     # These correspond to the SO_RCVBUF and SO_SNDBUF settings which
200     # can be set via the setsockopt(2) syscall.  Some kernels
201     # (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
202     # there is no need (and it is sometimes detrimental) to specify them.
203     #
204     # See the socket API documentation of your operating system
205     # to determine the exact semantics of these settings and
206     # other operating system-specific knobs where they can be
207     # specified.
208     #
209     # Defaults: operating system defaults
210     #
211     # +tcp_nodelay+: disables Nagle's algorithm on TCP sockets
212     #
213     # This has no effect on UNIX sockets.
214     #
215     # Default: operating system defaults (usually Nagle's algorithm enabled)
216     #
217     # +tcp_nopush+: enables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
218     #
219     # This will prevent partial TCP frames from being sent out.
220     # Enabling +tcp_nopush+ is generally not needed or recommended as
221     # controlling +tcp_nodelay+ already provides sufficient latency
222     # reduction whereas Unicorn does not know when the best times are
223     # for flushing corked sockets.
224     #
225     # This has no effect on UNIX sockets.
226     #
227     def listen(address, opt = {})
228       address = expand_addr(address)
229       if String === address
230         Hash === @set[:listener_opts] or
231           @set[:listener_opts] = Hash.new { |hash,key| hash[key] = {} }
232         [ :backlog, :sndbuf, :rcvbuf ].each do |key|
233           value = opt[key] or next
234           Integer === value or
235             raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
236         end
237         [ :tcp_nodelay, :tcp_nopush ].each do |key|
238           (value = opt[key]).nil? and next
239           TrueClass === value || FalseClass === value or
240             raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
241         end
242         @set[:listener_opts][address].merge!(opt)
243       end
245       @set[:listeners] = [] unless Array === @set[:listeners]
246       @set[:listeners] << address
247     end
249     # sets the +path+ for the PID file of the unicorn master process
250     def pid(path); set_path(:pid, path); end
252     # Enabling this preloads an application before forking worker
253     # processes.  This allows memory savings when using a
254     # copy-on-write-friendly GC but can cause bad things to happen when
255     # resources like sockets are opened at load time by the master
256     # process and shared by multiple children.  People enabling this are
257     # highly encouraged to look at the before_fork/after_fork hooks to
258     # properly close/reopen sockets.  Files opened for logging do not
259     # have to be reopened as (unbuffered-in-userspace) files opened with
260     # the File::APPEND flag are written to atomically on UNIX.
261     #
262     # In addition to reloading the unicorn-specific config settings,
263     # SIGHUP will reload application code in the working
264     # directory/symlink when workers are gracefully restarted.
265     def preload_app(bool)
266       case bool
267       when TrueClass, FalseClass
268         @set[:preload_app] = bool
269       else
270         raise ArgumentError, "preload_app=#{bool.inspect} not a boolean"
271       end
272     end
274     # Allow redirecting $stderr to a given path.  Unlike doing this from
275     # the shell, this allows the unicorn process to know the path its
276     # writing to and rotate the file if it is used for logging.  The
277     # file will be opened with the File::APPEND flag and writes
278     # synchronized to the kernel (but not necessarily to _disk_) so
279     # multiple processes can safely append to it.
280     def stderr_path(path)
281       set_path(:stderr_path, path)
282     end
284     # Same as stderr_path, except for $stdout
285     def stdout_path(path)
286       set_path(:stdout_path, path)
287     end
289     private
291     def set_path(var, path) #:nodoc:
292       case path
293       when NilClass
294       when String
295         path = File.expand_path(path)
296         File.writable?(File.dirname(path)) or \
297                raise ArgumentError, "directory for #{var}=#{path} not writable"
298       else
299         raise ArgumentError
300       end
301       @set[var] = path
302     end
304     def set_hook(var, my_proc, req_arity = 2) #:nodoc:
305       case my_proc
306       when Proc
307         arity = my_proc.arity
308         (arity == req_arity) or \
309           raise ArgumentError,
310                 "#{var}=#{my_proc.inspect} has invalid arity: " \
311                 "#{arity} (need #{req_arity})"
312       when NilClass
313         my_proc = DEFAULTS[var]
314       else
315         raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
316       end
317       @set[var] = my_proc
318     end
320     # expands "unix:path/to/foo" to a socket relative to the current path
321     # expands pathnames of sockets if relative to "~" or "~username"
322     # expands "*:port and ":port" to "0.0.0.0:port"
323     def expand_addr(address) #:nodoc
324       return "0.0.0.0:#{address}" if Integer === address
325       return address unless String === address
327       case address
328       when %r{\Aunix:(.*)\z}
329         File.expand_path($1)
330       when %r{\A~}
331         File.expand_path(address)
332       when %r{\A(?:\*:)?(\d+)\z}
333         "0.0.0.0:#$1"
334       when %r{\A(.*):(\d+)\z}
335         # canonicalize the name
336         packed = Socket.pack_sockaddr_in($2.to_i, $1)
337         Socket.unpack_sockaddr_in(packed).reverse!.join(':')
338       else
339         address
340       end
341     end
343   end