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.
7 class Unicorn::HttpServer
8 attr_accessor :app, :request, :timeout, :worker_processes,
9 :before_fork, :after_fork, :before_exec,
10 :listener_opts, :preload_app,
11 :reexec_pid, :orig_app, :init_listeners,
12 :master_pid, :config, :ready_pipe, :user
13 attr_reader :pid, :logger
16 include Unicorn::SocketHelper
17 include Unicorn::HttpResponse
19 # backwards compatibility with 1.x
20 Worker = Unicorn::Worker
22 # prevents IO objects in here from being GC-ed
25 # all bound listener sockets
28 # This hash maps PIDs to Workers
31 # We use SELF_PIPE differently in the master and worker processes:
33 # * The master process never closes or reinitializes this once
34 # initialized. Signal handlers in the master process will write to
35 # it to wake up the master from IO.select in exactly the same manner
36 # djb describes in http://cr.yp.to/docs/selfpipe.html
38 # * The workers immediately close the pipe they inherit from the
39 # master and replace it with a new pipe after forking. This new
40 # pipe is also used to wakeup from IO.select from inside (worker)
41 # signal handlers. However, workers *close* the pipe descriptors in
42 # the signal handlers to raise EBADF in IO.select instead of writing
43 # like we do in the master. We cannot easily use the reader set for
44 # IO.select because LISTENERS is already that set, and it's extra
45 # work (and cycles) to distinguish the pipe FD from the reader set
46 # once IO.select returns. So we're lazy and just close the pipe when
47 # a (rare) signal arrives in the worker and reinitialize the pipe later.
50 # signal queue used for self-piping
53 # list of signals we care about and trap in master.
54 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
57 # We populate this at startup so we can figure out how to reexecute
58 # and upgrade the currently running instance of Unicorn
59 # This Hash is considered a stable interface and changing its contents
60 # will allow you to switch between different installations of Unicorn
61 # or even different installations of the same applications without
62 # downtime. Keys of this constant Hash are described as follows:
64 # * 0 - the path to the unicorn/unicorn_rails executable
65 # * :argv - a deep copy of the ARGV array the executable originally saw
66 # * :cwd - the working directory of the application, this is where
67 # you originally started Unicorn.
69 # To change your unicorn executable to a different path without downtime,
70 # you can set the following in your Unicorn config file, HUP and then
71 # continue with the traditional USR2 + QUIT upgrade steps:
73 # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
75 :argv => ARGV.map { |arg| arg.dup },
78 # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
80 START_CTX[:cwd] = begin
81 a = File.stat(pwd = ENV['PWD'])
82 b = File.stat(Dir.pwd)
83 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 self.ready_pipe = options.delete(:ready_pipe)
98 self.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
119 BasicSocket.do_not_reverse_lookup = true
121 # inherit sockets from parents, they need to be plain Socket objects
122 # before they become Kgio::UNIXServer or Kgio::TCPServer
123 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
124 io = Socket.for_fd(fd.to_i)
125 set_server_sockopt(io, listener_opts[sock_name(io)])
127 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
131 config_listeners = config[:listeners].dup
132 LISTENERS.replace(inherited)
134 # we start out with generic Socket objects that get cast to either
135 # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
136 # objects share the same OS-level file descriptor as the higher-level
137 # *Server objects; we need to prevent Socket objects from being
139 config_listeners -= listener_names
140 if config_listeners.empty? && LISTENERS.empty?
141 config_listeners << Unicorn::Const::DEFAULT_LISTEN
142 init_listeners << Unicorn::Const::DEFAULT_LISTEN
143 START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
145 config_listeners.each { |addr| listen(addr) }
146 raise ArgumentError, "no listeners" if LISTENERS.empty?
148 # this pipe is used to wake us up from select(2) in #join when signals
149 # are trapped. See trap_deferred.
152 # setup signal handlers before writing pid file in case people get
153 # trigger happy and send signals as soon as the pid file exists.
154 # Note that signals don't actually get handled until the #join method
155 QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
156 trap(:CHLD) { awaken_master }
157 self.pid = config[:pid]
160 build_app! if preload_app
161 maintain_worker_count
165 # replaces current listener set with +listeners+. This will
166 # close the socket if it will not exist in the new listener set
167 def listeners=(listeners)
168 cur_names, dead_names = [], []
169 listener_names.each do |name|
171 # mark unlinked sockets as dead so we can rebind them
172 (File.socket?(name) ? cur_names : dead_names) << name
177 set_names = listener_names(listeners)
178 dead_names.concat(cur_names - set_names).uniq!
180 LISTENERS.delete_if do |io|
181 if dead_names.include?(sock_name(io))
182 IO_PURGATORY.delete_if do |pio|
183 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
185 (io.close rescue nil).nil? # true
187 set_server_sockopt(io, listener_opts[sock_name(io)])
192 (set_names - cur_names).each { |addr| listen(addr) }
195 def stdout_path=(path); redirect_io($stdout, path); end
196 def stderr_path=(path); redirect_io($stderr, path); end
199 Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
202 # sets the path for the PID file of the master process
205 if x = valid_pid?(path)
206 return path if pid && path == pid && x == $$
207 if x == reexec_pid && pid =~ /\.oldbin\z/
208 logger.warn("will not set pid=#{path} while reexec-ed "\
209 "child is running PID:#{x}")
212 raise ArgumentError, "Already running on PID:#{x} " \
213 "(or pid=#{path} is stale)"
216 unlink_pid_safe(pid) if pid
220 tmp = "#{File.dirname(path)}/#{rand}.#$$"
221 File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
226 File.rename(fp.path, path)
232 # add a given address to the +listeners+ set, idempotently
233 # Allows workers to add a private, per-process listener via the
234 # after_fork hook. Very useful for debugging and testing.
235 # +:tries+ may be specified as an option for the number of times
236 # to retry, and +:delay+ may be specified as the time in seconds
237 # to delay between retries.
238 # A negative value for +:tries+ indicates the listen will be
239 # retried indefinitely, this is useful when workers belonging to
240 # different masters are spawned during a transparent upgrade.
241 def listen(address, opt = {}.merge(listener_opts[address] || {}))
242 address = config.expand_addr(address)
243 return if String === address && listener_names.include?(address)
245 delay = opt[:delay] || 0.5
246 tries = opt[:tries] || 5
248 io = bind_listen(address, opt)
249 unless Kgio::TCPServer === io || Kgio::UNIXServer === io
253 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
256 rescue Errno::EADDRINUSE => err
257 logger.error "adding listener failed addr=#{address} (in use)"
258 raise err if tries == 0
260 logger.error "retrying in #{delay} seconds " \
261 "(#{tries < 0 ? 'infinite' : tries} tries left)"
265 logger.fatal "error adding listener addr=#{address}"
270 # monitors children and receives signals forever
271 # (or until a termination signal is sent). This handles signals
272 # one-at-a-time time and we'll happily drop signals in case somebody
273 # is signalling us too often.
276 last_check = Time.now
279 logger.info "master process ready" # test_exec.rb relies on this message
281 ready_pipe.syswrite($$.to_s)
282 ready_pipe.close rescue nil
283 self.ready_pipe = nil
289 # avoid murdering workers after our master process (or the
290 # machine) comes out of suspend/hibernation
291 if (last_check + @timeout) >= (last_check = Time.now)
292 sleep_time = murder_lazy_workers
294 # wait for workers to wakeup on suspend
295 sleep_time = @timeout/2.0 + 1
297 maintain_worker_count if respawn
298 master_sleep(sleep_time)
299 when :QUIT # graceful shutdown
301 when :TERM, :INT # immediate shutdown
304 when :USR1 # rotate logs
305 logger.info "master reopening logs..."
306 Unicorn::Util.reopen_logs
307 logger.info "master done reopening logs"
308 kill_each_worker(:USR1)
309 when :USR2 # exec binary, stay alive in case something went wrong
312 if Process.ppid == 1 || Process.getpgrp != $$
314 logger.info "gracefully stopping all workers"
315 kill_each_worker(:QUIT)
316 self.worker_processes = 0
318 logger.info "SIGWINCH ignored because we're not daemonized"
322 self.worker_processes += 1
324 self.worker_processes -= 1 if self.worker_processes > 0
327 if config.config_file
329 else # exec binary and exit if there's no config file
330 logger.info "config_file not present, reexecuting binary"
336 logger.error "Unhandled master loop exception #{e.inspect}."
337 logger.error e.backtrace.join("\n")
339 stop # gracefully shutdown all workers on our way out
340 logger.info "master complete"
341 unlink_pid_safe(pid) if pid
344 # Terminates all workers, but does not exit master process
345 def stop(graceful = true)
347 limit = Time.now + timeout
348 until WORKERS.empty? || Time.now > limit
349 kill_each_worker(graceful ? :QUIT : :TERM)
353 kill_each_worker(:KILL)
357 Unicorn::HttpRequest.input_class.method_defined?(:rewind)
360 def rewindable_input=(bool)
361 Unicorn::HttpRequest.input_class = bool ?
362 Unicorn::TeeInput : Unicorn::StreamInput
365 def client_body_buffer_size
366 Unicorn::TeeInput.client_body_buffer_size
369 def client_body_buffer_size=(bytes)
370 Unicorn::TeeInput.client_body_buffer_size = bytes
373 def trust_x_forwarded
374 Unicorn::HttpParser.trust_x_forwarded?
377 def trust_x_forwarded=(bool)
378 Unicorn::HttpParser.trust_x_forwarded = bool
383 # wait for a signal hander to wake us up and then consume the pipe
384 def master_sleep(sec)
385 IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
386 SELF_PIPE[0].kgio_tryread(11)
390 SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
393 # reaps all unreaped workers
396 wpid, status = Process.waitpid2(-1, Process::WNOHANG)
398 if reexec_pid == wpid
399 logger.error "reaped #{status.inspect} exec()-ed"
401 self.pid = pid.chomp('.oldbin') if pid
404 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
405 m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
406 status.success? ? logger.info(m) : logger.error(m)
413 # reexecutes the START_CTX with a new binary
417 Process.kill(0, reexec_pid)
418 logger.error "reexec-ed child already running PID:#{reexec_pid}"
426 old_pid = "#{pid}.oldbin"
429 self.pid = old_pid # clear the path for a new pid file
431 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
432 "existing pid=#{old_pid}, refusing rexec"
435 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
440 self.reexec_pid = fork do
441 listener_fds = LISTENERS.map { |sock| sock.fileno }
442 ENV['UNICORN_FD'] = listener_fds.join(',')
443 Dir.chdir(START_CTX[:cwd])
444 cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
446 # avoid leaking FDs we don't know about, but let before_exec
447 # unset FD_CLOEXEC, if anything else in the app eventually
448 # relies on FD inheritence.
449 (3..1024).each do |io|
450 next if listener_fds.include?(io)
451 io = IO.for_fd(io) rescue next
453 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
455 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
456 before_exec.call(self)
459 proc_name 'master (old)'
462 # forcibly terminate all workers that haven't checked in in timeout
463 # seconds. The timeout is implemented using an unlinked File
464 # shared between the parent process and each worker. The worker
465 # runs File#chmod to modify the ctime of the File. If the ctime
466 # is stale for >timeout seconds, then we'll kill the corresponding
468 def murder_lazy_workers
471 WORKERS.dup.each_pair do |wpid, worker|
472 stat = worker.tmp.stat
473 # skip workers that disable fchmod or have never fchmod-ed
474 stat.mode == 0100600 and next
475 diff = Time.now - stat.ctime
478 next_sleep < tmp and next_sleep = tmp
481 logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
482 "(#{diff}s > #{t}s), killing"
483 kill_worker(:KILL, wpid) # take no prisoners for timeout violations
488 def spawn_missing_workers
489 (0...worker_processes).each do |worker_nr|
490 WORKERS.values.include?(worker_nr) and next
491 worker = Worker.new(worker_nr, Unicorn::TmpIO.new)
492 before_fork.call(self, worker)
494 ready_pipe.close if ready_pipe
495 self.ready_pipe = nil
501 def maintain_worker_count
502 (off = WORKERS.size - worker_processes) == 0 and return
503 off < 0 and return spawn_missing_workers
504 WORKERS.dup.each_pair { |wpid,w|
505 w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
509 # if we get any error, try to write something back to the client
510 # assuming we haven't closed the socket, but don't get hung up
511 # if the socket is already closed or broken. We'll always ensure
512 # the socket is closed at the end of this function
513 def handle_error(client, e)
515 when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
516 Unicorn::Const::ERROR_500_RESPONSE
517 when Unicorn::HttpParserError # try to tell the client they're bad
518 Unicorn::Const::ERROR_400_RESPONSE
520 logger.error "Read error: #{e.inspect}"
521 logger.error e.backtrace.join("\n")
522 Unicorn::Const::ERROR_500_RESPONSE
524 client.kgio_trywrite(msg)
529 # once a client is accepted, it is processed in its entirety here
530 # in 3 easy steps: read request, call app, write app response
531 def process_client(client)
532 status, headers, body = @app.call(env = @request.read(client))
534 if 100 == status.to_i
535 client.write(Unicorn::Const::EXPECT_100_RESPONSE)
536 env.delete(Unicorn::Const::HTTP_EXPECT)
537 status, headers, body = @app.call(env)
539 @request.headers? or headers = nil
540 http_response_write(client, status, headers, body)
541 client.close # flush and uncork socket immediately, no keepalive
543 handle_error(client, e)
546 # gets rid of stuff the worker has no business keeping track of
547 # to free some resources and drops all sig handlers.
548 # traps for USR1, USR2, and HUP may be set in the after_fork Proc
550 def init_worker_process(worker)
551 QUEUE_SIGS.each { |sig| trap(sig, nil) }
552 trap(:CHLD, 'DEFAULT')
554 proc_name "worker[#{worker.nr}]"
557 WORKERS.values.each { |other| other.tmp.close rescue nil }
559 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
560 worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
561 after_fork.call(self, worker) # can drop perms
562 worker.user(*user) if user.kind_of?(Array) && ! worker.switched
563 self.timeout /= 2.0 # halve it for select()
564 build_app! unless preload_app
567 def reopen_worker_logs(worker_nr)
568 logger.info "worker=#{worker_nr} reopening logs..."
569 Unicorn::Util.reopen_logs
570 logger.info "worker=#{worker_nr} done reopening logs"
574 # runs inside each forked worker, this sits around and waits
575 # for connections and doesn't die until the parent dies (or is
576 # given a INT, QUIT, or TERM signal)
577 def worker_loop(worker)
579 init_worker_process(worker)
580 nr = 0 # this becomes negative if we need to reopen logs
581 alive = worker.tmp # tmp is our lifeline to the master process
584 # closing anything we IO.select on will raise EBADF
585 trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
586 trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
587 [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
588 logger.info "worker=#{worker.nr} ready"
592 nr < 0 and reopen_worker_logs(worker.nr)
595 # we're a goner in timeout seconds anyways if alive.chmod
596 # breaks, so don't trap the exception. Using fchmod() since
597 # futimes() is not available in base Ruby and I very strongly
598 # prefer temporary files to be unlinked for security,
599 # performance and reliability reasons, so utime is out. No-op
600 # changes with chmod doesn't update ctime on all filesystems; so
601 # we change our counter each and every time (after process_client
602 # and before IO.select).
603 alive.chmod(m = 0 == m ? 1 : 0)
606 if client = sock.kgio_tryaccept
607 process_client(client)
609 alive.chmod(m = 0 == m ? 1 : 0)
614 # make the following bet: if we accepted clients this round,
615 # we're probably reasonably busy, so avoid calling select()
616 # and do a speculative non-blocking accept() on ready listeners
617 # before we sleep again in select().
618 redo unless nr == 0 # (nr < 0) => reopen logs
620 ppid == Process.ppid or return
621 alive.chmod(m = 0 == m ? 1 : 0)
623 # timeout used so we can detect parent death:
624 ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) and ready = ret[0]
631 logger.error "Unhandled listen loop exception #{e.inspect}."
632 logger.error e.backtrace.join("\n")
637 # delivers a signal to a worker and fails gracefully if the worker
638 # is no longer running.
639 def kill_worker(signal, wpid)
640 Process.kill(signal, wpid)
642 worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
645 # delivers a signal to each worker
646 def kill_each_worker(signal)
647 WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
650 # unlinks a PID file at given +path+ if it contains the current PID
651 # still potentially racy without locking the directory (which is
652 # non-portable and may interact badly with other programs), but the
653 # window for hitting the race condition is small
654 def unlink_pid_safe(path)
655 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
658 # returns a PID if a given path contains a non-stale PID file,
661 wpid = File.read(path).to_i
663 Process.kill(0, wpid)
665 rescue Errno::ESRCH, Errno::ENOENT
666 # don't unlink stale pid files, racy without non-portable locking...
671 logger.info "reloading config_file=#{config.config_file}"
672 config[:listeners].replace(init_listeners)
675 kill_each_worker(:QUIT)
676 Unicorn::Util.reopen_logs
678 build_app! if preload_app
679 logger.info "done reloading config_file=#{config.config_file}"
680 rescue StandardError, LoadError, SyntaxError => e
681 logger.error "error reloading config_file=#{config.config_file}: " \
682 "#{e.class} #{e.message} #{e.backtrace}"
683 self.app = loaded_app
686 # returns an array of string names for the given listener array
687 def listener_names(listeners = LISTENERS)
688 listeners.map { |io| sock_name(io) }
692 if app.respond_to?(:arity) && app.arity == 0
693 if defined?(Gem) && Gem.respond_to?(:refresh)
694 logger.info "Refreshing Gem list"
702 $0 = ([ File.basename(START_CTX[0]), tag
703 ]).concat(START_CTX[:argv]).join(' ')
706 def redirect_io(io, path)
707 File.open(path, 'ab') { |fp| io.reopen(fp) } if path
712 SELF_PIPE.each { |io| io.close rescue nil }
713 SELF_PIPE.replace(Kgio::Pipe.new)
714 SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }