1 # -*- encoding: binary -*-
3 # This is the process manager of Unicorn. This manages worker
4 # processes which in turn handle the I/O and application process.
5 # Listener sockets are started in the master process and shared with
6 # forked worker children.
8 # Users do not need to know the internals of this class, but reading the
9 # {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb]
10 # is education for programmers wishing to learn how \Unicorn works.
11 # See Unicorn::Configurator for information on how to configure \Unicorn.
12 class Unicorn::HttpServer
14 attr_accessor :app, :timeout, :worker_processes,
15 :before_fork, :after_fork, :before_exec,
16 :listener_opts, :preload_app,
17 :orig_app, :config, :ready_pipe, :user
19 attr_reader :pid, :logger
20 include Unicorn::SocketHelper
21 include Unicorn::HttpResponse
23 # all bound listener sockets
24 # note: this is public used by raindrops, but not recommended for use
28 # listeners we have yet to bind
32 # We populate this at startup so we can figure out how to reexecute
33 # and upgrade the currently running instance of Unicorn
34 # This Hash is considered a stable interface and changing its contents
35 # will allow you to switch between different installations of Unicorn
36 # or even different installations of the same applications without
37 # downtime. Keys of this constant Hash are described as follows:
39 # * 0 - the path to the unicorn/unicorn_rails executable
40 # * :argv - a deep copy of the ARGV array the executable originally saw
41 # * :cwd - the working directory of the application, this is where
42 # you originally started Unicorn.
44 # To change your unicorn executable to a different path without downtime,
45 # you can set the following in your Unicorn config file, HUP and then
46 # continue with the traditional USR2 + QUIT upgrade steps:
48 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/2.2.0/bin/unicorn"
50 :argv => ARGV.map(&:dup),
53 # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
55 START_CTX[:cwd] = begin
56 a = File.stat(pwd = ENV['PWD'])
57 b = File.stat(Dir.pwd)
58 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
64 # Creates a working server on host:port (strange things happen if
65 # port isn't a Number). Use HttpServer::run to start the server and
66 # HttpServer.run.join to join the thread that's processing
67 # incoming requests on the socket.
68 def initialize(app, options = {})
70 @request = Unicorn::HttpRequest.new
73 @ready_pipe = options.delete(:ready_pipe)
74 @init_listeners = options[:listeners] ? options[:listeners].dup : []
75 options[:use_defaults] = true
76 self.config = Unicorn::Configurator.new(options)
77 self.listener_opts = {}
79 # We use @self_pipe differently in the master and worker processes:
81 # * The master process never closes or reinitializes this once
82 # initialized. Signal handlers in the master process will write to
83 # it to wake up the master from IO.select in exactly the same manner
84 # djb describes in http://cr.yp.to/docs/selfpipe.html
86 # * The workers immediately close the pipe they inherit. See the
87 # Unicorn::Worker class for the pipe workers use.
89 @workers = {} # hash maps PIDs to Workers
90 @sig_queue = [] # signal queue used for self-piping
92 # we try inheriting listeners first, so we bind them later.
93 # we don't write the pid file until we've bound listeners in case
94 # unicorn was started twice by mistake. Even though our #pid= method
95 # checks for stale/existing pid files, race conditions are still
96 # possible (and difficult/non-portable to avoid) and can be likely
97 # to clobber the pid if the second start was in quick succession
98 # after the first, so we rely on the listener binding to fail in
99 # that case. Some tests (in and outside of this source tree) and
100 # monitoring tools may also rely on pid files existing before we
101 # attempt to connect to the listener(s)
102 config.commit!(self, :skip => [:listeners, :pid])
104 # list of signals we care about and trap in master.
106 :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
109 # Runs the thing. Returns self so you can run join on it
112 # this pipe is used to wake us up from select(2) in #join when signals
113 # are trapped. See trap_deferred.
114 @self_pipe.replace(Unicorn.pipe)
117 # setup signal handlers before writing pid file in case people get
118 # trigger happy and send signals as soon as the pid file exists.
119 # Note that signals don't actually get handled until the #join method
120 @queue_sigs.each { |sig| trap(sig) { @sig_queue << sig; awaken_master } }
121 trap(:CHLD) { awaken_master }
123 # write pid early for Mongrel compatibility if we're not inheriting sockets
124 # This is needed for compatibility some Monit setups at least.
125 # This unfortunately has the side effect of clobbering valid PID if
126 # we upgrade and the upgrade breaks during preload_app==true && build_app!
127 self.pid = config[:pid]
129 build_app! if preload_app
132 spawn_missing_workers
136 # replaces current listener set with +listeners+. This will
137 # close the socket if it will not exist in the new listener set
138 def listeners=(listeners)
139 cur_names, dead_names = [], []
140 listener_names.each do |name|
142 # mark unlinked sockets as dead so we can rebind them
143 (File.socket?(name) ? cur_names : dead_names) << name
148 set_names = listener_names(listeners)
149 dead_names.concat(cur_names - set_names).uniq!
151 LISTENERS.delete_if do |io|
152 if dead_names.include?(sock_name(io))
153 (io.close rescue nil).nil? # true
155 set_server_sockopt(io, listener_opts[sock_name(io)])
160 (set_names - cur_names).each { |addr| listen(addr) }
163 def stdout_path=(path); redirect_io($stdout, path); end
164 def stderr_path=(path); redirect_io($stderr, path); end
167 Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
170 def clobber_pid(path)
171 unlink_pid_safe(@pid) if @pid
174 tmp = "#{File.dirname(path)}/#{rand}.#$$"
175 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
180 File.rename(fp.path, path)
185 # sets the path for the PID file of the master process
188 if x = valid_pid?(path)
189 return path if pid && path == pid && x == $$
190 if x == @reexec_pid && pid.end_with?('.oldbin')
191 logger.warn("will not set pid=#{path} while reexec-ed "\
192 "child is running PID:#{x}")
195 raise ArgumentError, "Already running on PID:#{x} " \
196 "(or pid=#{path} is stale)"
200 # rename the old pid if possible
203 File.rename(@pid, path)
204 rescue Errno::ENOENT, Errno::EXDEV
205 # a user may have accidentally removed the original,
206 # obviously cross-FS renames don't work, either.
215 # add a given address to the +listeners+ set, idempotently
216 # Allows workers to add a private, per-process listener via the
217 # after_fork hook. Very useful for debugging and testing.
218 # +:tries+ may be specified as an option for the number of times
219 # to retry, and +:delay+ may be specified as the time in seconds
220 # to delay between retries.
221 # A negative value for +:tries+ indicates the listen will be
222 # retried indefinitely, this is useful when workers belonging to
223 # different masters are spawned during a transparent upgrade.
224 def listen(address, opt = {}.merge(listener_opts[address] || {}))
225 address = config.expand_addr(address)
226 return if String === address && listener_names.include?(address)
228 delay = opt[:delay] || 0.5
229 tries = opt[:tries] || 5
231 io = bind_listen(address, opt)
232 unless Kgio::TCPServer === io || Kgio::UNIXServer === io
236 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
239 rescue Errno::EADDRINUSE => err
240 logger.error "adding listener failed addr=#{address} (in use)"
241 raise err if tries == 0
243 logger.error "retrying in #{delay} seconds " \
244 "(#{tries < 0 ? 'infinite' : tries} tries left)"
248 logger.fatal "error adding listener addr=#{address}"
253 # monitors children and receives signals forever
254 # (or until a termination signal is sent). This handles signals
255 # one-at-a-time time and we'll happily drop signals in case somebody
256 # is signalling us too often.
259 last_check = time_now
262 logger.info "master process ready" # test_exec.rb relies on this message
265 @ready_pipe.syswrite($$.to_s)
267 logger.warn("grandparent died too soon?: #{e.message} (#{e.class})")
269 @ready_pipe = @ready_pipe.close rescue nil
273 case @sig_queue.shift
275 # avoid murdering workers after our master process (or the
276 # machine) comes out of suspend/hibernation
277 if (last_check + @timeout) >= (last_check = time_now)
278 sleep_time = murder_lazy_workers
280 sleep_time = @timeout/2.0 + 1
281 @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
283 maintain_worker_count if respawn
284 master_sleep(sleep_time)
285 when :QUIT # graceful shutdown
287 when :TERM, :INT # immediate shutdown
290 when :USR1 # rotate logs
291 logger.info "master reopening logs..."
292 Unicorn::Util.reopen_logs
293 logger.info "master done reopening logs"
294 soft_kill_each_worker(:USR1)
295 when :USR2 # exec binary, stay alive in case something went wrong
299 logger.info "SIGWINCH ignored because we're not daemonized"
302 logger.info "gracefully stopping all workers"
303 soft_kill_each_worker(:QUIT)
304 self.worker_processes = 0
308 self.worker_processes += 1
310 self.worker_processes -= 1 if self.worker_processes > 0
313 if config.config_file
315 else # exec binary and exit if there's no config file
316 logger.info "config_file not present, reexecuting binary"
321 Unicorn.log_error(@logger, "master loop error", e)
323 stop # gracefully shutdown all workers on our way out
324 logger.info "master complete"
325 unlink_pid_safe(pid) if pid
328 # Terminates all workers, but does not exit master process
329 def stop(graceful = true)
331 limit = time_now + timeout
332 until @workers.empty? || time_now > limit
334 soft_kill_each_worker(:QUIT)
336 kill_each_worker(:TERM)
341 kill_each_worker(:KILL)
345 Unicorn::HttpRequest.input_class.method_defined?(:rewind)
348 def rewindable_input=(bool)
349 Unicorn::HttpRequest.input_class = bool ?
350 Unicorn::TeeInput : Unicorn::StreamInput
353 def client_body_buffer_size
354 Unicorn::TeeInput.client_body_buffer_size
357 def client_body_buffer_size=(bytes)
358 Unicorn::TeeInput.client_body_buffer_size = bytes
361 def check_client_connection
362 Unicorn::HttpRequest.check_client_connection
365 def check_client_connection=(bool)
366 Unicorn::HttpRequest.check_client_connection = bool
371 # wait for a signal hander to wake us up and then consume the pipe
372 def master_sleep(sec)
373 @self_pipe[0].kgio_wait_readable(sec) or return
374 # 11 bytes is the maximum string length which can be embedded within
375 # the Ruby itself and not require a separate malloc (on 32-bit MRI 1.9+).
376 # Most reads are only one byte here and uncommon, so it's not worth a
377 # persistent buffer, either:
378 @self_pipe[0].kgio_tryread(11)
382 return if $$ != @master_pid
383 @self_pipe[1].kgio_trywrite('.') # wakeup master process from select
386 # reaps all unreaped workers
389 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
391 if @reexec_pid == wpid
392 logger.error "reaped #{status.inspect} exec()-ed"
394 self.pid = pid.chomp('.oldbin') if pid
397 worker = @workers.delete(wpid) and worker.close rescue nil
398 m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
399 status.success? ? logger.info(m) : logger.error(m)
406 # reexecutes the START_CTX with a new binary
410 Process.kill(0, @reexec_pid)
411 logger.error "reexec-ed child already running PID:#@reexec_pid"
419 old_pid = "#{pid}.oldbin"
421 self.pid = old_pid # clear the path for a new pid file
423 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
424 "existing pid=#{old_pid}, refusing rexec"
427 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
432 @reexec_pid = fork do
434 LISTENERS.each do |sock|
435 sock.close_on_exec = false
436 listener_fds[sock.fileno] = sock
438 ENV['UNICORN_FD'] = listener_fds.keys.join(',')
439 Dir.chdir(START_CTX[:cwd])
440 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
442 # avoid leaking FDs we don't know about, but let before_exec
443 # unset FD_CLOEXEC, if anything else in the app eventually
444 # relies on FD inheritence.
445 (3..1024).each do |io|
446 next if listener_fds.include?(io)
447 io = IO.for_fd(io) rescue next
449 io.close_on_exec = true
452 # exec(command, hash) works in at least 1.9.1+, but will only be
453 # required in 1.9.4/2.0.0 at earliest.
455 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
456 before_exec.call(self)
459 proc_name 'master (old)'
462 # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
463 def murder_lazy_workers
464 next_sleep = @timeout - 1
466 @workers.dup.each_pair do |wpid, worker|
468 0 == tick and next # skip workers that haven't processed any clients
470 tmp = @timeout - diff
472 next_sleep > tmp and next_sleep = tmp
476 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
477 "(#{diff}s > #{@timeout}s), killing"
478 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
480 next_sleep <= 0 ? 1 : next_sleep
483 def after_fork_internal
484 @self_pipe.each(&:close).clear # this is master-only, now
485 @ready_pipe.close if @ready_pipe
486 Unicorn::Configurator::RACKUP.clear
487 @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
489 # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/36450
490 srand # remove in unicorn 6
492 # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
493 # dying workers can recycle pids
494 OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
497 def spawn_missing_workers
499 until (worker_nr += 1) == @worker_processes
500 @workers.value?(worker_nr) and next
501 worker = Unicorn::Worker.new(worker_nr)
502 before_fork.call(self, worker)
504 @workers[pid] = worker
513 @logger.error(e) rescue nil
517 def maintain_worker_count
518 (off = @workers.size - worker_processes) == 0 and return
519 off < 0 and return spawn_missing_workers
520 @workers.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
523 # if we get any error, try to write something back to the client
524 # assuming we haven't closed the socket, but don't get hung up
525 # if the socket is already closed or broken. We'll always ensure
526 # the socket is closed at the end of this function
527 def handle_error(client, e)
529 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
530 # client disconnected on us and there's nothing we can do
531 when Unicorn::RequestURITooLongError
533 when Unicorn::RequestEntityTooLargeError
535 when Unicorn::HttpParserError # try to tell the client they're bad
538 Unicorn.log_error(@logger, "app error", e)
542 client.kgio_trywrite(err_response(code, @request.response_start_sent))
548 def e100_response_write(client, env)
549 # We use String#freeze to avoid allocations under Ruby 2.1+
550 # Not many users hit this code path, so it's better to reduce the
551 # constant table sizes even for 1.9.3-2.0 users who'll hit extra
553 client.write(@request.response_start_sent ?
554 "100 Continue\r\n\r\nHTTP/1.1 ".freeze :
555 "HTTP/1.1 100 Continue\r\n\r\n".freeze)
556 env.delete('HTTP_EXPECT'.freeze)
559 # once a client is accepted, it is processed in its entirety here
560 # in 3 easy steps: read request, call app, write app response
561 def process_client(client)
562 status, headers, body = @app.call(env = @request.read(client))
565 return if @request.hijacked?
567 if 100 == status.to_i
568 e100_response_write(client, env)
569 status, headers, body = @app.call(env)
570 return if @request.hijacked?
572 @request.headers? or headers = nil
573 http_response_write(client, status, headers, body,
574 @request.response_start_sent)
576 body.respond_to?(:close) and body.close
579 unless client.closed? # rack.hijack may've close this for us
580 client.shutdown # in case of fork() in Rack app
581 client.close # flush and uncork socket immediately, no keepalive
584 handle_error(client, e)
587 def nuke_listeners!(readers)
588 # only called from the worker, ordering is important here
590 readers.replace([false]) # ensure worker does not continue ASAP
591 tmp.each { |io| io.close rescue nil } # break out of IO.select
594 # gets rid of stuff the worker has no business keeping track of
595 # to free some resources and drops all sig handlers.
596 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
598 def init_worker_process(worker)
600 # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
601 exit_sigs = [ :QUIT, :TERM, :INT ]
602 exit_sigs.each { |sig| trap(sig) { exit!(0) } }
603 exit!(0) if (@sig_queue & exit_sigs)[0]
604 (@queue_sigs - exit_sigs).each { |sig| trap(sig, nil) }
605 trap(:CHLD, 'DEFAULT')
607 proc_name "worker[#{worker.nr}]"
611 after_fork.call(self, worker) # can drop perms and create listeners
612 LISTENERS.each { |sock| sock.close_on_exec = true }
614 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
615 self.timeout /= 2.0 # halve it for select()
617 build_app! unless preload_app
618 @after_fork = @listener_opts = @orig_app = nil
619 readers = LISTENERS.dup
621 trap(:QUIT) { nuke_listeners!(readers) }
625 def reopen_worker_logs(worker_nr)
626 logger.info "worker=#{worker_nr} reopening logs..."
627 Unicorn::Util.reopen_logs
628 logger.info "worker=#{worker_nr} done reopening logs"
630 logger.error(e) rescue nil
631 exit!(77) # EX_NOPERM in sysexits.h
634 # runs inside each forked worker, this sits around and waits
635 # for connections and doesn't die until the parent dies (or is
636 # given a INT, QUIT, or TERM signal)
637 def worker_loop(worker)
639 readers = init_worker_process(worker)
640 nr = 0 # this becomes negative if we need to reopen logs
642 # this only works immediately if the master sent us the signal
643 # (which is the normal case)
644 trap(:USR1) { nr = -65536 }
647 @logger.info "worker=#{worker.nr} ready"
650 nr < 0 and reopen_worker_logs(worker.nr)
652 worker.tick = time_now.to_i
654 while sock = tmp.shift
655 # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
656 # but that will return false
657 if client = sock.kgio_tryaccept
658 process_client(client)
660 worker.tick = time_now.to_i
665 # make the following bet: if we accepted clients this round,
666 # we're probably reasonably busy, so avoid calling select()
667 # and do a speculative non-blocking accept() on ready listeners
668 # before we sleep again in select().
674 ppid == Process.ppid or return
676 # timeout used so we can detect parent death:
677 worker.tick = time_now.to_i
678 ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
680 redo if nr < 0 && readers[0]
681 Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
685 # delivers a signal to a worker and fails gracefully if the worker
686 # is no longer running.
687 def kill_worker(signal, wpid)
688 Process.kill(signal, wpid)
690 worker = @workers.delete(wpid) and worker.close rescue nil
693 # delivers a signal to each worker
694 def kill_each_worker(signal)
695 @workers.keys.each { |wpid| kill_worker(signal, wpid) }
698 def soft_kill_each_worker(signal)
699 @workers.each_value { |worker| worker.soft_kill(signal) }
702 # unlinks a PID file at given +path+ if it contains the current PID
703 # still potentially racy without locking the directory (which is
704 # non-portable and may interact badly with other programs), but the
705 # window for hitting the race condition is small
706 def unlink_pid_safe(path)
707 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
710 # returns a PID if a given path contains a non-stale PID file,
713 wpid = File.read(path).to_i
715 Process.kill(0, wpid)
718 logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
720 rescue Errno::ESRCH, Errno::ENOENT
721 # don't unlink stale pid files, racy without non-portable locking...
726 logger.info "reloading config_file=#{config.config_file}"
727 config[:listeners].replace(@init_listeners)
730 soft_kill_each_worker(:QUIT)
731 Unicorn::Util.reopen_logs
733 build_app! if preload_app
734 logger.info "done reloading config_file=#{config.config_file}"
735 rescue StandardError, LoadError, SyntaxError => e
736 Unicorn.log_error(@logger,
737 "error reloading config_file=#{config.config_file}", e)
738 self.app = loaded_app
741 # returns an array of string names for the given listener array
742 def listener_names(listeners = LISTENERS)
743 listeners.map { |io| sock_name(io) }
747 if app.respond_to?(:arity) && app.arity == 0
748 if defined?(Gem) && Gem.respond_to?(:refresh)
749 logger.info "Refreshing Gem list"
757 $0 = ([ File.basename(START_CTX[0]), tag
758 ]).concat(START_CTX[:argv]).join(' ')
761 def redirect_io(io, path)
762 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
766 def inherit_listeners!
767 # inherit sockets from parents, they need to be plain Socket objects
768 # before they become Kgio::UNIXServer or Kgio::TCPServer
769 inherited = ENV['UNICORN_FD'].to_s.split(',')
771 # emulate sd_listen_fds() for systemd
772 sd_pid, sd_fds = ENV.values_at('LISTEN_PID', 'LISTEN_FDS')
773 if sd_pid && sd_pid.to_i == $$
774 # 3 = SD_LISTEN_FDS_START
775 inherited.concat((3...(3 + sd_fds.to_i)).map { |fd| Socket.for_fd(fd) })
777 # to ease debugging, we will not unset LISTEN_PID and LISTEN_FDS
779 inherited.map! do |fd|
780 io = String === fd ? Socket.for_fd(fd.to_i) : fd
783 set_server_sockopt(io, listener_opts[sock_name(io)])
784 logger.info "inherited addr=#{sock_name(io)} fd=#{io.fileno}"
788 config_listeners = config[:listeners].dup
789 LISTENERS.replace(inherited)
791 # we start out with generic Socket objects that get cast to either
792 # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
793 # objects share the same OS-level file descriptor as the higher-level
794 # *Server objects; we need to prevent Socket objects from being
796 config_listeners -= listener_names
797 if config_listeners.empty? && LISTENERS.empty?
798 config_listeners << Unicorn::Const::DEFAULT_LISTEN
799 @init_listeners << Unicorn::Const::DEFAULT_LISTEN
800 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
802 NEW_LISTENERS.replace(config_listeners)
805 # call only after calling inherit_listeners!
806 # This binds any listeners we did NOT inherit from the parent
807 def bind_new_listeners!
808 NEW_LISTENERS.each { |addr| listen(addr) }.clear
809 raise ArgumentError, "no listeners" if LISTENERS.empty?
812 # try to use the monotonic clock in Ruby >= 2.1, it is immune to clock
813 # offset adjustments and generates less garbage (Float vs Time object)
815 Process.clock_gettime(Process::CLOCK_MONOTONIC)
817 Process.clock_gettime(Process::CLOCK_MONOTONIC)
819 rescue NameError, NoMethodError
820 def time_now # Ruby <= 2.0