1 # -*- encoding: binary -*-
2 require "unicorn/ssl_server"
4 # This is the process manager of Unicorn. This manages worker
5 # processes which in turn handle the I/O and application process.
6 # Listener sockets are started in the master process and shared with
7 # forked worker children.
9 # Users do not need to know the internals of this class, but reading the
10 # {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb]
11 # is education for programmers wishing to learn how \Unicorn works.
12 # See Unicorn::Configurator for information on how to configure \Unicorn.
13 class Unicorn::HttpServer
15 attr_accessor :app, :request, :timeout, :worker_processes,
16 :before_fork, :after_fork, :before_exec,
17 :listener_opts, :preload_app,
18 :reexec_pid, :orig_app, :init_listeners,
19 :master_pid, :config, :ready_pipe, :user
21 attr_reader :pid, :logger
22 include Unicorn::SocketHelper
23 include Unicorn::HttpResponse
24 include Unicorn::SSLServer
26 # backwards compatibility with 1.x
27 Worker = Unicorn::Worker
29 # all bound listener sockets
32 # listeners we have yet to bind
35 # This hash maps PIDs to Workers
38 # We use SELF_PIPE differently in the master and worker processes:
40 # * The master process never closes or reinitializes this once
41 # initialized. Signal handlers in the master process will write to
42 # it to wake up the master from IO.select in exactly the same manner
43 # djb describes in http://cr.yp.to/docs/selfpipe.html
45 # * The workers immediately close the pipe they inherit. See the
46 # Unicorn::Worker class for the pipe workers use.
49 # signal queue used for self-piping
52 # list of signals we care about and trap in master.
53 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
56 # We populate this at startup so we can figure out how to reexecute
57 # and upgrade the currently running instance of Unicorn
58 # This Hash is considered a stable interface and changing its contents
59 # will allow you to switch between different installations of Unicorn
60 # or even different installations of the same applications without
61 # downtime. Keys of this constant Hash are described as follows:
63 # * 0 - the path to the unicorn/unicorn_rails executable
64 # * :argv - a deep copy of the ARGV array the executable originally saw
65 # * :cwd - the working directory of the application, this is where
66 # you originally started Unicorn.
68 # To change your unicorn executable to a different path without downtime,
69 # you can set the following in your Unicorn config file, HUP and then
70 # continue with the traditional USR2 + QUIT upgrade steps:
72 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
74 :argv => ARGV.map { |arg| arg.dup },
77 # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
79 START_CTX[:cwd] = begin
80 a = File.stat(pwd = ENV['PWD'])
81 b = File.stat(Dir.pwd)
82 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
88 # Creates a working server on host:port (strange things happen if
89 # port isn't a Number). Use HttpServer::run to start the server and
90 # HttpServer.run.join to join the thread that's processing
91 # incoming requests on the socket.
92 def initialize(app, options = {})
94 @request = Unicorn::HttpRequest.new
97 @ready_pipe = options.delete(:ready_pipe)
98 @init_listeners = options[:listeners] ? options[:listeners].dup : []
99 options[:use_defaults] = true
100 self.config = Unicorn::Configurator.new(options)
101 self.listener_opts = {}
103 # we try inheriting listeners first, so we bind them later.
104 # we don't write the pid file until we've bound listeners in case
105 # unicorn was started twice by mistake. Even though our #pid= method
106 # checks for stale/existing pid files, race conditions are still
107 # possible (and difficult/non-portable to avoid) and can be likely
108 # to clobber the pid if the second start was in quick succession
109 # after the first, so we rely on the listener binding to fail in
110 # that case. Some tests (in and outside of this source tree) and
111 # monitoring tools may also rely on pid files existing before we
112 # attempt to connect to the listener(s)
113 config.commit!(self, :skip => [:listeners, :pid])
117 # Runs the thing. Returns self so you can run join on it
120 # this pipe is used to wake us up from select(2) in #join when signals
121 # are trapped. See trap_deferred.
122 SELF_PIPE.replace(Unicorn.pipe)
125 # setup signal handlers before writing pid file in case people get
126 # trigger happy and send signals as soon as the pid file exists.
127 # Note that signals don't actually get handled until the #join method
128 QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
129 trap(:CHLD) { awaken_master }
131 # write pid early for Mongrel compatibility if we're not inheriting sockets
132 # This is needed for compatibility some Monit setups at least.
133 # This unfortunately has the side effect of clobbering valid PID if
134 # we upgrade and the upgrade breaks during preload_app==true && build_app!
135 self.pid = config[:pid]
137 build_app! if preload_app
140 spawn_missing_workers
144 # replaces current listener set with +listeners+. This will
145 # close the socket if it will not exist in the new listener set
146 def listeners=(listeners)
147 cur_names, dead_names = [], []
148 listener_names.each do |name|
150 # mark unlinked sockets as dead so we can rebind them
151 (File.socket?(name) ? cur_names : dead_names) << name
156 set_names = listener_names(listeners)
157 dead_names.concat(cur_names - set_names).uniq!
159 LISTENERS.delete_if do |io|
160 if dead_names.include?(sock_name(io))
161 IO_PURGATORY.delete_if do |pio|
162 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
164 (io.close rescue nil).nil? # true
166 set_server_sockopt(io, listener_opts[sock_name(io)])
171 (set_names - cur_names).each { |addr| listen(addr) }
174 def stdout_path=(path); redirect_io($stdout, path); end
175 def stderr_path=(path); redirect_io($stderr, path); end
178 Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
181 def clobber_pid(path)
182 unlink_pid_safe(@pid) if @pid
185 tmp = "#{File.dirname(path)}/#{rand}.#$$"
186 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
191 File.rename(fp.path, path)
196 # sets the path for the PID file of the master process
199 if x = valid_pid?(path)
200 return path if pid && path == pid && x == $$
201 if x == reexec_pid && pid =~ /\.oldbin\z/
202 logger.warn("will not set pid=#{path} while reexec-ed "\
203 "child is running PID:#{x}")
206 raise ArgumentError, "Already running on PID:#{x} " \
207 "(or pid=#{path} is stale)"
211 # rename the old pid if possible
214 File.rename(@pid, path)
215 rescue Errno::ENOENT, Errno::EXDEV
216 # a user may have accidentally removed the original,
217 # obviously cross-FS renames don't work, either.
226 # add a given address to the +listeners+ set, idempotently
227 # Allows workers to add a private, per-process listener via the
228 # after_fork hook. Very useful for debugging and testing.
229 # +:tries+ may be specified as an option for the number of times
230 # to retry, and +:delay+ may be specified as the time in seconds
231 # to delay between retries.
232 # A negative value for +:tries+ indicates the listen will be
233 # retried indefinitely, this is useful when workers belonging to
234 # different masters are spawned during a transparent upgrade.
235 def listen(address, opt = {}.merge(listener_opts[address] || {}))
236 address = config.expand_addr(address)
237 return if String === address && listener_names.include?(address)
239 delay = opt[:delay] || 0.5
240 tries = opt[:tries] || 5
242 io = bind_listen(address, opt)
243 unless Kgio::TCPServer === io || Kgio::UNIXServer === io
244 prevent_autoclose(io)
247 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
250 rescue Errno::EADDRINUSE => err
251 logger.error "adding listener failed addr=#{address} (in use)"
252 raise err if tries == 0
254 logger.error "retrying in #{delay} seconds " \
255 "(#{tries < 0 ? 'infinite' : tries} tries left)"
259 logger.fatal "error adding listener addr=#{address}"
264 # monitors children and receives signals forever
265 # (or until a termination signal is sent). This handles signals
266 # one-at-a-time time and we'll happily drop signals in case somebody
267 # is signalling us too often.
270 last_check = Time.now
273 logger.info "master process ready" # test_exec.rb relies on this message
276 @ready_pipe.syswrite($$.to_s)
278 logger.warn("grandparent died too soon?: #{e.message} (#{e.class})")
280 @ready_pipe = @ready_pipe.close rescue nil
286 # avoid murdering workers after our master process (or the
287 # machine) comes out of suspend/hibernation
288 if (last_check + @timeout) >= (last_check = Time.now)
289 sleep_time = murder_lazy_workers
291 sleep_time = @timeout/2.0 + 1
292 @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
294 maintain_worker_count if respawn
295 master_sleep(sleep_time)
296 when :QUIT # graceful shutdown
298 when :TERM, :INT # immediate shutdown
301 when :USR1 # rotate logs
302 logger.info "master reopening logs..."
303 Unicorn::Util.reopen_logs
304 logger.info "master done reopening logs"
305 soft_kill_each_worker(:USR1)
306 when :USR2 # exec binary, stay alive in case something went wrong
309 if Unicorn::Configurator::RACKUP[:daemonized]
311 logger.info "gracefully stopping all workers"
312 soft_kill_each_worker(:QUIT)
313 self.worker_processes = 0
315 logger.info "SIGWINCH ignored because we're not daemonized"
319 self.worker_processes += 1
321 self.worker_processes -= 1 if self.worker_processes > 0
324 if config.config_file
326 else # exec binary and exit if there's no config file
327 logger.info "config_file not present, reexecuting binary"
332 Unicorn.log_error(@logger, "master loop error", e)
334 stop # gracefully shutdown all workers on our way out
335 logger.info "master complete"
336 unlink_pid_safe(pid) if pid
339 # Terminates all workers, but does not exit master process
340 def stop(graceful = true)
342 limit = Time.now + timeout
343 until WORKERS.empty? || Time.now > limit
345 soft_kill_each_worker(:QUIT)
347 kill_each_worker(:TERM)
352 kill_each_worker(:KILL)
356 Unicorn::HttpRequest.input_class.method_defined?(:rewind)
359 def rewindable_input=(bool)
360 Unicorn::HttpRequest.input_class = bool ?
361 Unicorn::TeeInput : Unicorn::StreamInput
364 def client_body_buffer_size
365 Unicorn::TeeInput.client_body_buffer_size
368 def client_body_buffer_size=(bytes)
369 Unicorn::TeeInput.client_body_buffer_size = bytes
372 def trust_x_forwarded
373 Unicorn::HttpParser.trust_x_forwarded?
376 def trust_x_forwarded=(bool)
377 Unicorn::HttpParser.trust_x_forwarded = bool
380 def check_client_connection
381 Unicorn::HttpRequest.check_client_connection
384 def check_client_connection=(bool)
385 Unicorn::HttpRequest.check_client_connection = bool
390 # wait for a signal hander to wake us up and then consume the pipe
391 def master_sleep(sec)
392 IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
393 SELF_PIPE[0].kgio_tryread(11)
397 return if $$ != @master_pid
398 SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
401 # reaps all unreaped workers
404 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
406 if reexec_pid == wpid
407 logger.error "reaped #{status.inspect} exec()-ed"
409 self.pid = pid.chomp('.oldbin') if pid
412 worker = WORKERS.delete(wpid) and worker.close rescue nil
413 m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
414 status.success? ? logger.info(m) : logger.error(m)
421 # reexecutes the START_CTX with a new binary
425 Process.kill(0, reexec_pid)
426 logger.error "reexec-ed child already running PID:#{reexec_pid}"
434 old_pid = "#{pid}.oldbin"
436 self.pid = old_pid # clear the path for a new pid file
438 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
439 "existing pid=#{old_pid}, refusing rexec"
442 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
447 self.reexec_pid = fork do
449 LISTENERS.each do |sock|
450 # IO#close_on_exec= will be available on any future version of
451 # Ruby that sets FD_CLOEXEC by default on new file descriptors
452 # ref: http://redmine.ruby-lang.org/issues/5041
453 sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
454 listener_fds[sock.fileno] = sock
456 ENV['UNICORN_FD'] = listener_fds.keys.join(',')
457 Dir.chdir(START_CTX[:cwd])
458 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
460 # avoid leaking FDs we don't know about, but let before_exec
461 # unset FD_CLOEXEC, if anything else in the app eventually
462 # relies on FD inheritence.
463 (3..1024).each do |io|
464 next if listener_fds.include?(io)
465 io = IO.for_fd(io) rescue next
466 prevent_autoclose(io)
467 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
470 # exec(command, hash) works in at least 1.9.1+, but will only be
471 # required in 1.9.4/2.0.0 at earliest.
472 cmd << listener_fds if RUBY_VERSION >= "1.9.1"
473 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
474 before_exec.call(self)
477 proc_name 'master (old)'
480 # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
481 def murder_lazy_workers
482 next_sleep = @timeout - 1
484 WORKERS.dup.each_pair do |wpid, worker|
486 0 == tick and next # skip workers that haven't processed any clients
488 tmp = @timeout - diff
490 next_sleep > tmp and next_sleep = tmp
494 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
495 "(#{diff}s > #{@timeout}s), killing"
496 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
498 next_sleep <= 0 ? 1 : next_sleep
501 def after_fork_internal
502 SELF_PIPE.each { |io| io.close }.clear # this is master-only, now
503 @ready_pipe.close if @ready_pipe
504 Unicorn::Configurator::RACKUP.clear
505 @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
507 srand # http://redmine.ruby-lang.org/issues/4338
509 # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
510 # dying workers can recycle pids
511 OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
514 def spawn_missing_workers
516 until (worker_nr += 1) == @worker_processes
517 WORKERS.value?(worker_nr) and next
518 worker = Worker.new(worker_nr)
519 before_fork.call(self, worker)
521 WORKERS[pid] = worker
530 @logger.error(e) rescue nil
534 def maintain_worker_count
535 (off = WORKERS.size - worker_processes) == 0 and return
536 off < 0 and return spawn_missing_workers
537 WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
540 # if we get any error, try to write something back to the client
541 # assuming we haven't closed the socket, but don't get hung up
542 # if the socket is already closed or broken. We'll always ensure
543 # the socket is closed at the end of this function
544 def handle_error(client, e)
546 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
547 # client disconnected on us and there's nothing we can do
548 when Unicorn::RequestURITooLongError
550 when Unicorn::RequestEntityTooLargeError
552 when Unicorn::HttpParserError # try to tell the client they're bad
555 Unicorn.log_error(@logger, "app error", e)
559 client.kgio_trywrite(err_response(code, @request.response_start_sent))
565 def expect_100_response
566 if @request.response_start_sent
567 Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED
569 Unicorn::Const::EXPECT_100_RESPONSE
573 # once a client is accepted, it is processed in its entirety here
574 # in 3 easy steps: read request, call app, write app response
575 def process_client(client)
576 status, headers, body = @app.call(env = @request.read(client))
577 return if @request.hijacked?
579 if 100 == status.to_i
580 client.write(expect_100_response)
581 env.delete(Unicorn::Const::HTTP_EXPECT)
582 status, headers, body = @app.call(env)
583 return if @request.hijacked?
585 @request.headers? or headers = nil
586 http_response_write(client, status, headers, body,
587 @request.response_start_sent)
588 unless client.closed? # rack.hijack may've close this for us
589 client.shutdown # in case of fork() in Rack app
590 client.close # flush and uncork socket immediately, no keepalive
593 handle_error(client, e)
596 EXIT_SIGS = [ :QUIT, :TERM, :INT ]
597 WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
599 def nuke_listeners!(readers)
600 # only called from the worker, ordering is important here
602 readers.replace([false]) # ensure worker does not continue ASAP
603 tmp.each { |io| io.close rescue nil } # break out of IO.select
606 # gets rid of stuff the worker has no business keeping track of
607 # to free some resources and drops all sig handlers.
608 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
610 def init_worker_process(worker)
612 # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
613 EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
614 exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
615 WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
616 trap(:CHLD, 'DEFAULT')
618 proc_name "worker[#{worker.nr}]"
622 after_fork.call(self, worker) # can drop perms and create listeners
623 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
625 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
626 self.timeout /= 2.0 # halve it for select()
628 build_app! unless preload_app
630 @after_fork = @listener_opts = @orig_app = nil
631 readers = LISTENERS.dup
633 trap(:QUIT) { nuke_listeners!(readers) }
637 def reopen_worker_logs(worker_nr)
638 logger.info "worker=#{worker_nr} reopening logs..."
639 Unicorn::Util.reopen_logs
640 logger.info "worker=#{worker_nr} done reopening logs"
642 logger.error(e) rescue nil
643 exit!(77) # EX_NOPERM in sysexits.h
646 # runs inside each forked worker, this sits around and waits
647 # for connections and doesn't die until the parent dies (or is
648 # given a INT, QUIT, or TERM signal)
649 def worker_loop(worker)
651 readers = init_worker_process(worker)
652 nr = 0 # this becomes negative if we need to reopen logs
654 # this only works immediately if the master sent us the signal
655 # (which is the normal case)
656 trap(:USR1) { nr = -65536 }
659 @logger.info "worker=#{worker.nr} ready"
662 nr < 0 and reopen_worker_logs(worker.nr)
664 worker.tick = Time.now.to_i
666 while sock = tmp.shift
667 # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
668 # but that will return false
669 if client = sock.kgio_tryaccept
670 process_client(client)
672 worker.tick = Time.now.to_i
677 # make the following bet: if we accepted clients this round,
678 # we're probably reasonably busy, so avoid calling select()
679 # and do a speculative non-blocking accept() on ready listeners
680 # before we sleep again in select().
686 ppid == Process.ppid or return
688 # timeout used so we can detect parent death:
689 worker.tick = Time.now.to_i
690 ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
692 redo if nr < 0 && readers[0]
693 Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
697 # delivers a signal to a worker and fails gracefully if the worker
698 # is no longer running.
699 def kill_worker(signal, wpid)
700 Process.kill(signal, wpid)
702 worker = WORKERS.delete(wpid) and worker.close rescue nil
705 # delivers a signal to each worker
706 def kill_each_worker(signal)
707 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
710 def soft_kill_each_worker(signal)
711 WORKERS.each_value { |worker| worker.soft_kill(signal) }
714 # unlinks a PID file at given +path+ if it contains the current PID
715 # still potentially racy without locking the directory (which is
716 # non-portable and may interact badly with other programs), but the
717 # window for hitting the race condition is small
718 def unlink_pid_safe(path)
719 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
722 # returns a PID if a given path contains a non-stale PID file,
725 wpid = File.read(path).to_i
727 Process.kill(0, wpid)
730 logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
732 rescue Errno::ESRCH, Errno::ENOENT
733 # don't unlink stale pid files, racy without non-portable locking...
738 logger.info "reloading config_file=#{config.config_file}"
739 config[:listeners].replace(@init_listeners)
742 soft_kill_each_worker(:QUIT)
743 Unicorn::Util.reopen_logs
745 build_app! if preload_app
746 logger.info "done reloading config_file=#{config.config_file}"
747 rescue StandardError, LoadError, SyntaxError => e
748 Unicorn.log_error(@logger,
749 "error reloading config_file=#{config.config_file}", e)
750 self.app = loaded_app
753 # returns an array of string names for the given listener array
754 def listener_names(listeners = LISTENERS)
755 listeners.map { |io| sock_name(io) }
759 if app.respond_to?(:arity) && app.arity == 0
760 if defined?(Gem) && Gem.respond_to?(:refresh)
761 logger.info "Refreshing Gem list"
769 $0 = ([ File.basename(START_CTX[0]), tag
770 ]).concat(START_CTX[:argv]).join(' ')
773 def redirect_io(io, path)
774 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
778 def inherit_listeners!
779 # inherit sockets from parents, they need to be plain Socket objects
780 # before they become Kgio::UNIXServer or Kgio::TCPServer
781 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
782 io = Socket.for_fd(fd.to_i)
783 set_server_sockopt(io, listener_opts[sock_name(io)])
784 prevent_autoclose(io)
785 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
789 config_listeners = config[:listeners].dup
790 LISTENERS.replace(inherited)
792 # we start out with generic Socket objects that get cast to either
793 # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
794 # objects share the same OS-level file descriptor as the higher-level
795 # *Server objects; we need to prevent Socket objects from being
797 config_listeners -= listener_names
798 if config_listeners.empty? && LISTENERS.empty?
799 config_listeners << Unicorn::Const::DEFAULT_LISTEN
800 @init_listeners << Unicorn::Const::DEFAULT_LISTEN
801 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
803 NEW_LISTENERS.replace(config_listeners)
806 # call only after calling inherit_listeners!
807 # This binds any listeners we did NOT inherit from the parent
808 def bind_new_listeners!
809 NEW_LISTENERS.each { |addr| listen(addr) }
810 raise ArgumentError, "no listeners" if LISTENERS.empty?