3 require 'unicorn/socket'
4 require 'unicorn/const'
5 require 'unicorn/http_request'
6 require 'unicorn/http_response'
7 require 'unicorn/configurator'
10 # Unicorn module containing all of the classes (include C extensions) for running
11 # a Unicorn web server. It contains a minimalist HTTP server with just enough
12 # functionality to service web application requests fast as possible.
15 def run(app, options = {})
16 HttpServer.new(app, options).start.join
20 # This is the process manager of Unicorn. This manages worker
21 # processes which in turn handle the I/O and application process.
22 # Listener sockets are started in the master process and shared with
23 # forked worker children.
26 include ::Unicorn::SocketHelper
29 :argv => ARGV.map { |arg| arg.dup },
30 # don't rely on Dir.pwd here since it's not symlink-aware, and
31 # symlink dirs are the default with Capistrano...
32 :cwd => `/bin/sh -c pwd`.chomp("\n"),
34 :environ => {}.merge!(ENV),
38 Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
40 # worker objects may be compared to just plain numbers
46 # Creates a working server on host:port (strange things happen if
47 # port isn't a Number). Use HttpServer::run to start the server and
48 # HttpServer.workers.join to join the thread that's processing
49 # incoming requests on the socket.
50 def initialize(app, options = {})
51 start_ctx = options.delete(:start_ctx)
52 @start_ctx = DEFAULT_START_CTX.dup
53 @start_ctx.merge!(start_ctx) if start_ctx
58 @io_purgatory = [] # prevents IO objects in here from being GC-ed
59 @request = @rd_sig = @wr_sig = nil
61 @config = Configurator.new(options.merge(:use_defaults => true))
62 @config.commit!(self, :skip => [:listeners, :pid])
66 # Runs the thing. Returns self so you can run join on it
68 BasicSocket.do_not_reverse_lookup = true
70 # inherit sockets from parents, they need to be plain Socket objects
71 # before they become UNIXServer or TCPServer
72 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
73 io = Socket.for_fd(fd.to_i)
74 set_server_sockopt(io)
76 logger.info "inherited: #{io} fd=#{fd} addr=#{sock_name(io)}"
80 config_listeners = @config[:listeners].dup
81 @listeners.replace(inherited)
83 # we start out with generic Socket objects that get cast to either
84 # TCPServer or UNIXServer objects; but since the Socket objects
85 # share the same OS-level file descriptor as the higher-level *Server
86 # objects; we need to prevent Socket objects from being garbage-collected
87 config_listeners -= listener_names
88 config_listeners.each { |addr| listen(addr) }
89 raise ArgumentError, "no listeners" if @listeners.empty?
90 self.pid = @config[:pid]
91 build_app! if @preload_app
92 $stderr.reopen(File.open(@stderr_path, "a")) if @stderr_path
93 $stdout.reopen(File.open(@stdout_path, "a")) if @stdout_path
94 $stderr.sync = $stdout.sync = true
99 # replaces current listener set with +listeners+. This will
100 # close the socket if it will not exist in the new listener set
101 def listeners=(listeners)
102 cur_names = listener_names
103 set_names = listener_names(listeners)
104 dead_names = cur_names - set_names
106 @listeners.delete_if do |io|
107 if dead_names.include?(sock_name(io))
108 @io_purgatory.delete_if { |pio| pio.fileno == io.fileno }
115 (set_names - cur_names).each { |addr| listen(addr) }
118 # sets the path for the PID file of the master process
121 if x = valid_pid?(path)
122 return path if @pid && path == @pid && x == $$
123 raise ArgumentError, "Already running on PID:#{x} " \
124 "(or pid=#{path} is stale)"
126 File.open(path, 'wb') { |fp| fp.syswrite("#{$$}\n") }
128 unlink_pid_safe(@pid) if @pid && @pid != path
132 # add a given address to the +listeners+ set, idempotently
133 # Allows workers to add a private, per-process listener via the
134 # @after_fork hook. Very useful for debugging and testing.
136 return if String === address && listener_names.include?(address)
138 if io = bind_listen(address, @backlog)
139 if Socket == io.class
143 logger.info "#{io} listening on PID:#{$$} " \
144 "fd=#{io.fileno} addr=#{sock_name(io)}"
147 logger.error "adding listener failed addr=#{address} (in use)"
148 raise Errno::EADDRINUSE, address
152 # monitors children and receives signals forever
153 # (or until a termination signal is sent). This handles signals
154 # one-at-a-time time and we'll happily drop signals in case somebody
155 # is signalling us too often.
157 # this pipe is used to wake us up from select(2) in #join when signals
158 # are trapped. See trap_deferred
159 @rd_sig, @wr_sig = IO.pipe unless (@rd_sig && @wr_sig)
160 @rd_sig.nonblock = @wr_sig.nonblock = true
164 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
165 trap('CHLD') { |sig_nr| awaken_master }
166 $0 = "unicorn master"
167 logger.info "master process ready" # test_exec.rb relies on this message
171 case (mode = @sig_queue.shift)
174 spawn_missing_workers if respawn
176 when 'QUIT' # graceful shutdown
178 when 'TERM', 'INT' # immediate shutdown
181 when 'USR1' # rotate logs
182 logger.info "master rotating logs..."
183 Unicorn::Util.reopen_logs
184 logger.info "master done rotating logs"
185 kill_each_worker('USR1')
186 when 'USR2' # exec binary, stay alive in case something went wrong
189 if Process.ppid == 1 || Process.getpgrp != $$
191 logger.info "gracefully stopping all workers"
192 kill_each_worker('QUIT')
194 logger.info "SIGWINCH ignored because we're not daemonized"
198 if @config.config_file
200 redo # immediate reaping since we may have QUIT workers
201 else # exec binary and exit if there's no config file
202 logger.info "config_file not present, reexecuting binary"
207 logger.error "master process in unknown mode: #{mode}"
213 logger.error "Unhandled master loop exception #{e.inspect}."
214 logger.error e.backtrace.join("\n")
217 stop # gracefully shutdown all workers on our way out
218 logger.info "master PID:#{$$} join complete"
219 unlink_pid_safe(@pid) if @pid
222 # Terminates all workers, but does not exit master process
223 def stop(graceful = true)
224 kill_each_worker(graceful ? 'QUIT' : 'TERM')
228 until @workers.empty?
231 (timeleft -= step) > 0 and next
232 kill_each_worker('KILL')
240 # list of signals we care about and trap in master.
242 %w(WINCH QUIT INT TERM USR1 USR2 HUP).map { |x| x.freeze }.freeze
244 # defer a signal for later processing in #join (master process)
245 def trap_deferred(signal)
246 trap(signal) do |sig_nr|
247 if @sig_queue.size < 5
251 logger.error "ignoring SIG#{signal}, queue=#{@sig_queue.inspect}"
256 # wait for a signal hander to wake us up and then consume the pipe
257 # Wake up every second anyways to run murder_lazy_workers
260 ready = IO.select([@rd_sig], nil, nil, 1)
261 ready && ready[0] && ready[0][0] or return
262 loop { @rd_sig.sysread(Const::CHUNK_SIZE) }
263 rescue Errno::EAGAIN, Errno::EINTR
269 @wr_sig.syswrite('.') # wakeup master process from IO.select
270 rescue Errno::EAGAIN # pipe is full, master should wake up anyways
276 # reaps all unreaped workers
280 pid, status = Process.waitpid2(-1, Process::WNOHANG)
282 if @reexec_pid == pid
283 logger.error "reaped #{status.inspect} exec()-ed"
285 self.pid = @pid.chomp('.oldbin') if @pid
286 $0 = "unicorn master"
288 worker = @workers.delete(pid)
289 worker.tempfile.close rescue nil
290 logger.info "reaped #{status.inspect} " \
291 "worker=#{worker.nr rescue 'unknown'}"
298 # reexecutes the @start_ctx with a new binary
302 Process.kill(0, @reexec_pid)
303 logger.error "reexec-ed child already running PID:#{@reexec_pid}"
311 old_pid = "#{@pid}.oldbin"
314 self.pid = old_pid # clear the path for a new pid file
316 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
317 "existing pid=#{old_pid}, refusing rexec"
320 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
325 @reexec_pid = fork do
326 @rd_sig.close if @rd_sig
327 @wr_sig.close if @wr_sig
328 @workers.values.each { |other| other.tempfile.close rescue nil }
330 ENV.replace(@start_ctx[:environ])
331 ENV['UNICORN_FD'] = @listeners.map { |sock| sock.fileno }.join(',')
332 File.umask(@start_ctx[:umask])
333 Dir.chdir(@start_ctx[:cwd])
334 cmd = [ @start_ctx[:zero] ] + @start_ctx[:argv]
335 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
336 @before_exec.call(self) if @before_exec
339 $0 = "unicorn master (old)"
342 # forcibly terminate all workers that haven't checked in in @timeout
343 # seconds. The timeout is implemented using an unlinked tempfile
344 # shared between the parent process and each worker. The worker
345 # runs File#chmod to modify the ctime of the tempfile. If the ctime
346 # is stale for >@timeout seconds, then we'll kill the corresponding
348 def murder_lazy_workers
350 @workers.each_pair do |pid, worker|
351 (now - worker.tempfile.ctime) <= @timeout and next
352 logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
353 kill_worker('KILL', pid) # take no prisoners for @timeout violations
354 worker.tempfile.close rescue nil
358 def spawn_missing_workers
359 return if @workers.size == @worker_processes
360 (0...@worker_processes).each do |worker_nr|
361 @workers.values.include?(worker_nr) and next
363 Dir.chdir(@start_ctx[:cwd])
364 rescue Errno::ENOENT => err
365 logger.fatal "#{err.inspect} (#{@start_ctx[:cwd]})"
366 @sig_queue << 'QUIT' # forcibly emulate SIGQUIT
369 tempfile = Tempfile.new('') # as short as possible to save dir space
370 tempfile.unlink # don't allow other processes to find or see it
372 worker = Worker.new(worker_nr, tempfile)
373 @before_fork.call(self, worker.nr)
374 pid = fork { worker_loop(worker) }
375 @workers[pid] = worker
379 # once a client is accepted, it is processed in its entirety here
380 # in 3 easy steps: read request, call app, write app response
381 def process_client(client)
382 env = @request.read(client) or return
383 app_response = @app.call(env)
384 HttpResponse.write(client, app_response)
385 rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
386 client.closed? or client.close rescue nil
388 logger.error "Read error: #{e.inspect}"
389 logger.error e.backtrace.join("\n")
392 client.closed? or client.close
394 logger.error "Client error: #{e.inspect}"
395 logger.error e.backtrace.join("\n")
400 # gets rid of stuff the worker has no business keeping track of
401 # to free some resources and drops all sig handlers.
402 # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
404 def init_worker_process(worker)
405 build_app! unless @preload_app
407 QUEUE_SIGS.each { |sig| trap(sig, 'IGNORE') }
408 trap('CHLD', 'DEFAULT')
410 @logger.info "worker=#{worker.nr} rotating logs..."
411 Unicorn::Util.reopen_logs
412 @logger.info "worker=#{worker.nr} done rotating logs"
415 $0 = "unicorn worker[#{worker.nr}]"
416 @rd_sig.close if @rd_sig
417 @wr_sig.close if @wr_sig
418 @workers.values.each { |other| other.tempfile.close rescue nil }
421 @start_ctx = @workers = @rd_sig = @wr_sig = nil
422 @listeners.each { |sock| set_cloexec(sock) }
423 ENV.delete('UNICORN_FD')
424 @after_fork.call(self, worker.nr) if @after_fork
425 @request = HttpRequest.new(logger)
428 # runs inside each forked worker, this sits around and waits
429 # for connections and doesn't die until the parent dies (or is
430 # given a INT, QUIT, or TERM signal)
431 def worker_loop(worker)
432 init_worker_process(worker)
434 tempfile = worker.tempfile
438 %w(TERM INT).each { |sig| trap(sig) { exit(0) } } # instant shutdown
441 @listeners.each { |sock| sock.close rescue nil } # break IO.select
444 while alive && @master_pid == Process.ppid
445 # we're a goner in @timeout seconds anyways if tempfile.chmod
446 # breaks, so don't trap the exception. Using fchmod() since
447 # futimes() is not available in base Ruby and I very strongly
448 # prefer temporary files to be unlinked for security,
449 # performance and reliability reasons, so utime is out. No-op
450 # changes with chmod doesn't update ctime on all filesystems; so
451 # we increment our counter each and every time.
452 tempfile.chmod(nr += 1)
463 accepted = client.sync = true
464 client.nonblock = false
465 set_client_sockopt(client) if TCPSocket === client
466 process_client(client)
467 rescue Errno::ECONNABORTED
468 # client closed the socket even before accept
469 if client && !client.closed?
470 client.close rescue nil
473 tempfile.chmod(nr += 1)
477 # make the following bet: if we accepted clients this round,
478 # we're probably reasonably busy, so avoid calling select(2)
479 # and try to do a blind non-blocking accept(2) on everything
480 # before we sleep again in select
485 tempfile.chmod(nr += 1)
486 # timeout used so we can detect parent death:
487 ret = IO.select(@listeners, nil, nil, @timeout/2.0) or next
491 rescue Errno::EBADF => e
495 rescue SystemExit => e
499 logger.error "Unhandled listen loop exception #{e.inspect}."
500 logger.error e.backtrace.join("\n")
506 # delivers a signal to a worker and fails gracefully if the worker
507 # is no longer running.
508 def kill_worker(signal, pid)
510 Process.kill(signal, pid)
512 worker = @workers.delete(pid) and worker.tempfile.close rescue nil
516 # delivers a signal to each worker
517 def kill_each_worker(signal)
518 @workers.keys.each { |pid| kill_worker(signal, pid) }
521 # unlinks a PID file at given +path+ if it contains the current PID
522 # useful as an at_exit handler.
523 def unlink_pid_safe(path)
524 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
527 # returns a PID if a given path contains a non-stale PID file,
530 if File.exist?(path) && (pid = File.read(path).to_i) > 1
542 logger.info "reloading config_file=#{@config.config_file}"
544 @config.commit!(self)
545 kill_each_worker('QUIT')
546 logger.info "done reloading config_file=#{@config.config_file}"
548 logger.error "error reloading config_file=#{@config.config_file}: " \
549 "#{e.class} #{e.message}"
553 # returns an array of string names for the given listener array
554 def listener_names(listeners = @listeners)
555 listeners.map { |io| sock_name(io) }
559 @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0