Cleanup GNUmakefile and fix dependencies
[unicorn.git] / lib / unicorn / configurator.rb
blobbd069969ae4005198ff655e60cea99ec0be944f9
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         (Symbol === value && 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.
147     def timeout(seconds)
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
153     end
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
163     end
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
174     end
176     # adds an +address+ to the existing listener set.
177     #
178     # The following options may be specified (but are generally not needed):
179     #
180     # +backlog+: this is the backlog of the listen() syscall.
181     #
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
187     #   this.
188     #
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.
192     #
193     #   Default: 1024
194     #
195     # +rcvbuf+, +sndbuf+: maximum send and receive buffer sizes of sockets
196     #
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.
201     #
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
205     #   specified.
206     #
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
215           Integer === value or
216             raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
217         end
218         @set[:listener_opts][address].merge!(opt)
219       end
221       @set[:listeners] = [] unless Array === @set[:listeners]
222       @set[:listeners] << address
223     end
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.
237     #
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)
242       case bool
243       when TrueClass, FalseClass
244         @set[:preload_app] = bool
245       else
246         raise ArgumentError, "preload_app=#{bool.inspect} not a boolean"
247       end
248     end
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)
258     end
260     # Same as stderr_path, except for $stdout
261     def stdout_path(path)
262       set_path(:stdout_path, path)
263     end
265     private
267     def set_path(var, path) #:nodoc:
268       case path
269       when NilClass
270       when String
271         path = File.expand_path(path)
272         File.writable?(File.dirname(path)) or \
273                raise ArgumentError, "directory for #{var}=#{path} not writable"
274       else
275         raise ArgumentError
276       end
277       @set[var] = path
278     end
280     def set_hook(var, my_proc, req_arity = 2) #:nodoc:
281       case my_proc
282       when Proc
283         arity = my_proc.arity
284         (arity == req_arity) or \
285           raise ArgumentError,
286                 "#{var}=#{my_proc.inspect} has invalid arity: " \
287                 "#{arity} (need #{req_arity})"
288       when NilClass
289         my_proc = DEFAULTS[var]
290       else
291         raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
292       end
293       @set[var] = my_proc
294     end
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
302       case address
303       when %r{\Aunix:(.*)\z}
304         File.expand_path($1)
305       when %r{\A~}
306         File.expand_path(address)
307       when %r{\A\*:(\d+)\z}
308         "0.0.0.0:#$1"
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(':')
313       else
314         address
315       end
316     end
318   end