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 @init_listeners = options[:listeners] ? options[:listeners].dup : []
63 @config = Configurator.new(options.merge(:use_defaults => true))
65 @config.commit!(self, :skip => [:listeners, :pid])
69 # Runs the thing. Returns self so you can run join on it
71 BasicSocket.do_not_reverse_lookup = true
73 # inherit sockets from parents, they need to be plain Socket objects
74 # before they become UNIXServer or TCPServer
75 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
76 io = Socket.for_fd(fd.to_i)
77 set_server_sockopt(io)
79 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
83 config_listeners = @config[:listeners].dup
84 @listeners.replace(inherited)
86 # we start out with generic Socket objects that get cast to either
87 # TCPServer or UNIXServer objects; but since the Socket objects
88 # share the same OS-level file descriptor as the higher-level *Server
89 # objects; we need to prevent Socket objects from being garbage-collected
90 config_listeners -= listener_names
91 if config_listeners.empty? && @listeners.empty?
92 config_listeners << Unicorn::Const::DEFAULT_LISTEN
94 config_listeners.each { |addr| listen(addr) }
95 raise ArgumentError, "no listeners" if @listeners.empty?
96 self.pid = @config[:pid]
97 build_app! if @preload_app
98 File.open(@stderr_path, "a") { |fp| $stderr.reopen(fp) } if @stderr_path
99 File.open(@stdout_path, "a") { |fp| $stdout.reopen(fp) } if @stdout_path
100 $stderr.sync = $stdout.sync = true
101 spawn_missing_workers
105 # replaces current listener set with +listeners+. This will
106 # close the socket if it will not exist in the new listener set
107 def listeners=(listeners)
108 cur_names, dead_names = [], []
109 listener_names.each do |name|
111 # mark unlinked sockets as dead so we can rebind them
112 (File.socket?(name) ? cur_names : dead_names) << name
117 set_names = listener_names(listeners)
118 dead_names += cur_names - set_names
121 @listeners.delete_if do |io|
122 if dead_names.include?(sock_name(io))
123 @io_purgatory.delete_if do |pio|
124 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
126 (io.close rescue nil).nil? # true
132 (set_names - cur_names).each { |addr| listen(addr) }
135 # sets the path for the PID file of the master process
138 if x = valid_pid?(path)
139 return path if @pid && path == @pid && x == $$
140 raise ArgumentError, "Already running on PID:#{x} " \
141 "(or pid=#{path} is stale)"
144 unlink_pid_safe(@pid) if @pid
145 File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
149 # add a given address to the +listeners+ set, idempotently
150 # Allows workers to add a private, per-process listener via the
151 # @after_fork hook. Very useful for debugging and testing.
152 def listen(address, opt = {}.merge(@listener_opts[address] || {}))
153 return if String === address && listener_names.include?(address)
155 if io = bind_listen(address, opt)
156 if Socket == io.class
160 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
163 logger.error "adding listener failed addr=#{address} (in use)"
164 raise Errno::EADDRINUSE, address
168 # monitors children and receives signals forever
169 # (or until a termination signal is sent). This handles signals
170 # one-at-a-time time and we'll happily drop signals in case somebody
171 # is signalling us too often.
173 # this pipe is used to wake us up from select(2) in #join when signals
174 # are trapped. See trap_deferred
175 @rd_sig, @wr_sig = IO.pipe unless (@rd_sig && @wr_sig)
179 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
180 trap(:CHLD) { |sig_nr| awaken_master }
182 logger.info "master process ready" # test_exec.rb relies on this message
186 case (mode = @sig_queue.shift)
189 spawn_missing_workers if respawn
191 when :QUIT # graceful shutdown
193 when :TERM, :INT # immediate shutdown
196 when :USR1 # rotate logs
197 logger.info "master rotating logs..."
198 Unicorn::Util.reopen_logs
199 logger.info "master done rotating logs"
200 kill_each_worker(:USR1)
201 when :USR2 # exec binary, stay alive in case something went wrong
204 if Process.ppid == 1 || Process.getpgrp != $$
206 logger.info "gracefully stopping all workers"
207 kill_each_worker(:QUIT)
209 logger.info "SIGWINCH ignored because we're not daemonized"
213 if @config.config_file
215 redo # immediate reaping since we may have QUIT workers
216 else # exec binary and exit if there's no config file
217 logger.info "config_file not present, reexecuting binary"
222 logger.error "master process in unknown mode: #{mode}"
228 logger.error "Unhandled master loop exception #{e.inspect}."
229 logger.error e.backtrace.join("\n")
232 stop # gracefully shutdown all workers on our way out
233 logger.info "master complete"
234 unlink_pid_safe(@pid) if @pid
237 # Terminates all workers, but does not exit master process
238 def stop(graceful = true)
239 kill_each_worker(graceful ? :QUIT : :TERM)
243 until @workers.empty?
246 (timeleft -= step) > 0 and next
247 kill_each_worker(:KILL)
255 # list of signals we care about and trap in master.
256 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP ].freeze
258 # defer a signal for later processing in #join (master process)
259 def trap_deferred(signal)
260 trap(signal) do |sig_nr|
261 if @sig_queue.size < 5
265 logger.error "ignoring SIG#{signal}, queue=#{@sig_queue.inspect}"
270 # wait for a signal hander to wake us up and then consume the pipe
271 # Wake up every second anyways to run murder_lazy_workers
274 ready = IO.select([@rd_sig], nil, nil, 1)
275 ready && ready[0] && ready[0][0] or return
276 loop { @rd_sig.read_nonblock(Const::CHUNK_SIZE) }
277 rescue Errno::EAGAIN, Errno::EINTR
283 @wr_sig.write_nonblock('.') # wakeup master process from IO.select
284 rescue Errno::EAGAIN, Errno::EINTR
285 # pipe is full, master should wake up anyways
290 # reaps all unreaped workers
294 pid, status = Process.waitpid2(-1, Process::WNOHANG)
296 if @reexec_pid == pid
297 logger.error "reaped #{status.inspect} exec()-ed"
299 self.pid = @pid.chomp('.oldbin') if @pid
302 worker = @workers.delete(pid)
303 worker.tempfile.close rescue nil
304 logger.info "reaped #{status.inspect} " \
305 "worker=#{worker.nr rescue 'unknown'}"
312 # reexecutes the @start_ctx with a new binary
316 Process.kill(0, @reexec_pid)
317 logger.error "reexec-ed child already running PID:#{@reexec_pid}"
325 old_pid = "#{@pid}.oldbin"
328 self.pid = old_pid # clear the path for a new pid file
330 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
331 "existing pid=#{old_pid}, refusing rexec"
334 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
339 @reexec_pid = fork do
340 ENV.replace(@start_ctx[:environ])
341 listener_fds = @listeners.map { |sock| sock.fileno }
342 ENV['UNICORN_FD'] = listener_fds.join(',')
343 File.umask(@start_ctx[:umask])
344 Dir.chdir(@start_ctx[:cwd])
345 cmd = [ @start_ctx[:zero] ] + @start_ctx[:argv]
347 # avoid leaking FDs we don't know about, but let before_exec
348 # unset FD_CLOEXEC, if anything else in the app eventually
349 # relies on FD inheritence.
350 purgatory = [] # prevent GC of IO objects
351 (3..1024).each do |io|
352 next if listener_fds.include?(io)
353 io = IO.for_fd(io) rescue nil
356 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
358 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
359 @before_exec.call(self) if @before_exec
362 proc_name 'master (old)'
365 # forcibly terminate all workers that haven't checked in in @timeout
366 # seconds. The timeout is implemented using an unlinked tempfile
367 # shared between the parent process and each worker. The worker
368 # runs File#chmod to modify the ctime of the tempfile. If the ctime
369 # is stale for >@timeout seconds, then we'll kill the corresponding
371 def murder_lazy_workers
373 @workers.each_pair do |pid, worker|
374 (now - worker.tempfile.ctime) <= @timeout and next
375 logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
376 kill_worker(:KILL, pid) # take no prisoners for @timeout violations
377 worker.tempfile.close rescue nil
381 def spawn_missing_workers
382 return if @workers.size == @worker_processes
383 (0...@worker_processes).each do |worker_nr|
384 @workers.values.include?(worker_nr) and next
386 Dir.chdir(@start_ctx[:cwd])
387 rescue Errno::ENOENT => err
388 logger.fatal "#{err.inspect} (#{@start_ctx[:cwd]})"
389 @sig_queue << :QUIT # forcibly emulate SIGQUIT
392 tempfile = Tempfile.new('') # as short as possible to save dir space
393 tempfile.unlink # don't allow other processes to find or see it
395 worker = Worker.new(worker_nr, tempfile)
396 @before_fork.call(self, worker.nr)
397 pid = fork { worker_loop(worker) }
398 @workers[pid] = worker
402 # once a client is accepted, it is processed in its entirety here
403 # in 3 easy steps: read request, call app, write app response
404 def process_client(client)
405 client.nonblock = false
406 set_client_sockopt(client) if TCPSocket === client
407 env = @request.read(client)
408 app_response = @app.call(env)
409 HttpResponse.write(client, app_response)
410 # if we get any error, try to write something back to the client
411 # assuming we haven't closed the socket, but don't get hung up
412 # if the socket is already closed or broken. We'll always ensure
413 # the socket is closed at the end of this function
414 rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
415 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
416 rescue HttpParserError # try to tell the client they're bad
417 client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
419 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
420 logger.error "Read error: #{e.inspect}"
421 logger.error e.backtrace.join("\n")
424 client.closed? or client.close
426 logger.error "Client error: #{e.inspect}"
427 logger.error e.backtrace.join("\n")
432 # gets rid of stuff the worker has no business keeping track of
433 # to free some resources and drops all sig handlers.
434 # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
436 def init_worker_process(worker)
437 build_app! unless @preload_app
439 QUEUE_SIGS.each { |sig| trap(sig, 'IGNORE') }
440 trap(:CHLD, 'DEFAULT')
442 proc_name "worker[#{worker.nr}]"
443 @rd_sig.close if @rd_sig
444 @wr_sig.close if @wr_sig
445 @workers.values.each { |other| other.tempfile.close rescue nil }
448 @start_ctx = @workers = @rd_sig = @wr_sig = nil
449 @listeners.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
450 ENV.delete('UNICORN_FD')
451 @after_fork.call(self, worker.nr) if @after_fork
452 worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
453 @request = HttpRequest.new(logger)
456 # runs inside each forked worker, this sits around and waits
457 # for connections and doesn't die until the parent dies (or is
458 # given a INT, QUIT, or TERM signal)
459 def worker_loop(worker)
460 init_worker_process(worker)
462 tempfile = worker.tempfile
466 [:TERM, :INT].each { |sig| trap(sig) { exit(0) } } # instant shutdown
469 @listeners.each { |sock| sock.close rescue nil } # break IO.select
471 reopen_logs, (rd, wr) = false, IO.pipe
472 rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
473 wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
474 trap(:USR1) { reopen_logs = true; rd.close rescue nil } # break IO.select
475 @logger.info "worker=#{worker.nr} ready"
477 while alive && @master_pid == Process.ppid
480 @logger.info "worker=#{worker.nr} rotating logs..."
481 Unicorn::Util.reopen_logs
482 @logger.info "worker=#{worker.nr} done rotating logs"
485 rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
486 wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
488 # we're a goner in @timeout seconds anyways if tempfile.chmod
489 # breaks, so don't trap the exception. Using fchmod() since
490 # futimes() is not available in base Ruby and I very strongly
491 # prefer temporary files to be unlinked for security,
492 # performance and reliability reasons, so utime is out. No-op
493 # changes with chmod doesn't update ctime on all filesystems; so
494 # we increment our counter each and every time.
495 tempfile.chmod(nr += 1)
507 process_client(client)
508 rescue Errno::ECONNABORTED
509 # client closed the socket even before accept
510 client.close rescue nil
512 tempfile.chmod(nr += 1)
517 # make the following bet: if we accepted clients this round,
518 # we're probably reasonably busy, so avoid calling select(2)
519 # and try to do a blind non-blocking accept(2) on everything
520 # before we sleep again in select
521 if accepted || reopen_logs
525 tempfile.chmod(nr += 1)
526 # timeout used so we can detect parent death:
527 ret = IO.select(@listeners, nil, [rd], @timeout/2.0) or next
531 rescue Errno::EBADF => e
532 reopen_logs or exit(alive ? 1 : 0)
535 rescue SystemExit => e
539 logger.error "Unhandled listen loop exception #{e.inspect}."
540 logger.error e.backtrace.join("\n")
546 # delivers a signal to a worker and fails gracefully if the worker
547 # is no longer running.
548 def kill_worker(signal, pid)
550 Process.kill(signal, pid)
552 worker = @workers.delete(pid) and worker.tempfile.close rescue nil
556 # delivers a signal to each worker
557 def kill_each_worker(signal)
558 @workers.keys.each { |pid| kill_worker(signal, pid) }
561 # unlinks a PID file at given +path+ if it contains the current PID
562 # useful as an at_exit handler.
563 def unlink_pid_safe(path)
564 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
567 # returns a PID if a given path contains a non-stale PID file,
570 if File.exist?(path) && (pid = File.read(path).to_i) > 1
582 logger.info "reloading config_file=#{@config.config_file}"
583 @config[:listeners].replace(@init_listeners)
585 @config.commit!(self)
586 kill_each_worker(:QUIT)
587 logger.info "done reloading config_file=#{@config.config_file}"
589 logger.error "error reloading config_file=#{@config.config_file}: " \
590 "#{e.class} #{e.message}"
594 # returns an array of string names for the given listener array
595 def listener_names(listeners = @listeners)
596 listeners.map { |io| sock_name(io) }
600 @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0
604 $0 = ([ File.basename(@start_ctx[:zero]), tag ] +
605 @start_ctx[:argv]).join(' ')