3 require 'unicorn/socket_helper'
4 require 'unicorn/const'
5 require 'unicorn/http_request'
6 require 'unicorn/http_response'
7 require 'unicorn/configurator'
10 # Unicorn module containing all of the classes (include C extensions) for running
11 # a Unicorn web server. It contains a minimalist HTTP server with just enough
12 # functionality to service web application requests fast as possible.
15 def run(app, options = {})
16 HttpServer.new(app, options).start.join
20 # This is the process manager of Unicorn. This manages worker
21 # processes which in turn handle the I/O and application process.
22 # Listener sockets are started in the master process and shared with
23 # forked worker children.
26 include ::Unicorn::SocketHelper
28 # prevents IO objects in here from being GC-ed
31 # all bound listener sockets
34 # This hash maps PIDs to Workers
37 # See: http://cr.yp.to/docs/selfpipe.html
40 # signal queue used for self-piping
43 # We populate this at startup so we can figure out how to reexecute
44 # and upgrade the currently running instance of Unicorn
46 :argv => ARGV.map { |arg| arg.dup },
47 # don't rely on Dir.pwd here since it's not symlink-aware, and
48 # symlink dirs are the default with Capistrano...
49 :cwd => `/bin/sh -c pwd`.chomp("\n"),
53 Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
55 # worker objects may be compared to just plain numbers
61 # Creates a working server on host:port (strange things happen if
62 # port isn't a Number). Use HttpServer::run to start the server and
63 # HttpServer.run.join to join the thread that's processing
64 # incoming requests on the socket.
65 def initialize(app, options = {})
68 @init_listeners = options[:listeners] ? options[:listeners].dup : []
69 @config = Configurator.new(options.merge(:use_defaults => true))
71 @config.commit!(self, :skip => [:listeners, :pid])
72 @request = HttpRequest.new(@logger)
75 # Runs the thing. Returns self so you can run join on it
77 BasicSocket.do_not_reverse_lookup = true
79 # inherit sockets from parents, they need to be plain Socket objects
80 # before they become UNIXServer or TCPServer
81 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
82 io = Socket.for_fd(fd.to_i)
83 set_server_sockopt(io, @listener_opts[sock_name(io)])
85 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
89 config_listeners = @config[:listeners].dup
90 LISTENERS.replace(inherited)
92 # we start out with generic Socket objects that get cast to either
93 # TCPServer or UNIXServer objects; but since the Socket objects
94 # share the same OS-level file descriptor as the higher-level *Server
95 # objects; we need to prevent Socket objects from being garbage-collected
96 config_listeners -= listener_names
97 if config_listeners.empty? && LISTENERS.empty?
98 config_listeners << Unicorn::Const::DEFAULT_LISTEN
100 config_listeners.each { |addr| listen(addr) }
101 raise ArgumentError, "no listeners" if LISTENERS.empty?
102 self.pid = @config[:pid]
103 build_app! if @preload_app
104 maintain_worker_count
108 # replaces current listener set with +listeners+. This will
109 # close the socket if it will not exist in the new listener set
110 def listeners=(listeners)
111 cur_names, dead_names = [], []
112 listener_names.each do |name|
114 # mark unlinked sockets as dead so we can rebind them
115 (File.socket?(name) ? cur_names : dead_names) << name
120 set_names = listener_names(listeners)
121 dead_names += cur_names - set_names
124 LISTENERS.delete_if do |io|
125 if dead_names.include?(sock_name(io))
126 IO_PURGATORY.delete_if do |pio|
127 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
129 (io.close rescue nil).nil? # true
131 set_server_sockopt(io, @listener_opts[sock_name(io)])
136 (set_names - cur_names).each { |addr| listen(addr) }
139 def stdout_path=(path); redirect_io($stdout, path); end
140 def stderr_path=(path); redirect_io($stderr, path); end
142 # sets the path for the PID file of the master process
145 if x = valid_pid?(path)
146 return path if @pid && path == @pid && x == $$
147 raise ArgumentError, "Already running on PID:#{x} " \
148 "(or pid=#{path} is stale)"
151 unlink_pid_safe(@pid) if @pid
152 File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
156 # add a given address to the +listeners+ set, idempotently
157 # Allows workers to add a private, per-process listener via the
158 # @after_fork hook. Very useful for debugging and testing.
159 def listen(address, opt = {}.merge(@listener_opts[address] || {}))
160 return if String === address && listener_names.include?(address)
162 if io = bind_listen(address, opt)
163 unless TCPServer === io || UNIXServer === io
167 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
170 logger.error "adding listener failed addr=#{address} (in use)"
171 raise Errno::EADDRINUSE, address
175 # monitors children and receives signals forever
176 # (or until a termination signal is sent). This handles signals
177 # one-at-a-time time and we'll happily drop signals in case somebody
178 # is signalling us too often.
180 # this pipe is used to wake us up from select(2) in #join when signals
181 # are trapped. See trap_deferred
185 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
186 trap(:CHLD) { |sig_nr| awaken_master }
188 logger.info "master process ready" # test_exec.rb relies on this message
195 maintain_worker_count if respawn
197 when :QUIT # graceful shutdown
199 when :TERM, :INT # immediate shutdown
202 when :USR1 # rotate logs
203 logger.info "master reopening logs..."
204 Unicorn::Util.reopen_logs
205 logger.info "master done reopening logs"
206 kill_each_worker(:USR1)
207 when :USR2 # exec binary, stay alive in case something went wrong
210 if Process.ppid == 1 || Process.getpgrp != $$
212 logger.info "gracefully stopping all workers"
213 kill_each_worker(:QUIT)
215 logger.info "SIGWINCH ignored because we're not daemonized"
218 @worker_processes += 1
220 @worker_processes -= 1 if @worker_processes > 0
223 if @config.config_file
225 redo # immediate reaping since we may have QUIT workers
226 else # exec binary and exit if there's no config file
227 logger.info "config_file not present, reexecuting binary"
236 logger.error "Unhandled master loop exception #{e.inspect}."
237 logger.error e.backtrace.join("\n")
240 stop # gracefully shutdown all workers on our way out
241 logger.info "master complete"
242 unlink_pid_safe(@pid) if @pid
245 # Terminates all workers, but does not exit master process
246 def stop(graceful = true)
247 kill_each_worker(graceful ? :QUIT : :TERM)
254 (timeleft -= step) > 0 and next
255 kill_each_worker(:KILL)
263 # list of signals we care about and trap in master.
264 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
265 :TTIN, :TTOU ].freeze
267 # defer a signal for later processing in #join (master process)
268 def trap_deferred(signal)
269 trap(signal) do |sig_nr|
270 if SIG_QUEUE.size < 5
274 logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
279 # wait for a signal hander to wake us up and then consume the pipe
280 # Wake up every second anyways to run murder_lazy_workers
283 ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
284 ready.first && ready.first.first or return
285 loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
286 rescue Errno::EAGAIN, Errno::EINTR
292 SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
293 rescue Errno::EAGAIN, Errno::EINTR
294 # pipe is full, master should wake up anyways
299 # reaps all unreaped workers
303 pid, status = Process.waitpid2(-1, Process::WNOHANG)
305 if @reexec_pid == pid
306 logger.error "reaped #{status.inspect} exec()-ed"
308 self.pid = @pid.chomp('.oldbin') if @pid
311 worker = WORKERS.delete(pid)
312 worker.tempfile.close rescue nil
313 logger.info "reaped #{status.inspect} " \
314 "worker=#{worker.nr rescue 'unknown'}"
321 # reexecutes the START_CTX with a new binary
325 Process.kill(0, @reexec_pid)
326 logger.error "reexec-ed child already running PID:#{@reexec_pid}"
334 old_pid = "#{@pid}.oldbin"
337 self.pid = old_pid # clear the path for a new pid file
339 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
340 "existing pid=#{old_pid}, refusing rexec"
343 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
348 @reexec_pid = fork do
349 listener_fds = LISTENERS.map { |sock| sock.fileno }
350 ENV['UNICORN_FD'] = listener_fds.join(',')
351 Dir.chdir(START_CTX[:cwd])
352 cmd = [ START_CTX[:zero] ] + START_CTX[:argv]
354 # avoid leaking FDs we don't know about, but let before_exec
355 # unset FD_CLOEXEC, if anything else in the app eventually
356 # relies on FD inheritence.
357 (3..1024).each do |io|
358 next if listener_fds.include?(io)
359 io = IO.for_fd(io) rescue nil
362 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
364 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
365 @before_exec.call(self)
368 proc_name 'master (old)'
371 # forcibly terminate all workers that haven't checked in in @timeout
372 # seconds. The timeout is implemented using an unlinked tempfile
373 # shared between the parent process and each worker. The worker
374 # runs File#chmod to modify the ctime of the tempfile. If the ctime
375 # is stale for >@timeout seconds, then we'll kill the corresponding
377 def murder_lazy_workers
378 WORKERS.each_pair do |pid, worker|
379 Time.now - worker.tempfile.ctime <= @timeout and next
380 logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
381 kill_worker(:KILL, pid) # take no prisoners for @timeout violations
382 worker.tempfile.close rescue nil
386 def spawn_missing_workers
387 (0...@worker_processes).each do |worker_nr|
388 WORKERS.values.include?(worker_nr) and next
390 Dir.chdir(START_CTX[:cwd])
391 rescue Errno::ENOENT => err
392 logger.fatal "#{err.inspect} (#{START_CTX[:cwd]})"
393 SIG_QUEUE << :QUIT # forcibly emulate SIGQUIT
396 tempfile = Tempfile.new(nil) # as short as possible to save dir space
397 tempfile.unlink # don't allow other processes to find or see it
398 worker = Worker.new(worker_nr, tempfile)
399 @before_fork.call(self, worker)
400 pid = fork { worker_loop(worker) }
401 WORKERS[pid] = worker
405 def maintain_worker_count
406 (off = WORKERS.size - @worker_processes) == 0 and return
407 off < 0 and return spawn_missing_workers
408 WORKERS.each_pair { |pid,w|
409 w.nr >= @worker_processes and kill_worker(:QUIT, pid) rescue nil
413 # once a client is accepted, it is processed in its entirety here
414 # in 3 easy steps: read request, call app, write app response
415 def process_client(client)
416 # one syscall less than "client.nonblock = false":
417 client.fcntl(Fcntl::F_SETFL, File::RDWR)
418 HttpResponse.write(client, @app.call(@request.read(client)))
419 # if we get any error, try to write something back to the client
420 # assuming we haven't closed the socket, but don't get hung up
421 # if the socket is already closed or broken. We'll always ensure
422 # the socket is closed at the end of this function
423 rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
424 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
425 rescue HttpParserError # try to tell the client they're bad
426 client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
428 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
429 logger.error "Read error: #{e.inspect}"
430 logger.error e.backtrace.join("\n")
433 client.closed? or client.close
435 logger.error "Client error: #{e.inspect}"
436 logger.error e.backtrace.join("\n")
441 # gets rid of stuff the worker has no business keeping track of
442 # to free some resources and drops all sig handlers.
443 # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
445 def init_worker_process(worker)
446 QUEUE_SIGS.each { |sig| trap(sig, 'IGNORE') }
447 trap(:CHLD, 'DEFAULT')
449 proc_name "worker[#{worker.nr}]"
452 WORKERS.values.each { |other| other.tempfile.close! rescue nil }
454 LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
455 worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
456 @after_fork.call(self, worker) # can drop perms
457 @timeout /= 2.0 # halve it for select()
458 build_app! unless @config[:preload_app]
461 def reopen_worker_logs(worker_nr)
462 @logger.info "worker=#{worker_nr} reopening logs..."
463 Unicorn::Util.reopen_logs
464 @logger.info "worker=#{worker_nr} done reopening logs"
468 # runs inside each forked worker, this sits around and waits
469 # for connections and doesn't die until the parent dies (or is
470 # given a INT, QUIT, or TERM signal)
471 def worker_loop(worker)
472 master_pid = Process.ppid # slightly racy, but less memory usage
473 init_worker_process(worker)
474 nr = 0 # this becomes negative if we need to reopen logs
475 alive = worker.tempfile # tempfile is our lifeline to the master process
479 # closing anything we IO.select on will raise EBADF
480 trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
481 trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
482 [:TERM, :INT].each { |sig| trap(sig) { exit(0) } } # instant shutdown
483 @logger.info "worker=#{worker.nr} ready"
486 reopen_worker_logs(worker.nr) if nr < 0
487 # we're a goner in @timeout seconds anyways if alive.chmod
488 # breaks, so don't trap the exception. Using fchmod() since
489 # futimes() is not available in base Ruby and I very strongly
490 # prefer temporary files to be unlinked for security,
491 # performance and reliability reasons, so utime is out. No-op
492 # changes with chmod doesn't update ctime on all filesystems; so
493 # we change our counter each and every time (after process_client
494 # and before IO.select).
505 process_client(client)
506 rescue Errno::ECONNABORTED
507 # client closed the socket even before accept
508 client.close rescue nil
510 alive.chmod(nr += 1) if client
516 # make the following bet: if we accepted clients this round,
517 # we're probably reasonably busy, so avoid calling select()
518 # and do a speculative accept_nonblock on every listener
519 # before we sleep again in select().
520 if nr != 0 # (nr < 0) => reopen logs
523 master_pid == Process.ppid or exit(0)
526 # timeout used so we can detect parent death:
527 ret = IO.select(LISTENERS, nil, SELF_PIPE, @timeout) or next
531 rescue Errno::EBADF => e
532 nr < 0 or exit(alive ? 1 : 0)
535 rescue SignalException, SystemExit => e
539 logger.error "Unhandled listen loop exception #{e.inspect}."
540 logger.error e.backtrace.join("\n")
546 # delivers a signal to a worker and fails gracefully if the worker
547 # is no longer running.
548 def kill_worker(signal, pid)
550 Process.kill(signal, pid)
552 worker = WORKERS.delete(pid) and worker.tempfile.close rescue nil
556 # delivers a signal to each worker
557 def kill_each_worker(signal)
558 WORKERS.keys.each { |pid| kill_worker(signal, pid) }
561 # unlinks a PID file at given +path+ if it contains the current PID
562 # useful as an at_exit handler.
563 def unlink_pid_safe(path)
564 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
567 # returns a PID if a given path contains a non-stale PID file,
570 if File.exist?(path) && (pid = File.read(path).to_i) > 1
582 logger.info "reloading config_file=#{@config.config_file}"
583 @config[:listeners].replace(@init_listeners)
585 @config.commit!(self)
586 kill_each_worker(:QUIT)
587 logger.info "done reloading config_file=#{@config.config_file}"
589 logger.error "error reloading config_file=#{@config.config_file}: " \
590 "#{e.class} #{e.message}"
594 # returns an array of string names for the given listener array
595 def listener_names(listeners = LISTENERS)
596 listeners.map { |io| sock_name(io) }
600 @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0
604 $0 = ([ File.basename(START_CTX[:zero]), tag ] +
605 START_CTX[:argv]).join(' ')
608 def redirect_io(io, path)
609 File.open(path, 'a') { |fp| io.reopen(fp) } if path
614 SELF_PIPE.each { |io| io.close rescue nil }
615 SELF_PIPE.replace(IO.pipe)
616 SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }