4 require 'unicorn/socket'
5 require 'unicorn/const'
6 require 'unicorn/http_request'
7 require 'unicorn/http_response'
8 require 'unicorn/configurator'
11 # Unicorn module containing all of the classes (include C extensions) for running
12 # a Unicorn web server. It contains a minimalist HTTP server with just enough
13 # functionality to service web application requests fast as possible.
16 def run(app, options = {})
17 HttpServer.new(app, options).start.join
21 # This is the process manager of Unicorn. This manages worker
22 # processes which in turn handle the I/O and application process.
23 # Listener sockets are started in the master process and shared with
24 # forked worker children.
27 include ::Unicorn::SocketHelper
30 :argv => ARGV.map { |arg| arg.dup },
31 # don't rely on Dir.pwd here since it's not symlink-aware, and
32 # symlink dirs are the default with Capistrano...
33 :cwd => `/bin/sh -c pwd`.chomp("\n"),
35 :environ => {}.merge!(ENV),
39 Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
41 # worker objects may be compared to just plain numbers
47 # Creates a working server on host:port (strange things happen if
48 # port isn't a Number). Use HttpServer::run to start the server and
49 # HttpServer.workers.join to join the thread that's processing
50 # incoming requests on the socket.
51 def initialize(app, options = {})
52 start_ctx = options.delete(:start_ctx)
53 @start_ctx = DEFAULT_START_CTX.dup
54 @start_ctx.merge!(start_ctx) if start_ctx
59 @io_purgatory = [] # prevents IO objects in here from being GC-ed
60 @request = @rd_sig = @wr_sig = nil
62 @config = Configurator.new(options.merge(:use_defaults => true))
64 @config.commit!(self, :skip => [:listeners, :pid])
68 # Runs the thing. Returns self so you can run join on it
70 BasicSocket.do_not_reverse_lookup = true
72 # inherit sockets from parents, they need to be plain Socket objects
73 # before they become UNIXServer or TCPServer
74 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
75 io = Socket.for_fd(fd.to_i)
76 set_server_sockopt(io)
78 logger.info "inherited: #{io} fd=#{fd} addr=#{sock_name(io)}"
82 config_listeners = @config[:listeners].dup
83 @listeners.replace(inherited)
85 # we start out with generic Socket objects that get cast to either
86 # TCPServer or UNIXServer objects; but since the Socket objects
87 # share the same OS-level file descriptor as the higher-level *Server
88 # objects; we need to prevent Socket objects from being garbage-collected
89 config_listeners -= listener_names
90 if config_listeners.empty? && @listeners.empty?
91 config_listeners << Unicorn::Const::DEFAULT_LISTEN
93 config_listeners.each { |addr| listen(addr) }
94 raise ArgumentError, "no listeners" if @listeners.empty?
95 self.pid = @config[:pid]
96 build_app! if @preload_app
97 $stderr.reopen(File.open(@stderr_path, "a")) if @stderr_path
98 $stdout.reopen(File.open(@stdout_path, "a")) if @stdout_path
99 $stderr.sync = $stdout.sync = true
100 spawn_missing_workers
104 # replaces current listener set with +listeners+. This will
105 # close the socket if it will not exist in the new listener set
106 def listeners=(listeners)
107 cur_names = listener_names
108 set_names = listener_names(listeners)
109 dead_names = cur_names - set_names
111 @listeners.delete_if do |io|
112 if dead_names.include?(sock_name(io))
113 @io_purgatory.delete_if { |pio| pio.fileno == io.fileno }
120 (set_names - cur_names).each { |addr| listen(addr) }
123 # sets the path for the PID file of the master process
126 if x = valid_pid?(path)
127 return path if @pid && path == @pid && x == $$
128 raise ArgumentError, "Already running on PID:#{x} " \
129 "(or pid=#{path} is stale)"
132 unlink_pid_safe(@pid) if @pid
133 File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
137 # add a given address to the +listeners+ set, idempotently
138 # Allows workers to add a private, per-process listener via the
139 # @after_fork hook. Very useful for debugging and testing.
140 def listen(address, opt = {}.merge(@listener_opts[address] || {}))
141 return if String === address && listener_names.include?(address)
143 if io = bind_listen(address, opt)
144 if Socket == io.class
148 logger.info "#{io} listening on PID:#{$$} " \
149 "fd=#{io.fileno} addr=#{sock_name(io)}"
152 logger.error "adding listener failed addr=#{address} (in use)"
153 raise Errno::EADDRINUSE, address
157 # monitors children and receives signals forever
158 # (or until a termination signal is sent). This handles signals
159 # one-at-a-time time and we'll happily drop signals in case somebody
160 # is signalling us too often.
162 # this pipe is used to wake us up from select(2) in #join when signals
163 # are trapped. See trap_deferred
164 @rd_sig, @wr_sig = IO.pipe unless (@rd_sig && @wr_sig)
168 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
169 trap(:CHLD) { |sig_nr| awaken_master }
170 $0 = "unicorn master"
171 logger.info "master process ready" # test_exec.rb relies on this message
175 case (mode = @sig_queue.shift)
178 spawn_missing_workers if respawn
180 when :QUIT # graceful shutdown
182 when :TERM, :INT # immediate shutdown
185 when :USR1 # rotate logs
186 logger.info "master rotating logs..."
187 Unicorn::Util.reopen_logs
188 logger.info "master done rotating logs"
189 kill_each_worker(:USR1)
190 when :USR2 # exec binary, stay alive in case something went wrong
193 if Process.ppid == 1 || Process.getpgrp != $$
195 logger.info "gracefully stopping all workers"
196 kill_each_worker(:QUIT)
198 logger.info "SIGWINCH ignored because we're not daemonized"
202 if @config.config_file
204 redo # immediate reaping since we may have QUIT workers
205 else # exec binary and exit if there's no config file
206 logger.info "config_file not present, reexecuting binary"
211 logger.error "master process in unknown mode: #{mode}"
217 logger.error "Unhandled master loop exception #{e.inspect}."
218 logger.error e.backtrace.join("\n")
221 stop # gracefully shutdown all workers on our way out
222 logger.info "master PID:#{$$} join complete"
223 unlink_pid_safe(@pid) if @pid
226 # Terminates all workers, but does not exit master process
227 def stop(graceful = true)
228 kill_each_worker(graceful ? :QUIT : :TERM)
232 until @workers.empty?
235 (timeleft -= step) > 0 and next
236 kill_each_worker(:KILL)
244 # list of signals we care about and trap in master.
245 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP ].freeze
247 # defer a signal for later processing in #join (master process)
248 def trap_deferred(signal)
249 trap(signal) do |sig_nr|
250 if @sig_queue.size < 5
254 logger.error "ignoring SIG#{signal}, queue=#{@sig_queue.inspect}"
259 # wait for a signal hander to wake us up and then consume the pipe
260 # Wake up every second anyways to run murder_lazy_workers
263 ready = IO.select([@rd_sig], nil, nil, 1)
264 ready && ready[0] && ready[0][0] or return
265 loop { @rd_sig.read_nonblock(Const::CHUNK_SIZE) }
266 rescue Errno::EAGAIN, Errno::EINTR
272 @wr_sig.write_nonblock('.') # wakeup master process from IO.select
273 rescue Errno::EAGAIN, Errno::EINTR
274 # pipe is full, master should wake up anyways
279 # reaps all unreaped workers
283 pid, status = Process.waitpid2(-1, Process::WNOHANG)
285 if @reexec_pid == pid
286 logger.error "reaped #{status.inspect} exec()-ed"
288 self.pid = @pid.chomp('.oldbin') if @pid
289 $0 = "unicorn master"
291 worker = @workers.delete(pid)
292 worker.tempfile.close rescue nil
293 logger.info "reaped #{status.inspect} " \
294 "worker=#{worker.nr rescue 'unknown'}"
301 # reexecutes the @start_ctx with a new binary
305 Process.kill(0, @reexec_pid)
306 logger.error "reexec-ed child already running PID:#{@reexec_pid}"
314 old_pid = "#{@pid}.oldbin"
317 self.pid = old_pid # clear the path for a new pid file
319 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
320 "existing pid=#{old_pid}, refusing rexec"
323 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
328 @reexec_pid = fork do
329 ENV.replace(@start_ctx[:environ])
330 listener_fds = @listeners.map { |sock| sock.fileno }
331 ENV['UNICORN_FD'] = listener_fds.join(',')
332 File.umask(@start_ctx[:umask])
333 Dir.chdir(@start_ctx[:cwd])
334 cmd = [ @start_ctx[:zero] ] + @start_ctx[:argv]
336 # avoid leaking FDs we don't know about, but let before_exec
337 # unset FD_CLOEXEC, if anything else in the app eventually
338 # relies on FD inheritence.
339 purgatory = [] # prevent GC of IO objects
340 (3..1024).each do |io|
341 next if listener_fds.include?(io)
342 io = IO.for_fd(io) rescue nil
345 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
347 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
348 @before_exec.call(self) if @before_exec
351 $0 = "unicorn master (old)"
354 # forcibly terminate all workers that haven't checked in in @timeout
355 # seconds. The timeout is implemented using an unlinked tempfile
356 # shared between the parent process and each worker. The worker
357 # runs File#chmod to modify the ctime of the tempfile. If the ctime
358 # is stale for >@timeout seconds, then we'll kill the corresponding
360 def murder_lazy_workers
362 @workers.each_pair do |pid, worker|
363 (now - worker.tempfile.ctime) <= @timeout and next
364 logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
365 kill_worker(:KILL, pid) # take no prisoners for @timeout violations
366 worker.tempfile.close rescue nil
370 def spawn_missing_workers
371 return if @workers.size == @worker_processes
372 (0...@worker_processes).each do |worker_nr|
373 @workers.values.include?(worker_nr) and next
375 Dir.chdir(@start_ctx[:cwd])
376 rescue Errno::ENOENT => err
377 logger.fatal "#{err.inspect} (#{@start_ctx[:cwd]})"
378 @sig_queue << :QUIT # forcibly emulate SIGQUIT
381 tempfile = Tempfile.new('') # as short as possible to save dir space
382 tempfile.unlink # don't allow other processes to find or see it
384 worker = Worker.new(worker_nr, tempfile)
385 @before_fork.call(self, worker.nr)
386 pid = fork { worker_loop(worker) }
387 @workers[pid] = worker
391 # once a client is accepted, it is processed in its entirety here
392 # in 3 easy steps: read request, call app, write app response
393 def process_client(client)
394 client.nonblock = false
395 set_client_sockopt(client) if TCPSocket === client
396 env = @request.read(client)
397 app_response = @app.call(env)
398 HttpResponse.write(client, app_response)
399 # if we get any error, try to write something back to the client
400 # assuming we haven't closed the socket, but don't get hung up
401 # if the socket is already closed or broken. We'll always ensure
402 # the socket is closed at the end of this function
403 rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
404 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
405 rescue HttpParserError # try to tell the client they're bad
406 client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
408 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
409 logger.error "Read error: #{e.inspect}"
410 logger.error e.backtrace.join("\n")
413 client.closed? or client.close
415 logger.error "Client error: #{e.inspect}"
416 logger.error e.backtrace.join("\n")
421 # gets rid of stuff the worker has no business keeping track of
422 # to free some resources and drops all sig handlers.
423 # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
425 def init_worker_process(worker)
426 build_app! unless @preload_app
428 QUEUE_SIGS.each { |sig| trap(sig, 'IGNORE') }
429 trap(:CHLD, 'DEFAULT')
431 $0 = "unicorn worker[#{worker.nr}]"
432 @rd_sig.close if @rd_sig
433 @wr_sig.close if @wr_sig
434 @workers.values.each { |other| other.tempfile.close rescue nil }
437 @start_ctx = @workers = @rd_sig = @wr_sig = nil
438 @listeners.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
439 ENV.delete('UNICORN_FD')
440 @after_fork.call(self, worker.nr) if @after_fork
441 worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
442 @request = HttpRequest.new(logger)
445 # runs inside each forked worker, this sits around and waits
446 # for connections and doesn't die until the parent dies (or is
447 # given a INT, QUIT, or TERM signal)
448 def worker_loop(worker)
449 init_worker_process(worker)
451 tempfile = worker.tempfile
455 [:TERM, :INT].each { |sig| trap(sig) { exit(0) } } # instant shutdown
458 @listeners.each { |sock| sock.close rescue nil } # break IO.select
460 reopen_logs, (rd, wr) = false, IO.pipe
461 rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
462 wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
463 trap(:USR1) { reopen_logs = true; rd.close rescue nil } # break IO.select
464 @logger.info "worker=#{worker.nr} ready"
466 while alive && @master_pid == Process.ppid
469 @logger.info "worker=#{worker.nr} rotating logs..."
470 Unicorn::Util.reopen_logs
471 @logger.info "worker=#{worker.nr} done rotating logs"
474 rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
475 wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
477 # we're a goner in @timeout seconds anyways if tempfile.chmod
478 # breaks, so don't trap the exception. Using fchmod() since
479 # futimes() is not available in base Ruby and I very strongly
480 # prefer temporary files to be unlinked for security,
481 # performance and reliability reasons, so utime is out. No-op
482 # changes with chmod doesn't update ctime on all filesystems; so
483 # we increment our counter each and every time.
484 tempfile.chmod(nr += 1)
496 process_client(client)
497 rescue Errno::ECONNABORTED
498 # client closed the socket even before accept
499 client.close rescue nil
501 tempfile.chmod(nr += 1)
506 # make the following bet: if we accepted clients this round,
507 # we're probably reasonably busy, so avoid calling select(2)
508 # and try to do a blind non-blocking accept(2) on everything
509 # before we sleep again in select
510 if accepted || reopen_logs
514 tempfile.chmod(nr += 1)
515 # timeout used so we can detect parent death:
516 ret = IO.select(@listeners, nil, [rd], @timeout/2.0) or next
520 rescue Errno::EBADF => e
521 reopen_logs or exit(alive ? 1 : 0)
524 rescue SystemExit => e
528 logger.error "Unhandled listen loop exception #{e.inspect}."
529 logger.error e.backtrace.join("\n")
535 # delivers a signal to a worker and fails gracefully if the worker
536 # is no longer running.
537 def kill_worker(signal, pid)
539 Process.kill(signal, pid)
541 worker = @workers.delete(pid) and worker.tempfile.close rescue nil
545 # delivers a signal to each worker
546 def kill_each_worker(signal)
547 @workers.keys.each { |pid| kill_worker(signal, pid) }
550 # unlinks a PID file at given +path+ if it contains the current PID
551 # useful as an at_exit handler.
552 def unlink_pid_safe(path)
553 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
556 # returns a PID if a given path contains a non-stale PID file,
559 if File.exist?(path) && (pid = File.read(path).to_i) > 1
571 logger.info "reloading config_file=#{@config.config_file}"
573 @config.commit!(self)
574 kill_each_worker(:QUIT)
575 logger.info "done reloading config_file=#{@config.config_file}"
577 logger.error "error reloading config_file=#{@config.config_file}: " \
578 "#{e.class} #{e.message}"
582 # returns an array of string names for the given listener array
583 def listener_names(listeners = @listeners)
584 listeners.map { |io| sock_name(io) }
588 @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0