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
20 attr_reader :pid, :logger
21 include Unicorn::SocketHelper
22 include Unicorn::HttpResponse
23 include Unicorn::SSLServer
25 # backwards compatibility with 1.x
26 Worker = Unicorn::Worker
28 # all bound listener sockets
31 # This hash maps PIDs to Workers
34 # We use SELF_PIPE differently in the master and worker processes:
36 # * The master process never closes or reinitializes this once
37 # initialized. Signal handlers in the master process will write to
38 # it to wake up the master from IO.select in exactly the same manner
39 # djb describes in http://cr.yp.to/docs/selfpipe.html
41 # * The workers immediately close the pipe they inherit from the
42 # master and replace it with a new pipe after forking. This new
43 # pipe is also used to wakeup from IO.select from inside (worker)
44 # signal handlers. However, workers *close* the pipe descriptors in
45 # the signal handlers to raise EBADF in IO.select instead of writing
46 # like we do in the master. We cannot easily use the reader set for
47 # IO.select because LISTENERS is already that set, and it's extra
48 # work (and cycles) to distinguish the pipe FD from the reader set
49 # once IO.select returns. So we're lazy and just close the pipe when
50 # a (rare) signal arrives in the worker and reinitialize the pipe later.
53 # signal queue used for self-piping
56 # list of signals we care about and trap in master.
57 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
60 # We populate this at startup so we can figure out how to reexecute
61 # and upgrade the currently running instance of Unicorn
62 # This Hash is considered a stable interface and changing its contents
63 # will allow you to switch between different installations of Unicorn
64 # or even different installations of the same applications without
65 # downtime. Keys of this constant Hash are described as follows:
67 # * 0 - the path to the unicorn/unicorn_rails executable
68 # * :argv - a deep copy of the ARGV array the executable originally saw
69 # * :cwd - the working directory of the application, this is where
70 # you originally started Unicorn.
72 # To change your unicorn executable to a different path without downtime,
73 # you can set the following in your Unicorn config file, HUP and then
74 # continue with the traditional USR2 + QUIT upgrade steps:
76 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
78 :argv => ARGV.map { |arg| arg.dup },
81 # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
83 START_CTX[:cwd] = begin
84 a = File.stat(pwd = ENV['PWD'])
85 b = File.stat(Dir.pwd)
86 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
92 # Creates a working server on host:port (strange things happen if
93 # port isn't a Number). Use HttpServer::run to start the server and
94 # HttpServer.run.join to join the thread that's processing
95 # incoming requests on the socket.
96 def initialize(app, options = {})
98 @request = Unicorn::HttpRequest.new
100 options = options.dup
101 @ready_pipe = options.delete(:ready_pipe)
102 @init_listeners = options[:listeners] ? options[:listeners].dup : []
103 options[:use_defaults] = true
104 self.config = Unicorn::Configurator.new(options)
105 self.listener_opts = {}
107 # we try inheriting listeners first, so we bind them later.
108 # we don't write the pid file until we've bound listeners in case
109 # unicorn was started twice by mistake. Even though our #pid= method
110 # checks for stale/existing pid files, race conditions are still
111 # possible (and difficult/non-portable to avoid) and can be likely
112 # to clobber the pid if the second start was in quick succession
113 # after the first, so we rely on the listener binding to fail in
114 # that case. Some tests (in and outside of this source tree) and
115 # monitoring tools may also rely on pid files existing before we
116 # attempt to connect to the listener(s)
117 config.commit!(self, :skip => [:listeners, :pid])
121 # Runs the thing. Returns self so you can run join on it
124 # this pipe is used to wake us up from select(2) in #join when signals
125 # are trapped. See trap_deferred.
128 # setup signal handlers before writing pid file in case people get
129 # trigger happy and send signals as soon as the pid file exists.
130 # Note that signals don't actually get handled until the #join method
131 QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
132 trap(:CHLD) { awaken_master }
133 self.pid = config[:pid]
136 build_app! if preload_app
137 spawn_missing_workers
141 # replaces current listener set with +listeners+. This will
142 # close the socket if it will not exist in the new listener set
143 def listeners=(listeners)
144 cur_names, dead_names = [], []
145 listener_names.each do |name|
147 # mark unlinked sockets as dead so we can rebind them
148 (File.socket?(name) ? cur_names : dead_names) << name
153 set_names = listener_names(listeners)
154 dead_names.concat(cur_names - set_names).uniq!
156 LISTENERS.delete_if do |io|
157 if dead_names.include?(sock_name(io))
158 IO_PURGATORY.delete_if do |pio|
159 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
161 (io.close rescue nil).nil? # true
163 set_server_sockopt(io, listener_opts[sock_name(io)])
168 (set_names - cur_names).each { |addr| listen(addr) }
171 def stdout_path=(path); redirect_io($stdout, path); end
172 def stderr_path=(path); redirect_io($stderr, path); end
175 Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
178 # sets the path for the PID file of the master process
181 if x = valid_pid?(path)
182 return path if pid && path == pid && x == $$
183 if x == reexec_pid && pid =~ /\.oldbin\z/
184 logger.warn("will not set pid=#{path} while reexec-ed "\
185 "child is running PID:#{x}")
188 raise ArgumentError, "Already running on PID:#{x} " \
189 "(or pid=#{path} is stale)"
192 unlink_pid_safe(pid) if pid
196 tmp = "#{File.dirname(path)}/#{rand}.#$$"
197 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
202 File.rename(fp.path, path)
208 # add a given address to the +listeners+ set, idempotently
209 # Allows workers to add a private, per-process listener via the
210 # after_fork hook. Very useful for debugging and testing.
211 # +:tries+ may be specified as an option for the number of times
212 # to retry, and +:delay+ may be specified as the time in seconds
213 # to delay between retries.
214 # A negative value for +:tries+ indicates the listen will be
215 # retried indefinitely, this is useful when workers belonging to
216 # different masters are spawned during a transparent upgrade.
217 def listen(address, opt = {}.merge(listener_opts[address] || {}))
218 address = config.expand_addr(address)
219 return if String === address && listener_names.include?(address)
221 delay = opt[:delay] || 0.5
222 tries = opt[:tries] || 5
224 io = bind_listen(address, opt)
225 unless Kgio::TCPServer === io || Kgio::UNIXServer === io
229 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
232 rescue Errno::EADDRINUSE => err
233 logger.error "adding listener failed addr=#{address} (in use)"
234 raise err if tries == 0
236 logger.error "retrying in #{delay} seconds " \
237 "(#{tries < 0 ? 'infinite' : tries} tries left)"
241 logger.fatal "error adding listener addr=#{address}"
246 # monitors children and receives signals forever
247 # (or until a termination signal is sent). This handles signals
248 # one-at-a-time time and we'll happily drop signals in case somebody
249 # is signalling us too often.
252 last_check = Time.now
255 logger.info "master process ready" # test_exec.rb relies on this message
257 @ready_pipe.syswrite($$.to_s)
258 @ready_pipe = @ready_pipe.close rescue nil
264 # avoid murdering workers after our master process (or the
265 # machine) comes out of suspend/hibernation
266 if (last_check + @timeout) >= (last_check = Time.now)
267 sleep_time = murder_lazy_workers
269 sleep_time = @timeout/2.0 + 1
270 @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
272 maintain_worker_count if respawn
273 master_sleep(sleep_time)
274 when :QUIT # graceful shutdown
276 when :TERM, :INT # immediate shutdown
279 when :USR1 # rotate logs
280 logger.info "master reopening logs..."
281 Unicorn::Util.reopen_logs
282 logger.info "master done reopening logs"
283 kill_each_worker(:USR1)
284 when :USR2 # exec binary, stay alive in case something went wrong
287 if Unicorn::Configurator::RACKUP[:daemonized]
289 logger.info "gracefully stopping all workers"
290 kill_each_worker(:QUIT)
291 self.worker_processes = 0
293 logger.info "SIGWINCH ignored because we're not daemonized"
297 self.worker_processes += 1
299 self.worker_processes -= 1 if self.worker_processes > 0
302 if config.config_file
304 else # exec binary and exit if there's no config file
305 logger.info "config_file not present, reexecuting binary"
310 Unicorn.log_error(@logger, "master loop error", e)
312 stop # gracefully shutdown all workers on our way out
313 logger.info "master complete"
314 unlink_pid_safe(pid) if pid
317 # Terminates all workers, but does not exit master process
318 def stop(graceful = true)
320 limit = Time.now + timeout
321 until WORKERS.empty? || Time.now > limit
322 kill_each_worker(graceful ? :QUIT : :TERM)
326 kill_each_worker(:KILL)
330 Unicorn::HttpRequest.input_class.method_defined?(:rewind)
333 def rewindable_input=(bool)
334 Unicorn::HttpRequest.input_class = bool ?
335 Unicorn::TeeInput : Unicorn::StreamInput
338 def client_body_buffer_size
339 Unicorn::TeeInput.client_body_buffer_size
342 def client_body_buffer_size=(bytes)
343 Unicorn::TeeInput.client_body_buffer_size = bytes
346 def trust_x_forwarded
347 Unicorn::HttpParser.trust_x_forwarded?
350 def trust_x_forwarded=(bool)
351 Unicorn::HttpParser.trust_x_forwarded = bool
356 # wait for a signal hander to wake us up and then consume the pipe
357 def master_sleep(sec)
358 IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
359 SELF_PIPE[0].kgio_tryread(11)
363 SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
366 # reaps all unreaped workers
369 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
371 if reexec_pid == wpid
372 logger.error "reaped #{status.inspect} exec()-ed"
374 self.pid = pid.chomp('.oldbin') if pid
377 worker = WORKERS.delete(wpid) and worker.close rescue nil
378 m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
379 status.success? ? logger.info(m) : logger.error(m)
386 # reexecutes the START_CTX with a new binary
390 Process.kill(0, reexec_pid)
391 logger.error "reexec-ed child already running PID:#{reexec_pid}"
399 old_pid = "#{pid}.oldbin"
401 self.pid = old_pid # clear the path for a new pid file
403 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
404 "existing pid=#{old_pid}, refusing rexec"
407 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
412 self.reexec_pid = fork do
413 listener_fds = Hash[LISTENERS.map do |sock|
414 # IO#close_on_exec= will be available on any future version of
415 # Ruby that sets FD_CLOEXEC by default on new file descriptors
416 # ref: http://redmine.ruby-lang.org/issues/5041
417 sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
418 [ sock.fileno, sock ]
420 ENV['UNICORN_FD'] = listener_fds.keys.join(',')
421 Dir.chdir(START_CTX[:cwd])
422 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
424 # avoid leaking FDs we don't know about, but let before_exec
425 # unset FD_CLOEXEC, if anything else in the app eventually
426 # relies on FD inheritence.
427 (3..1024).each do |io|
428 next if listener_fds.include?(io)
429 io = IO.for_fd(io) rescue next
431 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
434 # exec(command, hash) works in at least 1.9.1+, but will only be
435 # required in 1.9.4/2.0.0 at earliest.
436 cmd << listener_fds if RUBY_VERSION >= "1.9.1"
437 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
438 before_exec.call(self)
441 proc_name 'master (old)'
444 # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File
445 def murder_lazy_workers
446 next_sleep = @timeout - 1
448 WORKERS.dup.each_pair do |wpid, worker|
450 0 == tick and next # skip workers that haven't processed any clients
452 tmp = @timeout - diff
454 next_sleep > tmp and next_sleep = tmp
458 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
459 "(#{diff}s > #{@timeout}s), killing"
460 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
462 next_sleep <= 0 ? 1 : next_sleep
465 def after_fork_internal
466 @ready_pipe.close if @ready_pipe
467 Unicorn::Configurator::RACKUP.clear
468 @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
470 srand # http://redmine.ruby-lang.org/issues/4338
472 # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
473 # dying workers can recycle pids
474 OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
477 def spawn_missing_workers
479 until (worker_nr += 1) == @worker_processes
480 WORKERS.value?(worker_nr) and next
481 worker = Worker.new(worker_nr)
482 before_fork.call(self, worker)
484 WORKERS[pid] = worker
492 @logger.error(e) rescue nil
496 def maintain_worker_count
497 (off = WORKERS.size - worker_processes) == 0 and return
498 off < 0 and return spawn_missing_workers
499 WORKERS.dup.each_pair { |wpid,w|
500 w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
504 # if we get any error, try to write something back to the client
505 # assuming we haven't closed the socket, but don't get hung up
506 # if the socket is already closed or broken. We'll always ensure
507 # the socket is closed at the end of this function
508 def handle_error(client, e)
510 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
511 Unicorn::Const::ERROR_500_RESPONSE
512 when Unicorn::RequestURITooLongError
513 Unicorn::Const::ERROR_414_RESPONSE
514 when Unicorn::RequestEntityTooLargeError
515 Unicorn::Const::ERROR_413_RESPONSE
516 when Unicorn::HttpParserError # try to tell the client they're bad
517 Unicorn::Const::ERROR_400_RESPONSE
519 Unicorn.log_error(@logger, "app error", e)
520 Unicorn::Const::ERROR_500_RESPONSE
522 client.kgio_trywrite(msg)
527 # once a client is accepted, it is processed in its entirety here
528 # in 3 easy steps: read request, call app, write app response
529 def process_client(client)
530 status, headers, body = @app.call(env = @request.read(client))
532 if 100 == status.to_i
533 client.write(Unicorn::Const::EXPECT_100_RESPONSE)
534 env.delete(Unicorn::Const::HTTP_EXPECT)
535 status, headers, body = @app.call(env)
537 @request.headers? or headers = nil
538 http_response_write(client, status, headers, body)
539 client.close # flush and uncork socket immediately, no keepalive
541 handle_error(client, e)
544 EXIT_SIGS = [ :QUIT, :TERM, :INT ]
545 WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
547 # gets rid of stuff the worker has no business keeping track of
548 # to free some resources and drops all sig handlers.
549 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
551 def init_worker_process(worker)
552 # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
553 EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
554 exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
555 WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
556 trap(:CHLD, 'DEFAULT')
558 proc_name "worker[#{worker.nr}]"
562 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
563 after_fork.call(self, worker) # can drop perms
564 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
565 self.timeout /= 2.0 # halve it for select()
567 build_app! unless preload_app
569 @after_fork = @listener_opts = @orig_app = nil
572 def reopen_worker_logs(worker_nr)
573 logger.info "worker=#{worker_nr} reopening logs..."
574 Unicorn::Util.reopen_logs
575 logger.info "worker=#{worker_nr} done reopening logs"
578 logger.error(e) rescue nil
579 exit!(77) # EX_NOPERM in sysexits.h
582 # runs inside each forked worker, this sits around and waits
583 # for connections and doesn't die until the parent dies (or is
584 # given a INT, QUIT, or TERM signal)
585 def worker_loop(worker)
587 init_worker_process(worker)
588 nr = 0 # this becomes negative if we need to reopen logs
592 # closing anything we IO.select on will raise EBADF
593 trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
594 trap(:QUIT) { worker = nil; LISTENERS.each { |s| s.close rescue nil }.clear }
595 logger.info "worker=#{worker.nr} ready"
598 nr < 0 and reopen_worker_logs(worker.nr)
601 worker.tick = Time.now.to_i
602 while sock = ready.shift
603 if client = sock.kgio_tryaccept
604 process_client(client)
606 worker.tick = Time.now.to_i
611 # make the following bet: if we accepted clients this round,
612 # we're probably reasonably busy, so avoid calling select()
613 # and do a speculative non-blocking accept() on ready listeners
614 # before we sleep again in select().
615 unless nr == 0 # (nr < 0) => reopen logs (unlikely)
620 ppid == Process.ppid or return
622 # timeout used so we can detect parent death:
623 worker.tick = Time.now.to_i
624 ret = IO.select(l, nil, SELF_PIPE, @timeout) and ready = ret[0]
628 Unicorn.log_error(@logger, "listen loop error", e) if worker
632 # delivers a signal to a worker and fails gracefully if the worker
633 # is no longer running.
634 def kill_worker(signal, wpid)
635 Process.kill(signal, wpid)
637 worker = WORKERS.delete(wpid) and worker.close rescue nil
640 # delivers a signal to each worker
641 def kill_each_worker(signal)
642 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
645 # unlinks a PID file at given +path+ if it contains the current PID
646 # still potentially racy without locking the directory (which is
647 # non-portable and may interact badly with other programs), but the
648 # window for hitting the race condition is small
649 def unlink_pid_safe(path)
650 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
653 # returns a PID if a given path contains a non-stale PID file,
656 wpid = File.read(path).to_i
658 Process.kill(0, wpid)
660 rescue Errno::ESRCH, Errno::ENOENT
661 # don't unlink stale pid files, racy without non-portable locking...
666 logger.info "reloading config_file=#{config.config_file}"
667 config[:listeners].replace(@init_listeners)
670 kill_each_worker(:QUIT)
671 Unicorn::Util.reopen_logs
673 build_app! if preload_app
674 logger.info "done reloading config_file=#{config.config_file}"
675 rescue StandardError, LoadError, SyntaxError => e
676 Unicorn.log_error(@logger,
677 "error reloading config_file=#{config.config_file}", e)
678 self.app = loaded_app
681 # returns an array of string names for the given listener array
682 def listener_names(listeners = LISTENERS)
683 listeners.map { |io| sock_name(io) }
687 if app.respond_to?(:arity) && app.arity == 0
688 if defined?(Gem) && Gem.respond_to?(:refresh)
689 logger.info "Refreshing Gem list"
697 $0 = ([ File.basename(START_CTX[0]), tag
698 ]).concat(START_CTX[:argv]).join(' ')
701 def redirect_io(io, path)
702 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
707 SELF_PIPE.each { |io| io.close rescue nil }
708 SELF_PIPE.replace(Kgio::Pipe.new)
709 SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
712 def inherit_listeners!
713 # inherit sockets from parents, they need to be plain Socket objects
714 # before they become Kgio::UNIXServer or Kgio::TCPServer
715 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
716 io = Socket.for_fd(fd.to_i)
717 set_server_sockopt(io, listener_opts[sock_name(io)])
719 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
723 config_listeners = config[:listeners].dup
724 LISTENERS.replace(inherited)
726 # we start out with generic Socket objects that get cast to either
727 # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
728 # objects share the same OS-level file descriptor as the higher-level
729 # *Server objects; we need to prevent Socket objects from being
731 config_listeners -= listener_names
732 if config_listeners.empty? && LISTENERS.empty?
733 config_listeners << Unicorn::Const::DEFAULT_LISTEN
734 @init_listeners << Unicorn::Const::DEFAULT_LISTEN
735 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
737 config_listeners.each { |addr| listen(addr) }
738 raise ArgumentError, "no listeners" if LISTENERS.empty?