4 require 'unicorn/socket'
5 require 'unicorn/const'
6 require 'unicorn/http_request'
7 require 'unicorn/http_response'
8 require 'unicorn/configurator'
11 # Unicorn module containing all of the classes (include C extensions) for running
12 # a Unicorn web server. It contains a minimalist HTTP server with just enough
13 # functionality to service web application requests fast as possible.
16 def run(app, options = {})
17 HttpServer.new(app, options).start.join
21 # This is the process manager of Unicorn. This manages worker
22 # processes which in turn handle the I/O and application process.
23 # Listener sockets are started in the master process and shared with
24 # forked worker children.
27 include ::Unicorn::SocketHelper
31 :argv => ARGV.map { |arg| arg.dup },
32 # don't rely on Dir.pwd here since it's not symlink-aware, and
33 # symlink dirs are the default with Capistrano...
34 :cwd => `/bin/sh -c pwd`.chomp("\n"),
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
56 @io_purgatory = [] # prevents IO objects in here from being GC-ed
57 @request = @rd_sig = @wr_sig = nil
59 @init_listeners = options[:listeners] ? options[:listeners].dup : []
60 @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, @listener_opts[sock_name(io)])
76 logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
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 if config_listeners.empty? && @listeners.empty?
89 config_listeners << Unicorn::Const::DEFAULT_LISTEN
91 config_listeners.each { |addr| listen(addr) }
92 raise ArgumentError, "no listeners" if @listeners.empty?
93 self.pid = @config[:pid]
94 build_app! if @preload_app
95 File.open(@stderr_path, "a") { |fp| $stderr.reopen(fp) } if @stderr_path
96 File.open(@stdout_path, "a") { |fp| $stdout.reopen(fp) } if @stdout_path
97 $stderr.sync = $stdout.sync = true
102 # replaces current listener set with +listeners+. This will
103 # close the socket if it will not exist in the new listener set
104 def listeners=(listeners)
105 cur_names, dead_names = [], []
106 listener_names.each do |name|
108 # mark unlinked sockets as dead so we can rebind them
109 (File.socket?(name) ? cur_names : dead_names) << name
114 set_names = listener_names(listeners)
115 dead_names += cur_names - set_names
118 @listeners.delete_if do |io|
119 if dead_names.include?(sock_name(io))
120 @io_purgatory.delete_if do |pio|
121 pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
123 (io.close rescue nil).nil? # true
125 set_server_sockopt(io, @listener_opts[sock_name(io)])
130 (set_names - cur_names).each { |addr| listen(addr) }
133 # sets the path for the PID file of the master process
136 if x = valid_pid?(path)
137 return path if @pid && path == @pid && x == $$
138 raise ArgumentError, "Already running on PID:#{x} " \
139 "(or pid=#{path} is stale)"
142 unlink_pid_safe(@pid) if @pid
143 File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
147 # add a given address to the +listeners+ set, idempotently
148 # Allows workers to add a private, per-process listener via the
149 # @after_fork hook. Very useful for debugging and testing.
150 def listen(address, opt = {}.merge(@listener_opts[address] || {}))
151 return if String === address && listener_names.include?(address)
153 if io = bind_listen(address, opt)
154 unless TCPServer === io || UNIXServer === io
158 logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
161 logger.error "adding listener failed addr=#{address} (in use)"
162 raise Errno::EADDRINUSE, address
166 # monitors children and receives signals forever
167 # (or until a termination signal is sent). This handles signals
168 # one-at-a-time time and we'll happily drop signals in case somebody
169 # is signalling us too often.
171 # this pipe is used to wake us up from select(2) in #join when signals
172 # are trapped. See trap_deferred
173 @rd_sig, @wr_sig = IO.pipe unless (@rd_sig && @wr_sig)
177 QUEUE_SIGS.each { |sig| trap_deferred(sig) }
178 trap(:CHLD) { |sig_nr| awaken_master }
180 logger.info "master process ready" # test_exec.rb relies on this message
184 case (mode = SIG_QUEUE.shift)
187 spawn_missing_workers if respawn
189 when :QUIT # graceful shutdown
191 when :TERM, :INT # immediate shutdown
194 when :USR1 # rotate logs
195 logger.info "master reopening logs..."
196 Unicorn::Util.reopen_logs
197 logger.info "master done reopening logs"
198 kill_each_worker(:USR1)
199 when :USR2 # exec binary, stay alive in case something went wrong
202 if Process.ppid == 1 || Process.getpgrp != $$
204 logger.info "gracefully stopping all workers"
205 kill_each_worker(:QUIT)
207 logger.info "SIGWINCH ignored because we're not daemonized"
211 if @config.config_file
213 redo # immediate reaping since we may have QUIT workers
214 else # exec binary and exit if there's no config file
215 logger.info "config_file not present, reexecuting binary"
220 logger.error "master process in unknown mode: #{mode}"
226 logger.error "Unhandled master loop exception #{e.inspect}."
227 logger.error e.backtrace.join("\n")
230 stop # gracefully shutdown all workers on our way out
231 logger.info "master complete"
232 unlink_pid_safe(@pid) if @pid
235 # Terminates all workers, but does not exit master process
236 def stop(graceful = true)
237 kill_each_worker(graceful ? :QUIT : :TERM)
241 until @workers.empty?
244 (timeleft -= step) > 0 and next
245 kill_each_worker(:KILL)
253 # list of signals we care about and trap in master.
254 QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP ].freeze
256 # defer a signal for later processing in #join (master process)
257 def trap_deferred(signal)
258 trap(signal) do |sig_nr|
259 if SIG_QUEUE.size < 5
263 logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
268 # wait for a signal hander to wake us up and then consume the pipe
269 # Wake up every second anyways to run murder_lazy_workers
272 ready = IO.select([@rd_sig], nil, nil, 1)
273 ready && ready[0] && ready[0][0] or return
274 loop { @rd_sig.read_nonblock(Const::CHUNK_SIZE) }
275 rescue Errno::EAGAIN, Errno::EINTR
281 @wr_sig.write_nonblock('.') # wakeup master process from IO.select
282 rescue Errno::EAGAIN, Errno::EINTR
283 # pipe is full, master should wake up anyways
288 # reaps all unreaped workers
292 pid, status = Process.waitpid2(-1, Process::WNOHANG)
294 if @reexec_pid == pid
295 logger.error "reaped #{status.inspect} exec()-ed"
297 self.pid = @pid.chomp('.oldbin') if @pid
300 worker = @workers.delete(pid)
301 worker.tempfile.close rescue nil
302 logger.info "reaped #{status.inspect} " \
303 "worker=#{worker.nr rescue 'unknown'}"
310 # reexecutes the @start_ctx with a new binary
314 Process.kill(0, @reexec_pid)
315 logger.error "reexec-ed child already running PID:#{@reexec_pid}"
323 old_pid = "#{@pid}.oldbin"
326 self.pid = old_pid # clear the path for a new pid file
328 logger.error "old PID:#{valid_pid?(old_pid)} running with " \
329 "existing pid=#{old_pid}, refusing rexec"
332 logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
337 @reexec_pid = fork do
338 listener_fds = @listeners.map { |sock| sock.fileno }
339 ENV['UNICORN_FD'] = listener_fds.join(',')
340 Dir.chdir(@start_ctx[:cwd])
341 cmd = [ @start_ctx[:zero] ] + @start_ctx[:argv]
343 # avoid leaking FDs we don't know about, but let before_exec
344 # unset FD_CLOEXEC, if anything else in the app eventually
345 # relies on FD inheritence.
346 purgatory = [] # prevent GC of IO objects
347 (3..1024).each do |io|
348 next if listener_fds.include?(io)
349 io = IO.for_fd(io) rescue nil
352 io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
354 logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
355 @before_exec.call(self)
358 proc_name 'master (old)'
361 # forcibly terminate all workers that haven't checked in in @timeout
362 # seconds. The timeout is implemented using an unlinked tempfile
363 # shared between the parent process and each worker. The worker
364 # runs File#chmod to modify the ctime of the tempfile. If the ctime
365 # is stale for >@timeout seconds, then we'll kill the corresponding
367 def murder_lazy_workers
369 @workers.each_pair do |pid, worker|
370 (now - worker.tempfile.ctime) <= @timeout and next
371 logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
372 kill_worker(:KILL, pid) # take no prisoners for @timeout violations
373 worker.tempfile.close rescue nil
377 def spawn_missing_workers
378 return if @workers.size == @worker_processes
379 (0...@worker_processes).each do |worker_nr|
380 @workers.values.include?(worker_nr) and next
382 Dir.chdir(@start_ctx[:cwd])
383 rescue Errno::ENOENT => err
384 logger.fatal "#{err.inspect} (#{@start_ctx[:cwd]})"
385 SIG_QUEUE << :QUIT # forcibly emulate SIGQUIT
388 tempfile = Tempfile.new('') # as short as possible to save dir space
389 tempfile.unlink # don't allow other processes to find or see it
390 worker = Worker.new(worker_nr, tempfile)
391 @before_fork.call(self, worker)
392 pid = fork { worker_loop(worker) }
393 @workers[pid] = worker
397 # once a client is accepted, it is processed in its entirety here
398 # in 3 easy steps: read request, call app, write app response
399 def process_client(client)
400 # one syscall less than "client.nonblock = false":
401 client.fcntl(Fcntl::F_SETFL, File::RDWR)
402 HttpResponse.write(client, @app.call(@request.read(client)))
403 # if we get any error, try to write something back to the client
404 # assuming we haven't closed the socket, but don't get hung up
405 # if the socket is already closed or broken. We'll always ensure
406 # the socket is closed at the end of this function
407 rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
408 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
409 rescue HttpParserError # try to tell the client they're bad
410 client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
412 client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
413 logger.error "Read error: #{e.inspect}"
414 logger.error e.backtrace.join("\n")
417 client.closed? or client.close
419 logger.error "Client error: #{e.inspect}"
420 logger.error e.backtrace.join("\n")
425 # gets rid of stuff the worker has no business keeping track of
426 # to free some resources and drops all sig handlers.
427 # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
429 def init_worker_process(worker)
430 QUEUE_SIGS.each { |sig| trap(sig, 'DEFAULT') }
431 trap(:CHLD, 'DEFAULT')
433 proc_name "worker[#{worker.nr}]"
434 @rd_sig.close if @rd_sig
435 @wr_sig.close if @wr_sig
436 @workers.values.each { |other| other.tempfile.close rescue nil }
437 @start_ctx = @workers = @rd_sig = @wr_sig = nil
438 @listeners.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
439 worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
440 @after_fork.call(self, worker) # can drop perms
441 @request = HttpRequest.new(logger)
442 build_app! unless @preload_app
445 # runs inside each forked worker, this sits around and waits
446 # for connections and doesn't die until the parent dies (or is
447 # given a INT, QUIT, or TERM signal)
448 def worker_loop(worker)
449 master_pid = Process.ppid # slightly racy, but less memory usage
450 init_worker_process(worker)
451 nr = 0 # this becomes negative if we need to reopen logs
452 tempfile = worker.tempfile
456 rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
457 wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
459 # closing anything we IO.select on will raise EBADF
460 trap(:USR1) { nr = -65536; rd.close rescue nil }
461 trap(:QUIT) { @listeners.each { |sock| sock.close rescue nil } }
462 [:TERM, :INT].each { |sig| trap(sig) { exit(0) } } # instant shutdown
463 @logger.info "worker=#{worker.nr} ready"
465 while master_pid == Process.ppid
467 @logger.info "worker=#{worker.nr} reopening logs..."
468 Unicorn::Util.reopen_logs
469 @logger.info "worker=#{worker.nr} done reopening logs"
472 rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
473 wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
475 # we're a goner in @timeout seconds anyways if tempfile.chmod
476 # breaks, so don't trap the exception. Using fchmod() since
477 # futimes() is not available in base Ruby and I very strongly
478 # prefer temporary files to be unlinked for security,
479 # performance and reliability reasons, so utime is out. No-op
480 # changes with chmod doesn't update ctime on all filesystems; so
481 # we change our counter each and every time (after process_client
482 # and before IO.select).
483 tempfile.chmod(nr = 0)
493 process_client(client)
494 rescue Errno::ECONNABORTED
495 # client closed the socket even before accept
496 client.close rescue nil
498 tempfile.chmod(nr += 1) if client
504 # make the following bet: if we accepted clients this round,
505 # we're probably reasonably busy, so avoid calling select()
506 # and do a speculative accept_nonblock on every listener
507 # before we sleep again in select().
508 if nr != 0 # (nr < 0) => reopen logs
512 tempfile.chmod(nr += 1)
513 # timeout used so we can detect parent death:
514 ret = IO.select(@listeners, nil, [rd], @timeout/2.0) or next
518 rescue Errno::EBADF => e
519 nr < 0 or exit(@listeners[0].closed? ? 0 : 1)
522 rescue SignalException, SystemExit => e
526 logger.error "Unhandled listen loop exception #{e.inspect}."
527 logger.error e.backtrace.join("\n")
533 # delivers a signal to a worker and fails gracefully if the worker
534 # is no longer running.
535 def kill_worker(signal, pid)
537 Process.kill(signal, pid)
539 worker = @workers.delete(pid) and worker.tempfile.close rescue nil
543 # delivers a signal to each worker
544 def kill_each_worker(signal)
545 @workers.keys.each { |pid| kill_worker(signal, pid) }
548 # unlinks a PID file at given +path+ if it contains the current PID
549 # useful as an at_exit handler.
550 def unlink_pid_safe(path)
551 (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
554 # returns a PID if a given path contains a non-stale PID file,
557 if File.exist?(path) && (pid = File.read(path).to_i) > 1
569 logger.info "reloading config_file=#{@config.config_file}"
570 @config[:listeners].replace(@init_listeners)
572 @config.commit!(self)
573 kill_each_worker(:QUIT)
574 logger.info "done reloading config_file=#{@config.config_file}"
576 logger.error "error reloading config_file=#{@config.config_file}: " \
577 "#{e.class} #{e.message}"
581 # returns an array of string names for the given listener array
582 def listener_names(listeners = @listeners)
583 listeners.map { |io| sock_name(io) }
587 @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0
591 $0 = ([ File.basename(@start_ctx[:zero]), tag ] +
592 @start_ctx[:argv]).join(' ')