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, :request, :timeout, :worker_processes,
15 :before_fork, :after_fork, :before_exec,
16 :listener_opts, :preload_app,
17 :reexec_pid, :orig_app, :init_listeners,
18 :master_pid, :config, :ready_pipe, :user
20 attr_reader :pid, :logger
21 include Unicorn::SocketHelper
22 include Unicorn::HttpResponse
24 # backwards compatibility with 1.x
25 Worker = Unicorn::Worker
27 # all bound listener sockets
30 # listeners we have yet to bind
33 # This hash maps PIDs to Workers
36 # We use SELF_PIPE differently in the master and worker processes:
38 # * The master process never closes or reinitializes this once
39 # initialized. Signal handlers in the master process will write to
40 # it to wake up the master from IO.select in exactly the same manner
41 # djb describes in http://cr.yp.to/docs/selfpipe.html
43 # * The workers immediately close the pipe they inherit. See the
44 # Unicorn::Worker class for the pipe workers use.
47 # signal queue used for self-piping
50 # list of signals we care about and trap in master.
51 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
54 # We populate this at startup so we can figure out how to reexecute
55 # and upgrade the currently running instance of Unicorn
56 # This Hash is considered a stable interface and changing its contents
57 # will allow you to switch between different installations of Unicorn
58 # or even different installations of the same applications without
59 # downtime. Keys of this constant Hash are described as follows:
61 # * 0 - the path to the unicorn/unicorn_rails executable
62 # * :argv - a deep copy of the ARGV array the executable originally saw
63 # * :cwd - the working directory of the application, this is where
64 # you originally started Unicorn.
66 # To change your unicorn executable to a different path without downtime,
67 # you can set the following in your Unicorn config file, HUP and then
68 # continue with the traditional USR2 + QUIT upgrade steps:
70 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/2.2.0/bin/unicorn"
72 :argv => ARGV.map(&:dup),
75 # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
77 START_CTX[:cwd] = begin
78 a = File.stat(pwd = ENV['PWD'])
79 b = File.stat(Dir.pwd)
80 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
86 # Creates a working server on host:port (strange things happen if
87 # port isn't a Number). Use HttpServer::run to start the server and
88 # HttpServer.run.join to join the thread that's processing
89 # incoming requests on the socket.
90 def initialize(app, options = {})
92 @request = Unicorn::HttpRequest.new
95 @ready_pipe = options.delete(:ready_pipe)
96 @init_listeners = options[:listeners] ? options[:listeners].dup : []
97 options[:use_defaults] = true
98 self.config = Unicorn::Configurator.new(options)
99 self.listener_opts = {}
101 # we try inheriting listeners first, so we bind them later.
102 # we don't write the pid file until we've bound listeners in case
103 # unicorn was started twice by mistake. Even though our #pid= method
104 # checks for stale/existing pid files, race conditions are still
105 # possible (and difficult/non-portable to avoid) and can be likely
106 # to clobber the pid if the second start was in quick succession
107 # after the first, so we rely on the listener binding to fail in
108 # that case. Some tests (in and outside of this source tree) and
109 # monitoring tools may also rely on pid files existing before we
110 # attempt to connect to the listener(s)
111 config.commit!(self, :skip => [:listeners, :pid])
115 # Runs the thing. Returns self so you can run join on it
118 # this pipe is used to wake us up from select(2) in #join when signals
119 # are trapped. See trap_deferred.
120 SELF_PIPE.replace(Unicorn.pipe)
123 # setup signal handlers before writing pid file in case people get
124 # trigger happy and send signals as soon as the pid file exists.
125 # Note that signals don't actually get handled until the #join method
126 QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
127 trap(:CHLD) { awaken_master }
129 # write pid early for Mongrel compatibility if we're not inheriting sockets
130 # This is needed for compatibility some Monit setups at least.
131 # This unfortunately has the side effect of clobbering valid PID if
132 # we upgrade and the upgrade breaks during preload_app==true && build_app!
133 self.pid = config[:pid]
135 build_app! if preload_app
138 spawn_missing_workers
142 # replaces current listener set with +listeners+. This will
143 # close the socket if it will not exist in the new listener set
144 def listeners=(listeners)
145 cur_names, dead_names = [], []
146 listener_names.each do |name|
148 # mark unlinked sockets as dead so we can rebind them
149 (File.socket?(name) ? cur_names : dead_names) << name
154 set_names = listener_names(listeners)
155 dead_names.concat(cur_names - set_names).uniq!
157 LISTENERS.delete_if do |io|
158 if dead_names.include?(sock_name(io))
159 (io.close rescue nil).nil? # true
161 set_server_sockopt(io, listener_opts[sock_name(io)])
166 (set_names - cur_names).each { |addr| listen(addr) }
169 def stdout_path=(path); redirect_io($stdout, path); end
170 def stderr_path=(path); redirect_io($stderr, path); end
173 Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
176 def clobber_pid(path)
177 unlink_pid_safe(@pid) if @pid
180 tmp = "#{File.dirname(path)}/#{rand}.#$$"
181 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
186 File.rename(fp.path, path)
191 # sets the path for the PID file of the master process
194 if x = valid_pid?(path)
195 return path if pid && path == pid && x == $$
196 if x == reexec_pid && pid =~ /\.oldbin\z/
197 logger.warn("will not set pid=#{path} while reexec-ed "\
198 "child is running PID:#{x}")
201 raise ArgumentError, "Already running on PID:#{x} " \
202 "(or pid=#{path} is stale)"
206 # rename the old pid if possible
209 File.rename(@pid, path)
210 rescue Errno::ENOENT, Errno::EXDEV
211 # a user may have accidentally removed the original,
212 # obviously cross-FS renames don't work, either.
221 # add a given address to the +listeners+ set, idempotently
222 # Allows workers to add a private, per-process listener via the
223 # after_fork hook. Very useful for debugging and testing.
224 # +:tries+ may be specified as an option for the number of times
225 # to retry, and +:delay+ may be specified as the time in seconds
226 # to delay between retries.
227 # A negative value for +:tries+ indicates the listen will be
228 # retried indefinitely, this is useful when workers belonging to
229 # different masters are spawned during a transparent upgrade.
230 def listen(address, opt = {}.merge(listener_opts[address] || {}))
231 address = config.expand_addr(address)
232 return if String === address && listener_names.include?(address)
234 delay = opt[:delay] || 0.5
235 tries = opt[:tries] || 5
237 io = bind_listen(address, opt)
238 unless Kgio::TCPServer === io || Kgio::UNIXServer === io
242 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
245 rescue Errno::EADDRINUSE => err
246 logger.error "adding listener failed addr=#{address} (in use)"
247 raise err if tries == 0
249 logger.error "retrying in #{delay} seconds " \
250 "(#{tries < 0 ? 'infinite' : tries} tries left)"
254 logger.fatal "error adding listener addr=#{address}"
259 # monitors children and receives signals forever
260 # (or until a termination signal is sent). This handles signals
261 # one-at-a-time time and we'll happily drop signals in case somebody
262 # is signalling us too often.
265 last_check = time_now
268 logger.info "master process ready" # test_exec.rb relies on this message
271 @ready_pipe.syswrite($$.to_s)
273 logger.warn("grandparent died too soon?: #{e.message} (#{e.class})")
275 @ready_pipe = @ready_pipe.close rescue nil
281 # avoid murdering workers after our master process (or the
282 # machine) comes out of suspend/hibernation
283 if (last_check + @timeout) >= (last_check = time_now)
284 sleep_time = murder_lazy_workers
286 sleep_time = @timeout/2.0 + 1
287 @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
289 maintain_worker_count if respawn
290 master_sleep(sleep_time)
291 when :QUIT # graceful shutdown
293 when :TERM, :INT # immediate shutdown
296 when :USR1 # rotate logs
297 logger.info "master reopening logs..."
298 Unicorn::Util.reopen_logs
299 logger.info "master done reopening logs"
300 soft_kill_each_worker(:USR1)
301 when :USR2 # exec binary, stay alive in case something went wrong
304 if Unicorn::Configurator::RACKUP[:daemonized]
306 logger.info "gracefully stopping all workers"
307 soft_kill_each_worker(:QUIT)
308 self.worker_processes = 0
310 logger.info "SIGWINCH ignored because we're not daemonized"
314 self.worker_processes += 1
316 self.worker_processes -= 1 if self.worker_processes > 0
319 if config.config_file
321 else # exec binary and exit if there's no config file
322 logger.info "config_file not present, reexecuting binary"
327 Unicorn.log_error(@logger, "master loop error", e)
329 stop # gracefully shutdown all workers on our way out
330 logger.info "master complete"
331 unlink_pid_safe(pid) if pid
334 # Terminates all workers, but does not exit master process
335 def stop(graceful = true)
337 limit = time_now + timeout
338 until WORKERS.empty? || time_now > limit
340 soft_kill_each_worker(:QUIT)
342 kill_each_worker(:TERM)
347 kill_each_worker(:KILL)
351 Unicorn::HttpRequest.input_class.method_defined?(:rewind)
354 def rewindable_input=(bool)
355 Unicorn::HttpRequest.input_class = bool ?
356 Unicorn::TeeInput : Unicorn::StreamInput
359 def client_body_buffer_size
360 Unicorn::TeeInput.client_body_buffer_size
363 def client_body_buffer_size=(bytes)
364 Unicorn::TeeInput.client_body_buffer_size = bytes
367 def check_client_connection
368 Unicorn::HttpRequest.check_client_connection
371 def check_client_connection=(bool)
372 Unicorn::HttpRequest.check_client_connection = bool
377 # wait for a signal hander to wake us up and then consume the pipe
378 def master_sleep(sec)
379 IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
380 SELF_PIPE[0].kgio_tryread(11)
384 return if $$ != @master_pid
385 SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
388 # reaps all unreaped workers
391 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
393 if reexec_pid == wpid
394 logger.error "reaped #{status.inspect} exec()-ed"
396 self.pid = pid.chomp('.oldbin') if pid
399 worker = WORKERS.delete(wpid) and worker.close rescue nil
400 m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
401 status.success? ? logger.info(m) : logger.error(m)
408 # reexecutes the START_CTX with a new binary
412 Process.kill(0, reexec_pid)
413 logger.error "reexec-ed child already running PID:#{reexec_pid}"
421 old_pid = "#{pid}.oldbin"
423 self.pid = old_pid # clear the path for a new pid file
425 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
426 "existing pid=#{old_pid}, refusing rexec"
429 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
434 self.reexec_pid = fork do
436 LISTENERS.each do |sock|
437 sock.close_on_exec = false
438 listener_fds[sock.fileno] = sock
440 ENV['UNICORN_FD'] = listener_fds.keys.join(',')
441 Dir.chdir(START_CTX[:cwd])
442 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
444 # avoid leaking FDs we don't know about, but let before_exec
445 # unset FD_CLOEXEC, if anything else in the app eventually
446 # relies on FD inheritence.
447 (3..1024).each do |io|
448 next if listener_fds.include?(io)
449 io = IO.for_fd(io) rescue next
451 io.close_on_exec = true
454 # exec(command, hash) works in at least 1.9.1+, but will only be
455 # required in 1.9.4/2.0.0 at earliest.
457 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
458 before_exec.call(self)
461 proc_name 'master (old)'
464 # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
465 def murder_lazy_workers
466 next_sleep = @timeout - 1
468 WORKERS.dup.each_pair do |wpid, worker|
470 0 == tick and next # skip workers that haven't processed any clients
472 tmp = @timeout - diff
474 next_sleep > tmp and next_sleep = tmp
478 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
479 "(#{diff}s > #{@timeout}s), killing"
480 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
482 next_sleep <= 0 ? 1 : next_sleep
485 def after_fork_internal
486 SELF_PIPE.each(&:close).clear # this is master-only, now
487 @ready_pipe.close if @ready_pipe
488 Unicorn::Configurator::RACKUP.clear
489 @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
491 srand # http://redmine.ruby-lang.org/issues/4338
493 # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
494 # dying workers can recycle pids
495 OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
498 def spawn_missing_workers
500 until (worker_nr += 1) == @worker_processes
501 WORKERS.value?(worker_nr) and next
502 worker = Worker.new(worker_nr)
503 before_fork.call(self, worker)
505 WORKERS[pid] = worker
514 @logger.error(e) rescue nil
518 def maintain_worker_count
519 (off = WORKERS.size - worker_processes) == 0 and return
520 off < 0 and return spawn_missing_workers
521 WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
524 # if we get any error, try to write something back to the client
525 # assuming we haven't closed the socket, but don't get hung up
526 # if the socket is already closed or broken. We'll always ensure
527 # the socket is closed at the end of this function
528 def handle_error(client, e)
530 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
531 # client disconnected on us and there's nothing we can do
532 when Unicorn::RequestURITooLongError
534 when Unicorn::RequestEntityTooLargeError
536 when Unicorn::HttpParserError # try to tell the client they're bad
539 Unicorn.log_error(@logger, "app error", e)
543 client.kgio_trywrite(err_response(code, @request.response_start_sent))
549 def expect_100_response
550 if @request.response_start_sent
551 Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED
553 Unicorn::Const::EXPECT_100_RESPONSE
557 # once a client is accepted, it is processed in its entirety here
558 # in 3 easy steps: read request, call app, write app response
559 def process_client(client)
560 status, headers, body = @app.call(env = @request.read(client))
561 return if @request.hijacked?
563 if 100 == status.to_i
564 client.write(expect_100_response)
565 env.delete(Unicorn::Const::HTTP_EXPECT)
566 status, headers, body = @app.call(env)
567 return if @request.hijacked?
569 @request.headers? or headers = nil
570 http_response_write(client, status, headers, body,
571 @request.response_start_sent)
572 unless client.closed? # rack.hijack may've close this for us
573 client.shutdown # in case of fork() in Rack app
574 client.close # flush and uncork socket immediately, no keepalive
577 handle_error(client, e)
580 EXIT_SIGS = [ :QUIT, :TERM, :INT ]
581 WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
583 def nuke_listeners!(readers)
584 # only called from the worker, ordering is important here
586 readers.replace([false]) # ensure worker does not continue ASAP
587 tmp.each { |io| io.close rescue nil } # break out of IO.select
590 # gets rid of stuff the worker has no business keeping track of
591 # to free some resources and drops all sig handlers.
592 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
594 def init_worker_process(worker)
596 # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
597 EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
598 exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
599 WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
600 trap(:CHLD, 'DEFAULT')
602 proc_name "worker[#{worker.nr}]"
606 after_fork.call(self, worker) # can drop perms and create listeners
607 LISTENERS.each { |sock| sock.close_on_exec = true }
609 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
610 self.timeout /= 2.0 # halve it for select()
612 build_app! unless preload_app
613 @after_fork = @listener_opts = @orig_app = nil
614 readers = LISTENERS.dup
616 trap(:QUIT) { nuke_listeners!(readers) }
620 def reopen_worker_logs(worker_nr)
621 logger.info "worker=#{worker_nr} reopening logs..."
622 Unicorn::Util.reopen_logs
623 logger.info "worker=#{worker_nr} done reopening logs"
625 logger.error(e) rescue nil
626 exit!(77) # EX_NOPERM in sysexits.h
629 # runs inside each forked worker, this sits around and waits
630 # for connections and doesn't die until the parent dies (or is
631 # given a INT, QUIT, or TERM signal)
632 def worker_loop(worker)
634 readers = init_worker_process(worker)
635 nr = 0 # this becomes negative if we need to reopen logs
637 # this only works immediately if the master sent us the signal
638 # (which is the normal case)
639 trap(:USR1) { nr = -65536 }
642 @logger.info "worker=#{worker.nr} ready"
645 nr < 0 and reopen_worker_logs(worker.nr)
647 worker.tick = time_now.to_i
649 while sock = tmp.shift
650 # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
651 # but that will return false
652 if client = sock.kgio_tryaccept
653 process_client(client)
655 worker.tick = time_now.to_i
660 # make the following bet: if we accepted clients this round,
661 # we're probably reasonably busy, so avoid calling select()
662 # and do a speculative non-blocking accept() on ready listeners
663 # before we sleep again in select().
669 ppid == Process.ppid or return
671 # timeout used so we can detect parent death:
672 worker.tick = time_now.to_i
673 ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
675 redo if nr < 0 && readers[0]
676 Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
680 # delivers a signal to a worker and fails gracefully if the worker
681 # is no longer running.
682 def kill_worker(signal, wpid)
683 Process.kill(signal, wpid)
685 worker = WORKERS.delete(wpid) and worker.close rescue nil
688 # delivers a signal to each worker
689 def kill_each_worker(signal)
690 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
693 def soft_kill_each_worker(signal)
694 WORKERS.each_value { |worker| worker.soft_kill(signal) }
697 # unlinks a PID file at given +path+ if it contains the current PID
698 # still potentially racy without locking the directory (which is
699 # non-portable and may interact badly with other programs), but the
700 # window for hitting the race condition is small
701 def unlink_pid_safe(path)
702 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
705 # returns a PID if a given path contains a non-stale PID file,
708 wpid = File.read(path).to_i
710 Process.kill(0, wpid)
713 logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
715 rescue Errno::ESRCH, Errno::ENOENT
716 # don't unlink stale pid files, racy without non-portable locking...
721 logger.info "reloading config_file=#{config.config_file}"
722 config[:listeners].replace(@init_listeners)
725 soft_kill_each_worker(:QUIT)
726 Unicorn::Util.reopen_logs
728 build_app! if preload_app
729 logger.info "done reloading config_file=#{config.config_file}"
730 rescue StandardError, LoadError, SyntaxError => e
731 Unicorn.log_error(@logger,
732 "error reloading config_file=#{config.config_file}", e)
733 self.app = loaded_app
736 # returns an array of string names for the given listener array
737 def listener_names(listeners = LISTENERS)
738 listeners.map { |io| sock_name(io) }
742 if app.respond_to?(:arity) && app.arity == 0
743 if defined?(Gem) && Gem.respond_to?(:refresh)
744 logger.info "Refreshing Gem list"
752 $0 = ([ File.basename(START_CTX[0]), tag
753 ]).concat(START_CTX[:argv]).join(' ')
756 def redirect_io(io, path)
757 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
761 def inherit_listeners!
762 # inherit sockets from parents, they need to be plain Socket objects
763 # before they become Kgio::UNIXServer or Kgio::TCPServer
764 inherited = ENV['UNICORN_FD'].to_s.split(',').map do |fd|
765 io = Socket.for_fd(fd.to_i)
766 set_server_sockopt(io, listener_opts[sock_name(io)])
768 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
772 config_listeners = config[:listeners].dup
773 LISTENERS.replace(inherited)
775 # we start out with generic Socket objects that get cast to either
776 # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
777 # objects share the same OS-level file descriptor as the higher-level
778 # *Server objects; we need to prevent Socket objects from being
780 config_listeners -= listener_names
781 if config_listeners.empty? && LISTENERS.empty?
782 config_listeners << Unicorn::Const::DEFAULT_LISTEN
783 @init_listeners << Unicorn::Const::DEFAULT_LISTEN
784 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
786 NEW_LISTENERS.replace(config_listeners)
789 # call only after calling inherit_listeners!
790 # This binds any listeners we did NOT inherit from the parent
791 def bind_new_listeners!
792 NEW_LISTENERS.each { |addr| listen(addr) }
793 raise ArgumentError, "no listeners" if LISTENERS.empty?
797 # try to use the monotonic clock in Ruby >= 2.1, it is immune to clock
798 # offset adjustments and generates less garbage (Float vs Time object)
800 Process.clock_gettime(Process::CLOCK_MONOTONIC)
802 Process.clock_gettime(Process::CLOCK_MONOTONIC)
804 rescue NameError, NoMethodError
805 def time_now # Ruby <= 2.0