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/1.9.2/bin/unicorn"
72 :argv => ARGV.map { |arg| arg.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_PURGATORY.delete_if do |pio|
160 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
162 (io.close rescue nil).nil? # true
164 set_server_sockopt(io, listener_opts[sock_name(io)])
169 (set_names - cur_names).each { |addr| listen(addr) }
172 def stdout_path=(path); redirect_io($stdout, path); end
173 def stderr_path=(path); redirect_io($stderr, path); end
176 Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
179 def clobber_pid(path)
180 unlink_pid_safe(@pid) if @pid
183 tmp = "#{File.dirname(path)}/#{rand}.#$$"
184 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
189 File.rename(fp.path, path)
194 # sets the path for the PID file of the master process
197 if x = valid_pid?(path)
198 return path if pid && path == pid && x == $$
199 if x == reexec_pid && pid =~ /\.oldbin\z/
200 logger.warn("will not set pid=#{path} while reexec-ed "\
201 "child is running PID:#{x}")
204 raise ArgumentError, "Already running on PID:#{x} " \
205 "(or pid=#{path} is stale)"
209 # rename the old pid if possible
212 File.rename(@pid, path)
213 rescue Errno::ENOENT, Errno::EXDEV
214 # a user may have accidentally removed the original,
215 # obviously cross-FS renames don't work, either.
224 # add a given address to the +listeners+ set, idempotently
225 # Allows workers to add a private, per-process listener via the
226 # after_fork hook. Very useful for debugging and testing.
227 # +:tries+ may be specified as an option for the number of times
228 # to retry, and +:delay+ may be specified as the time in seconds
229 # to delay between retries.
230 # A negative value for +:tries+ indicates the listen will be
231 # retried indefinitely, this is useful when workers belonging to
232 # different masters are spawned during a transparent upgrade.
233 def listen(address, opt = {}.merge(listener_opts[address] || {}))
234 address = config.expand_addr(address)
235 return if String === address && listener_names.include?(address)
237 delay = opt[:delay] || 0.5
238 tries = opt[:tries] || 5
240 io = bind_listen(address, opt)
241 unless Kgio::TCPServer === io || Kgio::UNIXServer === io
242 prevent_autoclose(io)
245 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
248 rescue Errno::EADDRINUSE => err
249 logger.error "adding listener failed addr=#{address} (in use)"
250 raise err if tries == 0
252 logger.error "retrying in #{delay} seconds " \
253 "(#{tries < 0 ? 'infinite' : tries} tries left)"
257 logger.fatal "error adding listener addr=#{address}"
262 # monitors children and receives signals forever
263 # (or until a termination signal is sent). This handles signals
264 # one-at-a-time time and we'll happily drop signals in case somebody
265 # is signalling us too often.
268 last_check = Time.now
271 logger.info "master process ready" # test_exec.rb relies on this message
274 @ready_pipe.syswrite($$.to_s)
276 logger.warn("grandparent died too soon?: #{e.message} (#{e.class})")
278 @ready_pipe = @ready_pipe.close rescue nil
284 # avoid murdering workers after our master process (or the
285 # machine) comes out of suspend/hibernation
286 if (last_check + @timeout) >= (last_check = Time.now)
287 sleep_time = murder_lazy_workers
289 sleep_time = @timeout/2.0 + 1
290 @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
292 maintain_worker_count if respawn
293 master_sleep(sleep_time)
294 when :QUIT # graceful shutdown
296 when :TERM, :INT # immediate shutdown
299 when :USR1 # rotate logs
300 logger.info "master reopening logs..."
301 Unicorn::Util.reopen_logs
302 logger.info "master done reopening logs"
303 soft_kill_each_worker(:USR1)
304 when :USR2 # exec binary, stay alive in case something went wrong
307 if Unicorn::Configurator::RACKUP[:daemonized]
309 logger.info "gracefully stopping all workers"
310 soft_kill_each_worker(:QUIT)
311 self.worker_processes = 0
313 logger.info "SIGWINCH ignored because we're not daemonized"
317 self.worker_processes += 1
319 self.worker_processes -= 1 if self.worker_processes > 0
322 if config.config_file
324 else # exec binary and exit if there's no config file
325 logger.info "config_file not present, reexecuting binary"
330 Unicorn.log_error(@logger, "master loop error", e)
332 stop # gracefully shutdown all workers on our way out
333 logger.info "master complete"
334 unlink_pid_safe(pid) if pid
337 # Terminates all workers, but does not exit master process
338 def stop(graceful = true)
340 limit = Time.now + timeout
341 until WORKERS.empty? || Time.now > limit
343 soft_kill_each_worker(:QUIT)
345 kill_each_worker(:TERM)
350 kill_each_worker(:KILL)
354 Unicorn::HttpRequest.input_class.method_defined?(:rewind)
357 def rewindable_input=(bool)
358 Unicorn::HttpRequest.input_class = bool ?
359 Unicorn::TeeInput : Unicorn::StreamInput
362 def client_body_buffer_size
363 Unicorn::TeeInput.client_body_buffer_size
366 def client_body_buffer_size=(bytes)
367 Unicorn::TeeInput.client_body_buffer_size = bytes
370 def check_client_connection
371 Unicorn::HttpRequest.check_client_connection
374 def check_client_connection=(bool)
375 Unicorn::HttpRequest.check_client_connection = bool
380 # wait for a signal hander to wake us up and then consume the pipe
381 def master_sleep(sec)
382 IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
383 SELF_PIPE[0].kgio_tryread(11)
387 return if $$ != @master_pid
388 SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
391 # reaps all unreaped workers
394 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
396 if reexec_pid == wpid
397 logger.error "reaped #{status.inspect} exec()-ed"
399 self.pid = pid.chomp('.oldbin') if pid
402 worker = WORKERS.delete(wpid) and worker.close rescue nil
403 m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
404 status.success? ? logger.info(m) : logger.error(m)
411 # reexecutes the START_CTX with a new binary
415 Process.kill(0, reexec_pid)
416 logger.error "reexec-ed child already running PID:#{reexec_pid}"
424 old_pid = "#{pid}.oldbin"
426 self.pid = old_pid # clear the path for a new pid file
428 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
429 "existing pid=#{old_pid}, refusing rexec"
432 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
437 self.reexec_pid = fork do
439 LISTENERS.each do |sock|
440 # IO#close_on_exec= will be available on any future version of
441 # Ruby that sets FD_CLOEXEC by default on new file descriptors
442 # ref: http://redmine.ruby-lang.org/issues/5041
443 sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
444 listener_fds[sock.fileno] = sock
446 ENV['UNICORN_FD'] = listener_fds.keys.join(',')
447 Dir.chdir(START_CTX[:cwd])
448 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
450 # avoid leaking FDs we don't know about, but let before_exec
451 # unset FD_CLOEXEC, if anything else in the app eventually
452 # relies on FD inheritence.
453 (3..1024).each do |io|
454 next if listener_fds.include?(io)
455 io = IO.for_fd(io) rescue next
456 prevent_autoclose(io)
457 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
460 # exec(command, hash) works in at least 1.9.1+, but will only be
461 # required in 1.9.4/2.0.0 at earliest.
462 cmd << listener_fds if RUBY_VERSION >= "1.9.1"
463 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
464 before_exec.call(self)
467 proc_name 'master (old)'
470 # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
471 def murder_lazy_workers
472 next_sleep = @timeout - 1
474 WORKERS.dup.each_pair do |wpid, worker|
476 0 == tick and next # skip workers that haven't processed any clients
478 tmp = @timeout - diff
480 next_sleep > tmp and next_sleep = tmp
484 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
485 "(#{diff}s > #{@timeout}s), killing"
486 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
488 next_sleep <= 0 ? 1 : next_sleep
491 def after_fork_internal
492 SELF_PIPE.each { |io| io.close }.clear # this is master-only, now
493 @ready_pipe.close if @ready_pipe
494 Unicorn::Configurator::RACKUP.clear
495 @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
497 srand # http://redmine.ruby-lang.org/issues/4338
499 # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
500 # dying workers can recycle pids
501 OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
504 def spawn_missing_workers
506 until (worker_nr += 1) == @worker_processes
507 WORKERS.value?(worker_nr) and next
508 worker = Worker.new(worker_nr)
509 before_fork.call(self, worker)
511 WORKERS[pid] = worker
520 @logger.error(e) rescue nil
524 def maintain_worker_count
525 (off = WORKERS.size - worker_processes) == 0 and return
526 off < 0 and return spawn_missing_workers
527 WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
530 # if we get any error, try to write something back to the client
531 # assuming we haven't closed the socket, but don't get hung up
532 # if the socket is already closed or broken. We'll always ensure
533 # the socket is closed at the end of this function
534 def handle_error(client, e)
536 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
537 # client disconnected on us and there's nothing we can do
538 when Unicorn::RequestURITooLongError
540 when Unicorn::RequestEntityTooLargeError
542 when Unicorn::HttpParserError # try to tell the client they're bad
545 Unicorn.log_error(@logger, "app error", e)
549 client.kgio_trywrite(err_response(code, @request.response_start_sent))
555 def expect_100_response
556 if @request.response_start_sent
557 Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED
559 Unicorn::Const::EXPECT_100_RESPONSE
563 # once a client is accepted, it is processed in its entirety here
564 # in 3 easy steps: read request, call app, write app response
565 def process_client(client)
566 status, headers, body = @app.call(env = @request.read(client))
567 return if @request.hijacked?
569 if 100 == status.to_i
570 client.write(expect_100_response)
571 env.delete(Unicorn::Const::HTTP_EXPECT)
572 status, headers, body = @app.call(env)
573 return if @request.hijacked?
575 @request.headers? or headers = nil
576 http_response_write(client, status, headers, body,
577 @request.response_start_sent)
578 unless client.closed? # rack.hijack may've close this for us
579 client.shutdown # in case of fork() in Rack app
580 client.close # flush and uncork socket immediately, no keepalive
583 handle_error(client, e)
586 EXIT_SIGS = [ :QUIT, :TERM, :INT ]
587 WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
589 def nuke_listeners!(readers)
590 # only called from the worker, ordering is important here
592 readers.replace([false]) # ensure worker does not continue ASAP
593 tmp.each { |io| io.close rescue nil } # break out of IO.select
596 # gets rid of stuff the worker has no business keeping track of
597 # to free some resources and drops all sig handlers.
598 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
600 def init_worker_process(worker)
602 # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
603 EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
604 exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
605 WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
606 trap(:CHLD, 'DEFAULT')
608 proc_name "worker[#{worker.nr}]"
612 after_fork.call(self, worker) # can drop perms and create listeners
613 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
615 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
616 self.timeout /= 2.0 # halve it for select()
618 build_app! unless preload_app
619 @after_fork = @listener_opts = @orig_app = nil
620 readers = LISTENERS.dup
622 trap(:QUIT) { nuke_listeners!(readers) }
626 def reopen_worker_logs(worker_nr)
627 logger.info "worker=#{worker_nr} reopening logs..."
628 Unicorn::Util.reopen_logs
629 logger.info "worker=#{worker_nr} done reopening logs"
631 logger.error(e) rescue nil
632 exit!(77) # EX_NOPERM in sysexits.h
635 # runs inside each forked worker, this sits around and waits
636 # for connections and doesn't die until the parent dies (or is
637 # given a INT, QUIT, or TERM signal)
638 def worker_loop(worker)
640 readers = init_worker_process(worker)
641 nr = 0 # this becomes negative if we need to reopen logs
643 # this only works immediately if the master sent us the signal
644 # (which is the normal case)
645 trap(:USR1) { nr = -65536 }
648 @logger.info "worker=#{worker.nr} ready"
651 nr < 0 and reopen_worker_logs(worker.nr)
653 worker.tick = Time.now.to_i
655 while sock = tmp.shift
656 # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
657 # but that will return false
658 if client = sock.kgio_tryaccept
659 process_client(client)
661 worker.tick = Time.now.to_i
666 # make the following bet: if we accepted clients this round,
667 # we're probably reasonably busy, so avoid calling select()
668 # and do a speculative non-blocking accept() on ready listeners
669 # before we sleep again in select().
675 ppid == Process.ppid or return
677 # timeout used so we can detect parent death:
678 worker.tick = Time.now.to_i
679 ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
681 redo if nr < 0 && readers[0]
682 Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
686 # delivers a signal to a worker and fails gracefully if the worker
687 # is no longer running.
688 def kill_worker(signal, wpid)
689 Process.kill(signal, wpid)
691 worker = WORKERS.delete(wpid) and worker.close rescue nil
694 # delivers a signal to each worker
695 def kill_each_worker(signal)
696 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
699 def soft_kill_each_worker(signal)
700 WORKERS.each_value { |worker| worker.soft_kill(signal) }
703 # unlinks a PID file at given +path+ if it contains the current PID
704 # still potentially racy without locking the directory (which is
705 # non-portable and may interact badly with other programs), but the
706 # window for hitting the race condition is small
707 def unlink_pid_safe(path)
708 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
711 # returns a PID if a given path contains a non-stale PID file,
714 wpid = File.read(path).to_i
716 Process.kill(0, wpid)
719 logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
721 rescue Errno::ESRCH, Errno::ENOENT
722 # don't unlink stale pid files, racy without non-portable locking...
727 logger.info "reloading config_file=#{config.config_file}"
728 config[:listeners].replace(@init_listeners)
731 soft_kill_each_worker(:QUIT)
732 Unicorn::Util.reopen_logs
734 build_app! if preload_app
735 logger.info "done reloading config_file=#{config.config_file}"
736 rescue StandardError, LoadError, SyntaxError => e
737 Unicorn.log_error(@logger,
738 "error reloading config_file=#{config.config_file}", e)
739 self.app = loaded_app
742 # returns an array of string names for the given listener array
743 def listener_names(listeners = LISTENERS)
744 listeners.map { |io| sock_name(io) }
748 if app.respond_to?(:arity) && app.arity == 0
749 if defined?(Gem) && Gem.respond_to?(:refresh)
750 logger.info "Refreshing Gem list"
758 $0 = ([ File.basename(START_CTX[0]), tag
759 ]).concat(START_CTX[:argv]).join(' ')
762 def redirect_io(io, path)
763 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
767 def inherit_listeners!
768 # inherit sockets from parents, they need to be plain Socket objects
769 # before they become Kgio::UNIXServer or Kgio::TCPServer
770 inherited = ENV['UNICORN_FD'].to_s.split(',').map do |fd|
771 io = Socket.for_fd(fd.to_i)
772 set_server_sockopt(io, listener_opts[sock_name(io)])
773 prevent_autoclose(io)
774 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
778 config_listeners = config[:listeners].dup
779 LISTENERS.replace(inherited)
781 # we start out with generic Socket objects that get cast to either
782 # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
783 # objects share the same OS-level file descriptor as the higher-level
784 # *Server objects; we need to prevent Socket objects from being
786 config_listeners -= listener_names
787 if config_listeners.empty? && LISTENERS.empty?
788 config_listeners << Unicorn::Const::DEFAULT_LISTEN
789 @init_listeners << Unicorn::Const::DEFAULT_LISTEN
790 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
792 NEW_LISTENERS.replace(config_listeners)
795 # call only after calling inherit_listeners!
796 # This binds any listeners we did NOT inherit from the parent
797 def bind_new_listeners!
798 NEW_LISTENERS.each { |addr| listen(addr) }
799 raise ArgumentError, "no listeners" if LISTENERS.empty?