1 # -*- encoding: binary -*-
4 require 'unicorn/socket_helper'
8 # Unicorn module containing all of the classes (include C extensions) for running
9 # a Unicorn web server. It contains a minimalist HTTP server with just enough
10 # functionality to service web application requests fast as possible.
13 # raised inside TeeInput when a client closes the socket inside the
14 # application dispatch. This is always raised with an empty backtrace
15 # since there is nothing in the application stack that is responsible
16 # for client shutdowns/disconnects.
17 class ClientShutdown < EOFError
20 autoload :Const, 'unicorn/const'
21 autoload :HttpRequest, 'unicorn/http_request'
22 autoload :HttpResponse, 'unicorn/http_response'
23 autoload :Configurator, 'unicorn/configurator'
24 autoload :TeeInput, 'unicorn/tee_input'
25 autoload :Util, 'unicorn/util'
28 def run(app, options = {})
29 HttpServer.new(app, options).start.join
32 # This returns a lambda to pass in as the app, this does not "build" the
33 # app (which we defer based on the outcome of "preload_app" in the
34 # Unicorn config). The returned lambda will be called when it is
35 # time to build the app.
38 # parse embedded command-line options in config.ru comments
39 /^#\\(.*)/ =~ File.read(ru) and opts.parse!($1.split(/\s+/))
46 raw.sub!(/^__END__\n.*/, '')
47 eval("Rack::Builder.new {(#{raw}\n)}.to_app", TOPLEVEL_BINDING, ru)
50 Object.const_get(File.basename(ru, '.rb').capitalize)
53 pp({ :inner_app => inner_app }) if $DEBUG
55 # return value, matches rackup defaults based on env
59 use Rack::CommonLogger, $stderr
60 use Rack::ShowExceptions
66 use Rack::CommonLogger, $stderr
76 # This is the process manager of Unicorn. This manages worker
77 # processes which in turn handle the I/O and application process.
78 # Listener sockets are started in the master process and shared with
79 # forked worker children.
81 class HttpServer < Struct.new(:app, :timeout, :worker_processes,
82 :before_fork, :after_fork, :before_exec,
83 :logger, :pid, :listener_opts, :preload_app,
84 :reexec_pid, :orig_app, :init_listeners,
85 :master_pid, :config, :ready_pipe, :user)
86 include ::Unicorn::SocketHelper
88 # prevents IO objects in here from being GC-ed
91 # all bound listener sockets
94 # This hash maps PIDs to Workers
97 # We use SELF_PIPE differently in the master and worker processes:
99 # * The master process never closes or reinitializes this once
100 # initialized. Signal handlers in the master process will write to
101 # it to wake up the master from IO.select in exactly the same manner
102 # djb describes in http://cr.yp.to/docs/selfpipe.html
104 # * The workers immediately close the pipe they inherit from the
105 # master and replace it with a new pipe after forking. This new
106 # pipe is also used to wakeup from IO.select from inside (worker)
107 # signal handlers. However, workers *close* the pipe descriptors in
108 # the signal handlers to raise EBADF in IO.select instead of writing
109 # like we do in the master. We cannot easily use the reader set for
110 # IO.select because LISTENERS is already that set, and it's extra
111 # work (and cycles) to distinguish the pipe FD from the reader set
112 # once IO.select returns. So we're lazy and just close the pipe when
113 # a (rare) signal arrives in the worker and reinitialize the pipe later.
116 # signal queue used for self-piping
119 # constant lookups are faster and we're single-threaded/non-reentrant
120 REQUEST = HttpRequest.new
122 # We populate this at startup so we can figure out how to reexecute
123 # and upgrade the currently running instance of Unicorn
124 # This Hash is considered a stable interface and changing its contents
125 # will allow you to switch between different installations of Unicorn
126 # or even different installations of the same applications without
127 # downtime. Keys of this constant Hash are described as follows:
129 # * 0 - the path to the unicorn/unicorn_rails executable
130 # * :argv - a deep copy of the ARGV array the executable originally saw
131 # * :cwd - the working directory of the application, this is where
132 # you originally started Unicorn.
134 # The following example may be used in your Unicorn config file to
135 # change your working directory during a config reload (HUP) without
136 # upgrading or restarting:
138 # Dir.chdir(Unicorn::HttpServer::START_CTX[:cwd] = path)
140 # To change your unicorn executable to a different path without downtime,
141 # you can set the following in your Unicorn config file, HUP and then
142 # continue with the traditional USR2 + QUIT upgrade steps:
144 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
146 :argv => ARGV.map { |arg| arg.dup },
148 # favor ENV['PWD'] since it is (usually) symlink aware for
149 # Capistrano and like systems
151 a = File.stat(pwd = ENV['PWD'])
152 b = File.stat(Dir.pwd)
153 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
161 # This class and its members can be considered a stable interface
162 # and will not change in a backwards-incompatible fashion between
163 # releases of Unicorn. You may need to access it in the
164 # before_fork/after_fork hooks. See the Unicorn::Configurator RDoc
166 class Worker < Struct.new(:nr, :tmp, :switched)
168 # worker objects may be compared to just plain numbers
173 # Changes the worker process to the specified +user+ and +group+
174 # This is only intended to be called from within the worker
175 # process from the +after_fork+ hook. This should be called in
176 # the +after_fork+ hook after any priviledged functions need to be
177 # run (e.g. to set per-worker CPU affinity, niceness, etc)
179 # Any and all errors raised within this method will be propagated
180 # directly back to the caller (usually the +after_fork+ hook.
181 # These errors commonly include ArgumentError for specifying an
182 # invalid user/group and Errno::EPERM for insufficient priviledges
183 def user(user, group = nil)
184 # we do not protect the caller, checking Process.euid == 0 is
185 # insufficient because modern systems have fine-grained
186 # capabilities. Let the caller handle any and all errors.
187 uid = Etc.getpwnam(user).uid
188 gid = Etc.getgrnam(group).gid if group
189 Unicorn::Util.chown_logs(uid, gid)
191 if gid && Process.egid != gid
192 Process.initgroups(user, gid)
193 Process::GID.change_privilege(gid)
195 Process.euid != uid and Process::UID.change_privilege(uid)
201 # Creates a working server on host:port (strange things happen if
202 # port isn't a Number). Use HttpServer::run to start the server and
203 # HttpServer.run.join to join the thread that's processing
204 # incoming requests on the socket.
205 def initialize(app, options = {})
208 self.ready_pipe = options.delete(:ready_pipe)
209 self.init_listeners = options[:listeners] ? options[:listeners].dup : []
210 self.config = Configurator.new(options.merge(:use_defaults => true))
211 self.listener_opts = {}
213 # we try inheriting listeners first, so we bind them later.
214 # we don't write the pid file until we've bound listeners in case
215 # unicorn was started twice by mistake. Even though our #pid= method
216 # checks for stale/existing pid files, race conditions are still
217 # possible (and difficult/non-portable to avoid) and can be likely
218 # to clobber the pid if the second start was in quick succession
219 # after the first, so we rely on the listener binding to fail in
220 # that case. Some tests (in and outside of this source tree) and
221 # monitoring tools may also rely on pid files existing before we
222 # attempt to connect to the listener(s)
223 config.commit!(self, :skip => [:listeners, :pid])
227 # Runs the thing. Returns self so you can run join on it
229 BasicSocket.do_not_reverse_lookup = true
231 # inherit sockets from parents, they need to be plain Socket objects
232 # before they become UNIXServer or TCPServer
233 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
234 io = Socket.for_fd(fd.to_i)
235 set_server_sockopt(io, listener_opts[sock_name(io)])
237 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
241 config_listeners = config[:listeners].dup
242 LISTENERS.replace(inherited)
244 # we start out with generic Socket objects that get cast to either
245 # TCPServer or UNIXServer objects; but since the Socket objects
246 # share the same OS-level file descriptor as the higher-level *Server
247 # objects; we need to prevent Socket objects from being garbage-collected
248 config_listeners -= listener_names
249 if config_listeners.empty? && LISTENERS.empty?
250 config_listeners << Unicorn::Const::DEFAULT_LISTEN
251 init_listeners << Unicorn::Const::DEFAULT_LISTEN
252 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
254 config_listeners.each { |addr| listen(addr) }
255 raise ArgumentError, "no listeners" if LISTENERS.empty?
257 # this pipe is used to wake us up from select(2) in #join when signals
258 # are trapped. See trap_deferred.
261 # setup signal handlers before writing pid file in case people get
262 # trigger happy and send signals as soon as the pid file exists.
263 # Note that signals don't actually get handled until the #join method
264 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
265 trap(:CHLD) { |_| awaken_master }
266 self.pid = config[:pid]
269 build_app! if preload_app
270 maintain_worker_count
274 # replaces current listener set with +listeners+. This will
275 # close the socket if it will not exist in the new listener set
276 def listeners=(listeners)
277 cur_names, dead_names = [], []
278 listener_names.each do |name|
280 # mark unlinked sockets as dead so we can rebind them
281 (File.socket?(name) ? cur_names : dead_names) << name
286 set_names = listener_names(listeners)
287 dead_names.concat(cur_names - set_names).uniq!
289 LISTENERS.delete_if do |io|
290 if dead_names.include?(sock_name(io))
291 IO_PURGATORY.delete_if do |pio|
292 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
294 (io.close rescue nil).nil? # true
296 set_server_sockopt(io, listener_opts[sock_name(io)])
301 (set_names - cur_names).each { |addr| listen(addr) }
304 def stdout_path=(path); redirect_io($stdout, path); end
305 def stderr_path=(path); redirect_io($stderr, path); end
308 HttpRequest::DEFAULTS["rack.logger"] = super
311 # sets the path for the PID file of the master process
314 if x = valid_pid?(path)
315 return path if pid && path == pid && x == $$
316 raise ArgumentError, "Already running on PID:#{x} " \
317 "(or pid=#{path} is stale)"
320 unlink_pid_safe(pid) if pid
324 tmp = "#{File.dirname(path)}/#{rand}.#$$"
325 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
330 File.rename(fp.path, path)
336 # add a given address to the +listeners+ set, idempotently
337 # Allows workers to add a private, per-process listener via the
338 # after_fork hook. Very useful for debugging and testing.
339 # +:tries+ may be specified as an option for the number of times
340 # to retry, and +:delay+ may be specified as the time in seconds
341 # to delay between retries.
342 # A negative value for +:tries+ indicates the listen will be
343 # retried indefinitely, this is useful when workers belonging to
344 # different masters are spawned during a transparent upgrade.
345 def listen(address, opt = {}.merge(listener_opts[address] || {}))
346 address = config.expand_addr(address)
347 return if String === address && listener_names.include?(address)
349 delay = opt[:delay] || 0.5
350 tries = opt[:tries] || 5
352 io = bind_listen(address, opt)
353 unless TCPServer === io || UNIXServer === io
357 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
360 rescue Errno::EADDRINUSE => err
361 logger.error "adding listener failed addr=#{address} (in use)"
362 raise err if tries == 0
364 logger.error "retrying in #{delay} seconds " \
365 "(#{tries < 0 ? 'infinite' : tries} tries left)"
369 logger.fatal "error adding listener addr=#{address}"
374 # monitors children and receives signals forever
375 # (or until a termination signal is sent). This handles signals
376 # one-at-a-time time and we'll happily drop signals in case somebody
377 # is signalling us too often.
380 last_check = Time.now
383 logger.info "master process ready" # test_exec.rb relies on this message
385 ready_pipe.syswrite($$.to_s)
386 ready_pipe.close rescue nil
387 self.ready_pipe = nil
394 # avoid murdering workers after our master process (or the
395 # machine) comes out of suspend/hibernation
396 if (last_check + timeout) >= (last_check = Time.now)
399 maintain_worker_count if respawn
401 when :QUIT # graceful shutdown
403 when :TERM, :INT # immediate shutdown
406 when :USR1 # rotate logs
407 logger.info "master reopening logs..."
408 Unicorn::Util.reopen_logs
409 logger.info "master done reopening logs"
410 kill_each_worker(:USR1)
411 when :USR2 # exec binary, stay alive in case something went wrong
414 if Process.ppid == 1 || Process.getpgrp != $$
416 logger.info "gracefully stopping all workers"
417 kill_each_worker(:QUIT)
419 logger.info "SIGWINCH ignored because we're not daemonized"
422 self.worker_processes += 1
424 self.worker_processes -= 1 if self.worker_processes > 0
427 if config.config_file
429 redo # immediate reaping since we may have QUIT workers
430 else # exec binary and exit if there's no config file
431 logger.info "config_file not present, reexecuting binary"
440 logger.error "Unhandled master loop exception #{e.inspect}."
441 logger.error e.backtrace.join("\n")
444 stop # gracefully shutdown all workers on our way out
445 logger.info "master complete"
446 unlink_pid_safe(pid) if pid
449 # Terminates all workers, but does not exit master process
450 def stop(graceful = true)
452 limit = Time.now + timeout
453 until WORKERS.empty? || Time.now > limit
454 kill_each_worker(graceful ? :QUIT : :TERM)
458 kill_each_worker(:KILL)
463 # list of signals we care about and trap in master.
464 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
467 # defer a signal for later processing in #join (master process)
468 def trap_deferred(signal)
469 trap(signal) do |sig_nr|
470 if SIG_QUEUE.size < 5
474 logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
479 # wait for a signal hander to wake us up and then consume the pipe
480 # Wake up every second anyways to run murder_lazy_workers
483 ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
484 ready.first && ready.first.first or return
485 loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
486 rescue Errno::EAGAIN, Errno::EINTR
492 SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
493 rescue Errno::EAGAIN, Errno::EINTR
494 # pipe is full, master should wake up anyways
499 # reaps all unreaped workers
503 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
505 if reexec_pid == wpid
506 logger.error "reaped #{status.inspect} exec()-ed"
508 self.pid = pid.chomp('.oldbin') if pid
511 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
512 logger.info "reaped #{status.inspect} " \
513 "worker=#{worker.nr rescue 'unknown'}"
520 # reexecutes the START_CTX with a new binary
524 Process.kill(0, reexec_pid)
525 logger.error "reexec-ed child already running PID:#{reexec_pid}"
533 old_pid = "#{pid}.oldbin"
536 self.pid = old_pid # clear the path for a new pid file
538 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
539 "existing pid=#{old_pid}, refusing rexec"
542 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
547 self.reexec_pid = fork do
548 listener_fds = LISTENERS.map { |sock| sock.fileno }
549 ENV['UNICORN_FD'] = listener_fds.join(',')
550 Dir.chdir(START_CTX[:cwd])
551 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
553 # avoid leaking FDs we don't know about, but let before_exec
554 # unset FD_CLOEXEC, if anything else in the app eventually
555 # relies on FD inheritence.
556 (3..1024).each do |io|
557 next if listener_fds.include?(io)
558 io = IO.for_fd(io) rescue nil
561 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
563 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
564 before_exec.call(self)
567 proc_name 'master (old)'
570 # forcibly terminate all workers that haven't checked in in timeout
571 # seconds. The timeout is implemented using an unlinked File
572 # shared between the parent process and each worker. The worker
573 # runs File#chmod to modify the ctime of the File. If the ctime
574 # is stale for >timeout seconds, then we'll kill the corresponding
576 def murder_lazy_workers
577 WORKERS.dup.each_pair do |wpid, worker|
578 stat = worker.tmp.stat
579 # skip workers that disable fchmod or have never fchmod-ed
580 stat.mode == 0100600 and next
581 (diff = (Time.now - stat.ctime)) <= timeout and next
582 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
583 "(#{diff}s > #{timeout}s), killing"
584 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
588 def spawn_missing_workers
589 (0...worker_processes).each do |worker_nr|
590 WORKERS.values.include?(worker_nr) and next
591 worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
592 before_fork.call(self, worker)
594 ready_pipe.close if ready_pipe
595 self.ready_pipe = nil
601 def maintain_worker_count
602 (off = WORKERS.size - worker_processes) == 0 and return
603 off < 0 and return spawn_missing_workers
604 WORKERS.dup.each_pair { |wpid,w|
605 w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
609 # if we get any error, try to write something back to the client
610 # assuming we haven't closed the socket, but don't get hung up
611 # if the socket is already closed or broken. We'll always ensure
612 # the socket is closed at the end of this function
613 def handle_error(client, e)
615 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
616 Const::ERROR_500_RESPONSE
617 when HttpParserError # try to tell the client they're bad
618 Const::ERROR_400_RESPONSE
620 logger.error "Read error: #{e.inspect}"
621 logger.error e.backtrace.join("\n")
622 Const::ERROR_500_RESPONSE
624 client.write_nonblock(msg)
630 # once a client is accepted, it is processed in its entirety here
631 # in 3 easy steps: read request, call app, write app response
632 def process_client(client)
633 client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
634 response = app.call(env = REQUEST.read(client))
636 if 100 == response.first.to_i
637 client.write(Const::EXPECT_100_RESPONSE)
638 env.delete(Const::HTTP_EXPECT)
639 response = app.call(env)
641 HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
643 handle_error(client, e)
646 # gets rid of stuff the worker has no business keeping track of
647 # to free some resources and drops all sig handlers.
648 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
650 def init_worker_process(worker)
651 QUEUE_SIGS.each { |sig| trap(sig, nil) }
652 trap(:CHLD, 'DEFAULT')
654 proc_name "worker[#{worker.nr}]"
657 WORKERS.values.each { |other| other.tmp.close rescue nil }
659 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
660 worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
661 after_fork.call(self, worker) # can drop perms
662 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
663 self.timeout /= 2.0 # halve it for select()
664 build_app! unless preload_app
667 def reopen_worker_logs(worker_nr)
668 logger.info "worker=#{worker_nr} reopening logs..."
669 Unicorn::Util.reopen_logs
670 logger.info "worker=#{worker_nr} done reopening logs"
674 # runs inside each forked worker, this sits around and waits
675 # for connections and doesn't die until the parent dies (or is
676 # given a INT, QUIT, or TERM signal)
677 def worker_loop(worker)
679 init_worker_process(worker)
680 nr = 0 # this becomes negative if we need to reopen logs
681 alive = worker.tmp # tmp is our lifeline to the master process
684 # closing anything we IO.select on will raise EBADF
685 trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
686 trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
687 [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
688 logger.info "worker=#{worker.nr} ready"
692 nr < 0 and reopen_worker_logs(worker.nr)
695 # we're a goner in timeout seconds anyways if alive.chmod
696 # breaks, so don't trap the exception. Using fchmod() since
697 # futimes() is not available in base Ruby and I very strongly
698 # prefer temporary files to be unlinked for security,
699 # performance and reliability reasons, so utime is out. No-op
700 # changes with chmod doesn't update ctime on all filesystems; so
701 # we change our counter each and every time (after process_client
702 # and before IO.select).
703 alive.chmod(m = 0 == m ? 1 : 0)
707 process_client(sock.accept_nonblock)
709 alive.chmod(m = 0 == m ? 1 : 0)
710 rescue Errno::EAGAIN, Errno::ECONNABORTED
715 # make the following bet: if we accepted clients this round,
716 # we're probably reasonably busy, so avoid calling select()
717 # and do a speculative accept_nonblock on ready listeners
718 # before we sleep again in select().
719 redo unless nr == 0 # (nr < 0) => reopen logs
721 ppid == Process.ppid or return
722 alive.chmod(m = 0 == m ? 1 : 0)
724 # timeout used so we can detect parent death:
725 ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
734 logger.error "Unhandled listen loop exception #{e.inspect}."
735 logger.error e.backtrace.join("\n")
740 # delivers a signal to a worker and fails gracefully if the worker
741 # is no longer running.
742 def kill_worker(signal, wpid)
744 Process.kill(signal, wpid)
746 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
750 # delivers a signal to each worker
751 def kill_each_worker(signal)
752 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
755 # unlinks a PID file at given +path+ if it contains the current PID
756 # still potentially racy without locking the directory (which is
757 # non-portable and may interact badly with other programs), but the
758 # window for hitting the race condition is small
759 def unlink_pid_safe(path)
760 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
763 # returns a PID if a given path contains a non-stale PID file,
766 wpid = File.read(path).to_i
767 wpid <= 0 and return nil
769 Process.kill(0, wpid)
772 # don't unlink stale pid files, racy without non-portable locking...
780 logger.info "reloading config_file=#{config.config_file}"
781 config[:listeners].replace(init_listeners)
784 kill_each_worker(:QUIT)
785 Unicorn::Util.reopen_logs
787 build_app! if preload_app
788 logger.info "done reloading config_file=#{config.config_file}"
789 rescue StandardError, LoadError, SyntaxError => e
790 logger.error "error reloading config_file=#{config.config_file}: " \
791 "#{e.class} #{e.message}"
792 self.app = loaded_app
796 # returns an array of string names for the given listener array
797 def listener_names(listeners = LISTENERS)
798 listeners.map { |io| sock_name(io) }
802 if app.respond_to?(:arity) && app.arity == 0
803 # exploit COW in case of preload_app. Also avoids race
804 # conditions in Rainbows! since load/require are not thread-safe
805 Unicorn.constants.each { |x| Unicorn.const_get(x) }
807 if defined?(Gem) && Gem.respond_to?(:refresh)
808 logger.info "Refreshing Gem list"
816 $0 = ([ File.basename(START_CTX[0]), tag
817 ]).concat(START_CTX[:argv]).join(' ')
820 def redirect_io(io, path)
821 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
826 SELF_PIPE.each { |io| io.close rescue nil }
827 SELF_PIPE.replace(IO.pipe)
828 SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }