3 require 'unicorn/socket'
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
29 :argv => ARGV.map { |arg| arg.dup },
30 # don't rely on Dir.pwd here since it's not symlink-aware, and
31 # symlink dirs are the default with Capistrano...
32 :cwd => `/bin/sh -c pwd`.chomp("\n"),
34 :environ => {}.merge!(ENV),
38 Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
40 # worker objects may be compared to just plain numbers
46 # Creates a working server on host:port (strange things happen if
47 # port isn't a Number). Use HttpServer::run to start the server and
48 # HttpServer.workers.join to join the thread that's processing
49 # incoming requests on the socket.
50 def initialize(app, options = {})
51 start_ctx = options.delete(:start_ctx)
52 @start_ctx = DEFAULT_START_CTX.dup
53 @start_ctx.merge!(start_ctx) if start_ctx
58 @io_purgatory = [] # prevents IO objects in here from being GC-ed
59 @request = @rd_sig = @wr_sig = nil
61 @config = Configurator.new(options.merge(:use_defaults => true))
62 @config.commit!(self, :skip => [:listeners, :pid])
66 # Runs the thing. Returns self so you can run join on it
68 BasicSocket.do_not_reverse_lookup = true
70 # inherit sockets from parents, they need to be plain Socket objects
71 # before they become UNIXServer or TCPServer
72 inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
73 io = Socket.for_fd(fd.to_i)
74 set_server_sockopt(io)
76 logger.info "inherited: #{io} fd=#{fd} addr=#{sock_name(io)}"
80 config_listeners = @config[:listeners].dup
81 @listeners.replace(inherited)
83 # we start out with generic Socket objects that get cast to either
84 # TCPServer or UNIXServer objects; but since the Socket objects
85 # share the same OS-level file descriptor as the higher-level *Server
86 # objects; we need to prevent Socket objects from being garbage-collected
87 config_listeners -= listener_names
88 config_listeners.each { |addr| listen(addr) }
89 raise ArgumentError, "no listeners" if @listeners.empty?
90 self.pid = @config[:pid]
91 build_app! if @preload_app
92 $stderr.reopen(File.open(@stderr_path, "a")) if @stderr_path
93 $stdout.reopen(File.open(@stdout_path, "a")) if @stdout_path
94 $stderr.sync = $stdout.sync = true
99 # replaces current listener set with +listeners+. This will
100 # close the socket if it will not exist in the new listener set
101 def listeners=(listeners)
102 cur_names = listener_names
103 set_names = listener_names(listeners)
104 dead_names = cur_names - set_names
106 @listeners.delete_if do |io|
107 if dead_names.include?(sock_name(io))
108 @io_purgatory.delete_if { |pio| pio.fileno == io.fileno }
115 (set_names - cur_names).each { |addr| listen(addr) }
118 # sets the path for the PID file of the master process
121 if x = valid_pid?(path)
122 return path if @pid && path == @pid && x == $$
123 raise ArgumentError, "Already running on PID:#{x} " \
124 "(or pid=#{path} is stale)"
126 File.open(path, 'wb') { |fp| fp.syswrite("#{$$}\n") }
128 unlink_pid_safe(@pid) if @pid && @pid != path
132 # add a given address to the +listeners+ set, idempotently
133 # Allows workers to add a private, per-process listener via the
134 # @after_fork hook. Very useful for debugging and testing.
136 return if String === address && listener_names.include?(address)
138 if io = bind_listen(address, { :backlog => @backlog })
139 if Socket == io.class
143 logger.info "#{io} listening on PID:#{$$} " \
144 "fd=#{io.fileno} addr=#{sock_name(io)}"
147 logger.error "adding listener failed addr=#{address} (in use)"
148 raise Errno::EADDRINUSE, address
152 # monitors children and receives signals forever
153 # (or until a termination signal is sent). This handles signals
154 # one-at-a-time time and we'll happily drop signals in case somebody
155 # is signalling us too often.
157 # this pipe is used to wake us up from select(2) in #join when signals
158 # are trapped. See trap_deferred
159 @rd_sig, @wr_sig = IO.pipe unless (@rd_sig && @wr_sig)
160 @rd_sig.nonblock = @wr_sig.nonblock = true
164 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
165 trap('CHLD') { |sig_nr| awaken_master }
166 $0 = "unicorn master"
167 logger.info "master process ready" # test_exec.rb relies on this message
171 case (mode = @sig_queue.shift)
174 spawn_missing_workers if respawn
176 when 'QUIT' # graceful shutdown
178 when 'TERM', 'INT' # immediate shutdown
181 when 'USR1' # rotate logs
182 logger.info "master rotating logs..."
183 Unicorn::Util.reopen_logs
184 logger.info "master done rotating logs"
185 kill_each_worker('USR1')
186 when 'USR2' # exec binary, stay alive in case something went wrong
189 if Process.ppid == 1 || Process.getpgrp != $$
191 logger.info "gracefully stopping all workers"
192 kill_each_worker('QUIT')
194 logger.info "SIGWINCH ignored because we're not daemonized"
198 if @config.config_file
200 redo # immediate reaping since we may have QUIT workers
201 else # exec binary and exit if there's no config file
202 logger.info "config_file not present, reexecuting binary"
207 logger.error "master process in unknown mode: #{mode}"
213 logger.error "Unhandled master loop exception #{e.inspect}."
214 logger.error e.backtrace.join("\n")
217 stop # gracefully shutdown all workers on our way out
218 logger.info "master PID:#{$$} join complete"
219 unlink_pid_safe(@pid) if @pid
222 # Terminates all workers, but does not exit master process
223 def stop(graceful = true)
224 kill_each_worker(graceful ? 'QUIT' : 'TERM')
228 until @workers.empty?
231 (timeleft -= step) > 0 and next
232 kill_each_worker('KILL')
240 # list of signals we care about and trap in master.
242 %w(WINCH QUIT INT TERM USR1 USR2 HUP).map { |x| x.freeze }.freeze
244 # defer a signal for later processing in #join (master process)
245 def trap_deferred(signal)
246 trap(signal) do |sig_nr|
247 if @sig_queue.size < 5
251 logger.error "ignoring SIG#{signal}, queue=#{@sig_queue.inspect}"
256 # wait for a signal hander to wake us up and then consume the pipe
257 # Wake up every second anyways to run murder_lazy_workers
260 ready = IO.select([@rd_sig], nil, nil, 1)
261 ready && ready[0] && ready[0][0] or return
262 loop { @rd_sig.sysread(Const::CHUNK_SIZE) }
263 rescue Errno::EAGAIN, Errno::EINTR
269 @wr_sig.syswrite('.') # wakeup master process from IO.select
270 rescue Errno::EAGAIN # pipe is full, master should wake up anyways
276 # reaps all unreaped workers
280 pid, status = Process.waitpid2(-1, Process::WNOHANG)
282 if @reexec_pid == pid
283 logger.error "reaped #{status.inspect} exec()-ed"
285 self.pid = @pid.chomp('.oldbin') if @pid
286 $0 = "unicorn master"
288 worker = @workers.delete(pid)
289 worker.tempfile.close rescue nil
290 logger.info "reaped #{status.inspect} " \
291 "worker=#{worker.nr rescue 'unknown'}"
298 # reexecutes the @start_ctx with a new binary
302 Process.kill(0, @reexec_pid)
303 logger.error "reexec-ed child already running PID:#{@reexec_pid}"
311 old_pid = "#{@pid}.oldbin"
314 self.pid = old_pid # clear the path for a new pid file
316 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
317 "existing pid=#{old_pid}, refusing rexec"
320 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
325 @reexec_pid = fork do
326 @rd_sig.close if @rd_sig
327 @wr_sig.close if @wr_sig
328 @workers.values.each { |other| other.tempfile.close rescue nil }
330 ENV.replace(@start_ctx[:environ])
331 ENV['UNICORN_FD'] = @listeners.map { |sock| sock.fileno }.join(',')
332 File.umask(@start_ctx[:umask])
333 Dir.chdir(@start_ctx[:cwd])
334 cmd = [ @start_ctx[:zero] ] + @start_ctx[:argv]
335 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
336 @before_exec.call(self) if @before_exec
339 $0 = "unicorn master (old)"
342 # forcibly terminate all workers that haven't checked in in @timeout
343 # seconds. The timeout is implemented using an unlinked tempfile
344 # shared between the parent process and each worker. The worker
345 # runs File#chmod to modify the ctime of the tempfile. If the ctime
346 # is stale for >@timeout seconds, then we'll kill the corresponding
348 def murder_lazy_workers
350 @workers.each_pair do |pid, worker|
351 (now - worker.tempfile.ctime) <= @timeout and next
352 logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
353 kill_worker('KILL', pid) # take no prisoners for @timeout violations
354 worker.tempfile.close rescue nil
358 def spawn_missing_workers
359 return if @workers.size == @worker_processes
360 (0...@worker_processes).each do |worker_nr|
361 @workers.values.include?(worker_nr) and next
363 Dir.chdir(@start_ctx[:cwd])
364 rescue Errno::ENOENT => err
365 logger.fatal "#{err.inspect} (#{@start_ctx[:cwd]})"
366 @sig_queue << 'QUIT' # forcibly emulate SIGQUIT
369 tempfile = Tempfile.new('') # as short as possible to save dir space
370 tempfile.unlink # don't allow other processes to find or see it
372 worker = Worker.new(worker_nr, tempfile)
373 @before_fork.call(self, worker.nr)
374 pid = fork { worker_loop(worker) }
375 @workers[pid] = worker
379 # once a client is accepted, it is processed in its entirety here
380 # in 3 easy steps: read request, call app, write app response
381 def process_client(client)
382 env = @request.read(client) or return
383 app_response = @app.call(env)
384 HttpResponse.write(client, app_response)
385 rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
386 client.closed? or client.close rescue nil
388 logger.error "Read error: #{e.inspect}"
389 logger.error e.backtrace.join("\n")
392 client.closed? or client.close
394 logger.error "Client error: #{e.inspect}"
395 logger.error e.backtrace.join("\n")
400 # gets rid of stuff the worker has no business keeping track of
401 # to free some resources and drops all sig handlers.
402 # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
404 def init_worker_process(worker)
405 build_app! unless @preload_app
407 QUEUE_SIGS.each { |sig| trap(sig, 'IGNORE') }
408 trap('CHLD', 'DEFAULT')
410 $0 = "unicorn worker[#{worker.nr}]"
411 @rd_sig.close if @rd_sig
412 @wr_sig.close if @wr_sig
413 @workers.values.each { |other| other.tempfile.close rescue nil }
416 @start_ctx = @workers = @rd_sig = @wr_sig = nil
417 @listeners.each { |sock| set_cloexec(sock) }
418 ENV.delete('UNICORN_FD')
419 @after_fork.call(self, worker.nr) if @after_fork
420 @request = HttpRequest.new(logger)
423 # runs inside each forked worker, this sits around and waits
424 # for connections and doesn't die until the parent dies (or is
425 # given a INT, QUIT, or TERM signal)
426 def worker_loop(worker)
427 init_worker_process(worker)
429 tempfile = worker.tempfile
433 %w(TERM INT).each { |sig| trap(sig) { exit(0) } } # instant shutdown
436 @listeners.each { |sock| sock.close rescue nil } # break IO.select
438 reopen_logs, (rd, wr) = false, IO.pipe
439 trap(:USR1) { reopen_logs = true; rd.close rescue nil }
440 @logger.info "worker=#{worker.nr} ready"
442 while alive && @master_pid == Process.ppid
445 @logger.info "worker=#{worker.nr} rotating logs..."
446 Unicorn::Util.reopen_logs
447 @logger.info "worker=#{worker.nr} done rotating logs"
451 # we're a goner in @timeout seconds anyways if tempfile.chmod
452 # breaks, so don't trap the exception. Using fchmod() since
453 # futimes() is not available in base Ruby and I very strongly
454 # prefer temporary files to be unlinked for security,
455 # performance and reliability reasons, so utime is out. No-op
456 # changes with chmod doesn't update ctime on all filesystems; so
457 # we increment our counter each and every time.
458 tempfile.chmod(nr += 1)
469 accepted = client.sync = true
470 client.nonblock = false
471 set_client_sockopt(client) if TCPSocket === client
472 process_client(client)
473 rescue Errno::ECONNABORTED
474 # client closed the socket even before accept
475 if client && !client.closed?
476 client.close rescue nil
479 tempfile.chmod(nr += 1)
484 # make the following bet: if we accepted clients this round,
485 # we're probably reasonably busy, so avoid calling select(2)
486 # and try to do a blind non-blocking accept(2) on everything
487 # before we sleep again in select
488 if accepted || reopen_logs
492 tempfile.chmod(nr += 1)
493 # timeout used so we can detect parent death:
494 ret = IO.select(@listeners, nil, [rd], @timeout/2.0) or next
498 rescue Errno::EBADF => e
499 reopen_logs or exit(alive ? 1 : 0)
502 rescue SystemExit => e
506 logger.error "Unhandled listen loop exception #{e.inspect}."
507 logger.error e.backtrace.join("\n")
513 # delivers a signal to a worker and fails gracefully if the worker
514 # is no longer running.
515 def kill_worker(signal, pid)
517 Process.kill(signal, pid)
519 worker = @workers.delete(pid) and worker.tempfile.close rescue nil
523 # delivers a signal to each worker
524 def kill_each_worker(signal)
525 @workers.keys.each { |pid| kill_worker(signal, pid) }
528 # unlinks a PID file at given +path+ if it contains the current PID
529 # useful as an at_exit handler.
530 def unlink_pid_safe(path)
531 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
534 # returns a PID if a given path contains a non-stale PID file,
537 if File.exist?(path) && (pid = File.read(path).to_i) > 1
549 logger.info "reloading config_file=#{@config.config_file}"
551 @config.commit!(self)
552 kill_each_worker('QUIT')
553 logger.info "done reloading config_file=#{@config.config_file}"
555 logger.error "error reloading config_file=#{@config.config_file}: " \
556 "#{e.class} #{e.message}"
560 # returns an array of string names for the given listener array
561 def listener_names(listeners = @listeners)
562 listeners.map { |io| sock_name(io) }
566 @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0