1 # -*- encoding: binary -*-
4 require 'unicorn/socket_helper'
7 # Unicorn module containing all of the classes (include C extensions) for running
8 # a Unicorn web server. It contains a minimalist HTTP server with just enough
9 # functionality to service web application requests fast as possible.
12 # raise this inside TeeInput when a client disconnects inside the
13 # application dispatch
14 class ClientShutdown < EOFError
17 autoload :Const, 'unicorn/const'
18 autoload :HttpRequest, 'unicorn/http_request'
19 autoload :HttpResponse, 'unicorn/http_response'
20 autoload :Configurator, 'unicorn/configurator'
21 autoload :TeeInput, 'unicorn/tee_input'
22 autoload :Util, 'unicorn/util'
25 def run(app, options = {})
26 HttpServer.new(app, options).start.join
30 # This is the process manager of Unicorn. This manages worker
31 # processes which in turn handle the I/O and application process.
32 # Listener sockets are started in the master process and shared with
33 # forked worker children.
35 class HttpServer < Struct.new(:listener_opts, :timeout, :worker_processes,
36 :before_fork, :after_fork, :before_exec,
37 :logger, :pid, :app, :preload_app,
38 :reexec_pid, :orig_app, :init_listeners,
40 include ::Unicorn::SocketHelper
42 # prevents IO objects in here from being GC-ed
45 # all bound listener sockets
48 # This hash maps PIDs to Workers
51 # We use SELF_PIPE differently in the master and worker processes:
53 # * The master process never closes or reinitializes this once
54 # initialized. Signal handlers in the master process will write to
55 # it to wake up the master from IO.select in exactly the same manner
56 # djb describes in http://cr.yp.to/docs/selfpipe.html
58 # * The workers immediately close the pipe they inherit from the
59 # master and replace it with a new pipe after forking. This new
60 # pipe is also used to wakeup from IO.select from inside (worker)
61 # signal handlers. However, workers *close* the pipe descriptors in
62 # the signal handlers to raise EBADF in IO.select instead of writing
63 # like we do in the master. We cannot easily use the reader set for
64 # IO.select because LISTENERS is already that set, and it's extra
65 # work (and cycles) to distinguish the pipe FD from the reader set
66 # once IO.select returns. So we're lazy and just close the pipe when
67 # a (rare) signal arrives in the worker and reinitialize the pipe later.
70 # signal queue used for self-piping
73 # constant lookups are faster and we're single-threaded/non-reentrant
74 REQUEST = HttpRequest.new
76 # We populate this at startup so we can figure out how to reexecute
77 # and upgrade the currently running instance of Unicorn
78 # This Hash is considered a stable interface and changing its contents
79 # will allow you to switch between different installations of Unicorn
80 # or even different installations of the same applications without
81 # downtime. Keys of this constant Hash are described as follows:
83 # * 0 - the path to the unicorn/unicorn_rails executable
84 # * :argv - a deep copy of the ARGV array the executable originally saw
85 # * :cwd - the working directory of the application, this is where
86 # you originally started Unicorn.
88 # The following example may be used in your Unicorn config file to
89 # change your working directory during a config reload (HUP) without
90 # upgrading or restarting:
92 # Dir.chdir(Unicorn::HttpServer::START_CTX[:cwd] = path)
94 # To change your unicorn executable to a different path without downtime,
95 # you can set the following in your Unicorn config file, HUP and then
96 # continue with the traditional USR2 + QUIT upgrade steps:
98 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
100 :argv => ARGV.map { |arg| arg.dup },
102 # favor ENV['PWD'] since it is (usually) symlink aware for
103 # Capistrano and like systems
105 a = File.stat(pwd = ENV['PWD'])
106 b = File.stat(Dir.pwd)
107 a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
115 # This class and its members can be considered a stable interface
116 # and will not change in a backwards-incompatible fashion between
117 # releases of Unicorn. You may need to access it in the
118 # before_fork/after_fork hooks. See the Unicorn::Configurator RDoc
120 class Worker < Struct.new(:nr, :tmp)
124 # worker objects may be compared to just plain numbers
129 # Changes the worker process to the specified +user+ and +group+
130 # This is only intended to be called from within the worker
131 # process from the +after_fork+ hook. This should be called in
132 # the +after_fork+ hook after any priviledged functions need to be
133 # run (e.g. to set per-worker CPU affinity, niceness, etc)
135 # Any and all errors raised within this method will be propagated
136 # directly back to the caller (usually the +after_fork+ hook.
137 # These errors commonly include ArgumentError for specifying an
138 # invalid user/group and Errno::EPERM for insufficient priviledges
139 def user(user, group = nil)
140 # we do not protect the caller, checking Process.euid == 0 is
141 # insufficient because modern systems have fine-grained
142 # capabilities. Let the caller handle any and all errors.
143 uid = Etc.getpwnam(user).uid
144 gid = Etc.getgrnam(group).gid if group
145 Unicorn::Util.chown_logs(uid, gid)
147 if gid && Process.egid != gid
148 Process.initgroups(user, gid)
149 Process::GID.change_privilege(gid)
151 Process.euid != uid and Process::UID.change_privilege(uid)
156 # Creates a working server on host:port (strange things happen if
157 # port isn't a Number). Use HttpServer::run to start the server and
158 # HttpServer.run.join to join the thread that's processing
159 # incoming requests on the socket.
160 def initialize(app, options = {})
163 self.init_listeners = options[:listeners] ? options[:listeners].dup : []
164 self.config = Configurator.new(options.merge(:use_defaults => true))
165 self.listener_opts = {}
167 # we try inheriting listeners first, so we bind them later.
168 # we don't write the pid file until we've bound listeners in case
169 # unicorn was started twice by mistake. Even though our #pid= method
170 # checks for stale/existing pid files, race conditions are still
171 # possible (and difficult/non-portable to avoid) and can be likely
172 # to clobber the pid if the second start was in quick succession
173 # after the first, so we rely on the listener binding to fail in
174 # that case. Some tests (in and outside of this source tree) and
175 # monitoring tools may also rely on pid files existing before we
176 # attempt to connect to the listener(s)
177 config.commit!(self, :skip => [:listeners, :pid])
181 # Runs the thing. Returns self so you can run join on it
183 BasicSocket.do_not_reverse_lookup = true
185 # inherit sockets from parents, they need to be plain Socket objects
186 # before they become UNIXServer or TCPServer
187 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
188 io = Socket.for_fd(fd.to_i)
189 set_server_sockopt(io, listener_opts[sock_name(io)])
191 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
195 config_listeners = config[:listeners].dup
196 LISTENERS.replace(inherited)
198 # we start out with generic Socket objects that get cast to either
199 # TCPServer or UNIXServer objects; but since the Socket objects
200 # share the same OS-level file descriptor as the higher-level *Server
201 # objects; we need to prevent Socket objects from being garbage-collected
202 config_listeners -= listener_names
203 if config_listeners.empty? && LISTENERS.empty?
204 config_listeners << Unicorn::Const::DEFAULT_LISTEN
205 init_listeners << Unicorn::Const::DEFAULT_LISTEN
206 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
208 config_listeners.each { |addr| listen(addr) }
209 raise ArgumentError, "no listeners" if LISTENERS.empty?
210 self.pid = config[:pid]
212 build_app! if preload_app
213 maintain_worker_count
217 # replaces current listener set with +listeners+. This will
218 # close the socket if it will not exist in the new listener set
219 def listeners=(listeners)
220 cur_names, dead_names = [], []
221 listener_names.each do |name|
223 # mark unlinked sockets as dead so we can rebind them
224 (File.socket?(name) ? cur_names : dead_names) << name
229 set_names = listener_names(listeners)
230 dead_names.concat(cur_names - set_names).uniq!
232 LISTENERS.delete_if do |io|
233 if dead_names.include?(sock_name(io))
234 IO_PURGATORY.delete_if do |pio|
235 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
237 (io.close rescue nil).nil? # true
239 set_server_sockopt(io, listener_opts[sock_name(io)])
244 (set_names - cur_names).each { |addr| listen(addr) }
247 def stdout_path=(path); redirect_io($stdout, path); end
248 def stderr_path=(path); redirect_io($stderr, path); end
250 alias_method :set_pid, :pid=
253 # sets the path for the PID file of the master process
256 if x = valid_pid?(path)
257 return path if pid && path == pid && x == $$
258 raise ArgumentError, "Already running on PID:#{x} " \
259 "(or pid=#{path} is stale)"
262 unlink_pid_safe(pid) if pid
266 tmp = "#{File.dirname(path)}/#{rand}.#$$"
267 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
272 File.rename(fp.path, path)
278 # add a given address to the +listeners+ set, idempotently
279 # Allows workers to add a private, per-process listener via the
280 # after_fork hook. Very useful for debugging and testing.
281 # +:tries+ may be specified as an option for the number of times
282 # to retry, and +:delay+ may be specified as the time in seconds
283 # to delay between retries.
284 # A negative value for +:tries+ indicates the listen will be
285 # retried indefinitely, this is useful when workers belonging to
286 # different masters are spawned during a transparent upgrade.
287 def listen(address, opt = {}.merge(listener_opts[address] || {}))
288 address = config.expand_addr(address)
289 return if String === address && listener_names.include?(address)
291 delay = opt[:delay] || 0.5
292 tries = opt[:tries] || 5
294 io = bind_listen(address, opt)
295 unless TCPServer === io || UNIXServer === io
299 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
302 rescue Errno::EADDRINUSE => err
303 logger.error "adding listener failed addr=#{address} (in use)"
304 raise err if tries == 0
306 logger.error "retrying in #{delay} seconds " \
307 "(#{tries < 0 ? 'infinite' : tries} tries left)"
313 # monitors children and receives signals forever
314 # (or until a termination signal is sent). This handles signals
315 # one-at-a-time time and we'll happily drop signals in case somebody
316 # is signalling us too often.
318 # this pipe is used to wake us up from select(2) in #join when signals
319 # are trapped. See trap_deferred
322 last_check = Time.now
324 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
325 trap(:CHLD) { |sig_nr| awaken_master }
327 logger.info "master process ready" # test_exec.rb relies on this message
333 # avoid murdering workers after our master process (or the
334 # machine) comes out of suspend/hibernation
335 if (last_check + timeout) >= (last_check = Time.now)
338 maintain_worker_count if respawn
340 when :QUIT # graceful shutdown
342 when :TERM, :INT # immediate shutdown
345 when :USR1 # rotate logs
346 logger.info "master reopening logs..."
347 Unicorn::Util.reopen_logs
348 logger.info "master done reopening logs"
349 kill_each_worker(:USR1)
350 when :USR2 # exec binary, stay alive in case something went wrong
353 if Process.ppid == 1 || Process.getpgrp != $$
355 logger.info "gracefully stopping all workers"
356 kill_each_worker(:QUIT)
358 logger.info "SIGWINCH ignored because we're not daemonized"
361 self.worker_processes += 1
363 self.worker_processes -= 1 if self.worker_processes > 0
366 if config.config_file
368 redo # immediate reaping since we may have QUIT workers
369 else # exec binary and exit if there's no config file
370 logger.info "config_file not present, reexecuting binary"
379 logger.error "Unhandled master loop exception #{e.inspect}."
380 logger.error e.backtrace.join("\n")
383 stop # gracefully shutdown all workers on our way out
384 logger.info "master complete"
385 unlink_pid_safe(pid) if pid
388 # Terminates all workers, but does not exit master process
389 def stop(graceful = true)
391 limit = Time.now + timeout
392 until WORKERS.empty? || Time.now > limit
393 kill_each_worker(graceful ? :QUIT : :TERM)
397 kill_each_worker(:KILL)
402 # list of signals we care about and trap in master.
403 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
406 # defer a signal for later processing in #join (master process)
407 def trap_deferred(signal)
408 trap(signal) do |sig_nr|
409 if SIG_QUEUE.size < 5
413 logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
418 # wait for a signal hander to wake us up and then consume the pipe
419 # Wake up every second anyways to run murder_lazy_workers
422 ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
423 ready.first && ready.first.first or return
424 loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
425 rescue Errno::EAGAIN, Errno::EINTR
431 SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
432 rescue Errno::EAGAIN, Errno::EINTR
433 # pipe is full, master should wake up anyways
438 # reaps all unreaped workers
442 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
444 if reexec_pid == wpid
445 logger.error "reaped #{status.inspect} exec()-ed"
447 self.pid = pid.chomp('.oldbin') if pid
450 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
451 logger.info "reaped #{status.inspect} " \
452 "worker=#{worker.nr rescue 'unknown'}"
459 # reexecutes the START_CTX with a new binary
463 Process.kill(0, reexec_pid)
464 logger.error "reexec-ed child already running PID:#{reexec_pid}"
472 old_pid = "#{pid}.oldbin"
475 self.pid = old_pid # clear the path for a new pid file
477 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
478 "existing pid=#{old_pid}, refusing rexec"
481 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
486 self.reexec_pid = fork do
487 listener_fds = LISTENERS.map { |sock| sock.fileno }
488 ENV['UNICORN_FD'] = listener_fds.join(',')
489 Dir.chdir(START_CTX[:cwd])
490 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
492 # avoid leaking FDs we don't know about, but let before_exec
493 # unset FD_CLOEXEC, if anything else in the app eventually
494 # relies on FD inheritence.
495 (3..1024).each do |io|
496 next if listener_fds.include?(io)
497 io = IO.for_fd(io) rescue nil
500 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
502 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
503 before_exec.call(self)
506 proc_name 'master (old)'
509 # forcibly terminate all workers that haven't checked in in timeout
510 # seconds. The timeout is implemented using an unlinked File
511 # shared between the parent process and each worker. The worker
512 # runs File#chmod to modify the ctime of the File. If the ctime
513 # is stale for >timeout seconds, then we'll kill the corresponding
515 def murder_lazy_workers
516 WORKERS.dup.each_pair do |wpid, worker|
517 stat = worker.tmp.stat
518 # skip workers that disable fchmod or have never fchmod-ed
519 stat.mode == 0100600 and next
520 (diff = (Time.now - stat.ctime)) <= timeout and next
521 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
522 "(#{diff}s > #{timeout}s), killing"
523 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
527 def spawn_missing_workers
528 (0...worker_processes).each do |worker_nr|
529 WORKERS.values.include?(worker_nr) and next
530 worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
531 before_fork.call(self, worker)
532 WORKERS[fork { worker_loop(worker) }] = worker
536 def maintain_worker_count
537 (off = WORKERS.size - worker_processes) == 0 and return
538 off < 0 and return spawn_missing_workers
539 WORKERS.dup.each_pair { |wpid,w|
540 w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
544 # if we get any error, try to write something back to the client
545 # assuming we haven't closed the socket, but don't get hung up
546 # if the socket is already closed or broken. We'll always ensure
547 # the socket is closed at the end of this function
548 def handle_error(client, e)
550 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
551 Const::ERROR_500_RESPONSE
552 when HttpParserError # try to tell the client they're bad
553 Const::ERROR_400_RESPONSE
555 logger.error "Read error: #{e.inspect}"
556 logger.error e.backtrace.join("\n")
557 Const::ERROR_500_RESPONSE
559 client.write_nonblock(msg)
565 # once a client is accepted, it is processed in its entirety here
566 # in 3 easy steps: read request, call app, write app response
567 def process_client(client)
568 client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
569 response = app.call(env = REQUEST.read(client))
571 if 100 == response.first.to_i
572 client.write(Const::EXPECT_100_RESPONSE)
573 env.delete(Const::HTTP_EXPECT)
574 response = app.call(env)
576 HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
578 handle_error(client, e)
581 # gets rid of stuff the worker has no business keeping track of
582 # to free some resources and drops all sig handlers.
583 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
585 def init_worker_process(worker)
586 QUEUE_SIGS.each { |sig| trap(sig, nil) }
587 trap(:CHLD, 'DEFAULT')
589 proc_name "worker[#{worker.nr}]"
592 WORKERS.values.each { |other| other.tmp.close rescue nil }
594 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
595 worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
596 after_fork.call(self, worker) # can drop perms
597 self.timeout /= 2.0 # halve it for select()
598 build_app! unless preload_app
601 def reopen_worker_logs(worker_nr)
602 logger.info "worker=#{worker_nr} reopening logs..."
603 Unicorn::Util.reopen_logs
604 logger.info "worker=#{worker_nr} done reopening logs"
608 # runs inside each forked worker, this sits around and waits
609 # for connections and doesn't die until the parent dies (or is
610 # given a INT, QUIT, or TERM signal)
611 def worker_loop(worker)
613 init_worker_process(worker)
614 nr = 0 # this becomes negative if we need to reopen logs
615 alive = worker.tmp # tmp is our lifeline to the master process
618 # closing anything we IO.select on will raise EBADF
619 trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
620 trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
621 [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
622 logger.info "worker=#{worker.nr} ready"
626 nr < 0 and reopen_worker_logs(worker.nr)
629 # we're a goner in timeout seconds anyways if alive.chmod
630 # breaks, so don't trap the exception. Using fchmod() since
631 # futimes() is not available in base Ruby and I very strongly
632 # prefer temporary files to be unlinked for security,
633 # performance and reliability reasons, so utime is out. No-op
634 # changes with chmod doesn't update ctime on all filesystems; so
635 # we change our counter each and every time (after process_client
636 # and before IO.select).
637 alive.chmod(m = 0 == m ? 1 : 0)
641 process_client(sock.accept_nonblock)
643 alive.chmod(m = 0 == m ? 1 : 0)
644 rescue Errno::EAGAIN, Errno::ECONNABORTED
649 # make the following bet: if we accepted clients this round,
650 # we're probably reasonably busy, so avoid calling select()
651 # and do a speculative accept_nonblock on ready listeners
652 # before we sleep again in select().
653 redo unless nr == 0 # (nr < 0) => reopen logs
655 ppid == Process.ppid or return
656 alive.chmod(m = 0 == m ? 1 : 0)
658 # timeout used so we can detect parent death:
659 ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
668 logger.error "Unhandled listen loop exception #{e.inspect}."
669 logger.error e.backtrace.join("\n")
674 # delivers a signal to a worker and fails gracefully if the worker
675 # is no longer running.
676 def kill_worker(signal, wpid)
678 Process.kill(signal, wpid)
680 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
684 # delivers a signal to each worker
685 def kill_each_worker(signal)
686 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
689 # unlinks a PID file at given +path+ if it contains the current PID
690 # still potentially racy without locking the directory (which is
691 # non-portable and may interact badly with other programs), but the
692 # window for hitting the race condition is small
693 def unlink_pid_safe(path)
694 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
697 # returns a PID if a given path contains a non-stale PID file,
700 wpid = File.read(path).to_i
701 wpid <= 0 and return nil
703 Process.kill(0, wpid)
706 # don't unlink stale pid files, racy without non-portable locking...
713 logger.info "reloading config_file=#{config.config_file}"
714 config[:listeners].replace(init_listeners)
717 kill_each_worker(:QUIT)
718 Unicorn::Util.reopen_logs
720 build_app! if preload_app
721 logger.info "done reloading config_file=#{config.config_file}"
723 logger.error "error reloading config_file=#{config.config_file}: " \
724 "#{e.class} #{e.message}"
728 # returns an array of string names for the given listener array
729 def listener_names(listeners = LISTENERS)
730 listeners.map { |io| sock_name(io) }
734 if app.respond_to?(:arity) && app.arity == 0
735 # exploit COW in case of preload_app. Also avoids race
736 # conditions in Rainbows! since load/require are not thread-safe
737 Unicorn.constants.each { |x| Unicorn.const_get(x) }
739 if defined?(Gem) && Gem.respond_to?(:refresh)
740 logger.info "Refreshing Gem list"
748 $0 = ([ File.basename(START_CTX[0]), tag
749 ]).concat(START_CTX[:argv]).join(' ')
752 def redirect_io(io, path)
753 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
758 SELF_PIPE.each { |io| io.close rescue nil }
759 SELF_PIPE.replace(IO.pipe)
760 SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }