Avoid getppid() if serving heavy traffic
[unicorn.git] / lib / unicorn.rb
bloba049b5cdab9af3c385dffda923cc9b4cac3a8ef1
1 require 'fcntl'
3 require 'unicorn/socket_helper'
4 require 'unicorn/const'
5 require 'unicorn/http_request'
6 require 'unicorn/http_response'
7 require 'unicorn/configurator'
8 require 'unicorn/util'
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.
13 module Unicorn
14   class << self
15     def run(app, options = {})
16       HttpServer.new(app, options).start.join
17     end
18   end
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.
24   class HttpServer
25     attr_reader :logger
26     include ::Unicorn::SocketHelper
28     # prevents IO objects in here from being GC-ed
29     IO_PURGATORY = []
31     # all bound listener sockets
32     LISTENERS = []
34     # This hash maps PIDs to Workers
35     WORKERS = {}
37     # See: http://cr.yp.to/docs/selfpipe.html
38     SELF_PIPE = []
40     # signal queue used for self-piping
41     SIG_QUEUE = []
43     # We populate this at startup so we can figure out how to reexecute
44     # and upgrade the currently running instance of Unicorn
45     START_CTX = {
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"),
50       :zero => $0.dup,
51     }
53     Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
54     class Worker
55       # worker objects may be compared to just plain numbers
56       def ==(other_nr)
57         self.nr == other_nr
58       end
59     end
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 = {})
66       @app = app
67       @request = nil
68       @reexec_pid = 0
69       @init_listeners = options[:listeners] ? options[:listeners].dup : []
70       @config = Configurator.new(options.merge(:use_defaults => true))
71       @listener_opts = {}
72       @config.commit!(self, :skip => [:listeners, :pid])
73     end
75     # Runs the thing.  Returns self so you can run join on it
76     def start
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)])
84         IO_PURGATORY << io
85         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
86         server_cast(io)
87       end
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
99       end
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       File.open(@stderr_path, "a") { |fp| $stderr.reopen(fp) } if @stderr_path
105       File.open(@stdout_path, "a") { |fp| $stdout.reopen(fp) } if @stdout_path
106       $stderr.sync = $stdout.sync = true
107       spawn_missing_workers
108       self
109     end
111     # replaces current listener set with +listeners+.  This will
112     # close the socket if it will not exist in the new listener set
113     def listeners=(listeners)
114       cur_names, dead_names = [], []
115       listener_names.each do |name|
116         if "/" == name[0..0]
117           # mark unlinked sockets as dead so we can rebind them
118           (File.socket?(name) ? cur_names : dead_names) << name
119         else
120           cur_names << name
121         end
122       end
123       set_names = listener_names(listeners)
124       dead_names += cur_names - set_names
125       dead_names.uniq!
127       LISTENERS.delete_if do |io|
128         if dead_names.include?(sock_name(io))
129           IO_PURGATORY.delete_if do |pio|
130             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
131           end
132           (io.close rescue nil).nil? # true
133         else
134           set_server_sockopt(io, @listener_opts[sock_name(io)])
135           false
136         end
137       end
139       (set_names - cur_names).each { |addr| listen(addr) }
140     end
142     # sets the path for the PID file of the master process
143     def pid=(path)
144       if path
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)"
149         end
150       end
151       unlink_pid_safe(@pid) if @pid
152       File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
153       @pid = path
154     end
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
164           IO_PURGATORY << io
165           io = server_cast(io)
166         end
167         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
168         LISTENERS << io
169       else
170         logger.error "adding listener failed addr=#{address} (in use)"
171         raise Errno::EADDRINUSE, address
172       end
173     end
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.
179     def join
180       # this pipe is used to wake us up from select(2) in #join when signals
181       # are trapped.  See trap_deferred
182       SELF_PIPE.replace(IO.pipe)
183       mode = nil
184       respawn = true
186       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
187       trap(:CHLD) { |sig_nr| awaken_master }
188       proc_name 'master'
189       logger.info "master process ready" # test_exec.rb relies on this message
190       begin
191         loop do
192           reap_all_workers
193           case (mode = SIG_QUEUE.shift)
194           when nil
195             murder_lazy_workers
196             spawn_missing_workers if respawn
197             master_sleep
198           when :QUIT # graceful shutdown
199             break
200           when :TERM, :INT # immediate shutdown
201             stop(false)
202             break
203           when :USR1 # rotate logs
204             logger.info "master reopening logs..."
205             Unicorn::Util.reopen_logs
206             logger.info "master done reopening logs"
207             kill_each_worker(:USR1)
208           when :USR2 # exec binary, stay alive in case something went wrong
209             reexec
210           when :WINCH
211             if Process.ppid == 1 || Process.getpgrp != $$
212               respawn = false
213               logger.info "gracefully stopping all workers"
214               kill_each_worker(:QUIT)
215             else
216               logger.info "SIGWINCH ignored because we're not daemonized"
217             end
218           when :HUP
219             respawn = true
220             if @config.config_file
221               load_config!
222               redo # immediate reaping since we may have QUIT workers
223             else # exec binary and exit if there's no config file
224               logger.info "config_file not present, reexecuting binary"
225               reexec
226               break
227             end
228           else
229             logger.error "master process in unknown mode: #{mode}"
230           end
231         end
232       rescue Errno::EINTR
233         retry
234       rescue Object => e
235         logger.error "Unhandled master loop exception #{e.inspect}."
236         logger.error e.backtrace.join("\n")
237         retry
238       end
239       stop # gracefully shutdown all workers on our way out
240       logger.info "master complete"
241       unlink_pid_safe(@pid) if @pid
242     end
244     # Terminates all workers, but does not exit master process
245     def stop(graceful = true)
246       kill_each_worker(graceful ? :QUIT : :TERM)
247       timeleft = @timeout
248       step = 0.2
249       reap_all_workers
250       until WORKERS.empty?
251         sleep(step)
252         reap_all_workers
253         (timeleft -= step) > 0 and next
254         kill_each_worker(:KILL)
255       end
256     ensure
257       self.listeners = []
258     end
260     private
262     # list of signals we care about and trap in master.
263     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP ].freeze
265     # defer a signal for later processing in #join (master process)
266     def trap_deferred(signal)
267       trap(signal) do |sig_nr|
268         if SIG_QUEUE.size < 5
269           SIG_QUEUE << signal
270           awaken_master
271         else
272           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
273         end
274       end
275     end
277     # wait for a signal hander to wake us up and then consume the pipe
278     # Wake up every second anyways to run murder_lazy_workers
279     def master_sleep
280       begin
281         ready = IO.select([SELF_PIPE.first], nil, nil, 1)
282         ready && ready[0] && ready[0][0] or return
283         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
284       rescue Errno::EAGAIN, Errno::EINTR
285       end
286     end
288     def awaken_master
289       begin
290         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
291       rescue Errno::EAGAIN, Errno::EINTR
292         # pipe is full, master should wake up anyways
293         retry
294       end
295     end
297     # reaps all unreaped workers
298     def reap_all_workers
299       begin
300         loop do
301           pid, status = Process.waitpid2(-1, Process::WNOHANG)
302           pid or break
303           if @reexec_pid == pid
304             logger.error "reaped #{status.inspect} exec()-ed"
305             @reexec_pid = 0
306             self.pid = @pid.chomp('.oldbin') if @pid
307             proc_name 'master'
308           else
309             worker = WORKERS.delete(pid)
310             worker.tempfile.close rescue nil
311             logger.info "reaped #{status.inspect} " \
312                         "worker=#{worker.nr rescue 'unknown'}"
313           end
314         end
315       rescue Errno::ECHILD
316       end
317     end
319     # reexecutes the START_CTX with a new binary
320     def reexec
321       if @reexec_pid > 0
322         begin
323           Process.kill(0, @reexec_pid)
324           logger.error "reexec-ed child already running PID:#{@reexec_pid}"
325           return
326         rescue Errno::ESRCH
327           @reexec_pid = 0
328         end
329       end
331       if @pid
332         old_pid = "#{@pid}.oldbin"
333         prev_pid = @pid.dup
334         begin
335           self.pid = old_pid  # clear the path for a new pid file
336         rescue ArgumentError
337           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
338                        "existing pid=#{old_pid}, refusing rexec"
339           return
340         rescue Object => e
341           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
342           return
343         end
344       end
346       @reexec_pid = fork do
347         listener_fds = LISTENERS.map { |sock| sock.fileno }
348         ENV['UNICORN_FD'] = listener_fds.join(',')
349         Dir.chdir(START_CTX[:cwd])
350         cmd = [ START_CTX[:zero] ] + START_CTX[:argv]
352         # avoid leaking FDs we don't know about, but let before_exec
353         # unset FD_CLOEXEC, if anything else in the app eventually
354         # relies on FD inheritence.
355         (3..1024).each do |io|
356           next if listener_fds.include?(io)
357           io = IO.for_fd(io) rescue nil
358           io or next
359           IO_PURGATORY << io
360           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
361         end
362         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
363         @before_exec.call(self)
364         exec(*cmd)
365       end
366       proc_name 'master (old)'
367     end
369     # forcibly terminate all workers that haven't checked in in @timeout
370     # seconds.  The timeout is implemented using an unlinked tempfile
371     # shared between the parent process and each worker.  The worker
372     # runs File#chmod to modify the ctime of the tempfile.  If the ctime
373     # is stale for >@timeout seconds, then we'll kill the corresponding
374     # worker.
375     def murder_lazy_workers
376       now = Time.now
377       WORKERS.each_pair do |pid, worker|
378         (now - worker.tempfile.ctime) <= @timeout and next
379         logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
380         kill_worker(:KILL, pid) # take no prisoners for @timeout violations
381         worker.tempfile.close rescue nil
382       end
383     end
385     def spawn_missing_workers
386       return if WORKERS.size == @worker_processes
387       (0...@worker_processes).each do |worker_nr|
388         WORKERS.values.include?(worker_nr) and next
389         begin
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
394           return
395         end
396         tempfile = Tempfile.new('') # 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
402       end
403     end
405     # once a client is accepted, it is processed in its entirety here
406     # in 3 easy steps: read request, call app, write app response
407     def process_client(client)
408       # one syscall less than "client.nonblock = false":
409       client.fcntl(Fcntl::F_SETFL, File::RDWR)
410       HttpResponse.write(client, @app.call(@request.read(client)))
411     # if we get any error, try to write something back to the client
412     # assuming we haven't closed the socket, but don't get hung up
413     # if the socket is already closed or broken.  We'll always ensure
414     # the socket is closed at the end of this function
415     rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
416       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
417     rescue HttpParserError # try to tell the client they're bad
418       client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
419     rescue Object => e
420       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
421       logger.error "Read error: #{e.inspect}"
422       logger.error e.backtrace.join("\n")
423     ensure
424       begin
425         client.closed? or client.close
426       rescue Object => e
427         logger.error "Client error: #{e.inspect}"
428         logger.error e.backtrace.join("\n")
429       end
430       @request.reset
431     end
433     # gets rid of stuff the worker has no business keeping track of
434     # to free some resources and drops all sig handlers.
435     # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
436     # by the user.
437     def init_worker_process(worker)
438       QUEUE_SIGS.each { |sig| trap(sig, 'DEFAULT') }
439       trap(:CHLD, 'DEFAULT')
440       SIG_QUEUE.clear
441       proc_name "worker[#{worker.nr}]"
442       START_CTX.clear
443       SELF_PIPE.each { |x| x.close rescue nil }
444       SELF_PIPE.clear
445       WORKERS.values.each { |other| other.tempfile.close rescue nil }
446       WORKERS.clear
447       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
448       worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
449       @after_fork.call(self, worker) # can drop perms
450       @request = HttpRequest.new(logger)
451       build_app! unless @preload_app
452     end
454     # runs inside each forked worker, this sits around and waits
455     # for connections and doesn't die until the parent dies (or is
456     # given a INT, QUIT, or TERM signal)
457     def worker_loop(worker)
458       master_pid = Process.ppid # slightly racy, but less memory usage
459       init_worker_process(worker)
460       nr = 0 # this becomes negative if we need to reopen logs
461       alive = worker.tempfile # tempfile is our lifeline to the master process
462       ready = LISTENERS
463       client = nil
464       rd, wr = IO.pipe
465       rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
466       wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
468       # closing anything we IO.select on will raise EBADF
469       trap(:USR1) { nr = -65536; rd.close rescue nil }
470       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
471       [:TERM, :INT].each { |sig| trap(sig) { exit(0) } } # instant shutdown
472       @logger.info "worker=#{worker.nr} ready"
474       while alive
475         if nr < 0
476           @logger.info "worker=#{worker.nr} reopening logs..."
477           Unicorn::Util.reopen_logs
478           @logger.info "worker=#{worker.nr} done reopening logs"
479           wr.close rescue nil
480           rd, wr = IO.pipe
481           rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
482           wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
483         end
484         # we're a goner in @timeout seconds anyways if alive.chmod
485         # breaks, so don't trap the exception.  Using fchmod() since
486         # futimes() is not available in base Ruby and I very strongly
487         # prefer temporary files to be unlinked for security,
488         # performance and reliability reasons, so utime is out.  No-op
489         # changes with chmod doesn't update ctime on all filesystems; so
490         # we change our counter each and every time (after process_client
491         # and before IO.select).
492         alive.chmod(nr = 0)
494         begin
495           ready.each do |sock|
496             begin
497               client = begin
498                 sock.accept_nonblock
499               rescue Errno::EAGAIN
500                 next
501               end
502               process_client(client)
503             rescue Errno::ECONNABORTED
504               # client closed the socket even before accept
505               client.close rescue nil
506             ensure
507               alive.chmod(nr += 1) if client
508               break if nr < 0
509             end
510           end
511           client = nil
513           # make the following bet: if we accepted clients this round,
514           # we're probably reasonably busy, so avoid calling select()
515           # and do a speculative accept_nonblock on every listener
516           # before we sleep again in select().
517           if nr != 0 # (nr < 0) => reopen logs
518             ready = LISTENERS
519           else
520             master_pid == Process.ppid or exit(0)
521             begin
522               alive.chmod(nr += 1)
523               # timeout used so we can detect parent death:
524               ret = IO.select(LISTENERS, nil, [rd], @timeout/2.0) or next
525               ready = ret[0]
526             rescue Errno::EINTR
527               ready = LISTENERS
528             rescue Errno::EBADF => e
529               nr < 0 or exit(alive ? 1 : 0)
530             end
531           end
532         rescue SignalException, SystemExit => e
533           raise e
534         rescue Object => e
535           if alive
536             logger.error "Unhandled listen loop exception #{e.inspect}."
537             logger.error e.backtrace.join("\n")
538           end
539         end
540       end
541     end
543     # delivers a signal to a worker and fails gracefully if the worker
544     # is no longer running.
545     def kill_worker(signal, pid)
546       begin
547         Process.kill(signal, pid)
548       rescue Errno::ESRCH
549         worker = WORKERS.delete(pid) and worker.tempfile.close rescue nil
550       end
551     end
553     # delivers a signal to each worker
554     def kill_each_worker(signal)
555       WORKERS.keys.each { |pid| kill_worker(signal, pid) }
556     end
558     # unlinks a PID file at given +path+ if it contains the current PID
559     # useful as an at_exit handler.
560     def unlink_pid_safe(path)
561       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
562     end
564     # returns a PID if a given path contains a non-stale PID file,
565     # nil otherwise.
566     def valid_pid?(path)
567       if File.exist?(path) && (pid = File.read(path).to_i) > 1
568         begin
569           Process.kill(0, pid)
570           return pid
571         rescue Errno::ESRCH
572         end
573       end
574       nil
575     end
577     def load_config!
578       begin
579         logger.info "reloading config_file=#{@config.config_file}"
580         @config[:listeners].replace(@init_listeners)
581         @config.reload
582         @config.commit!(self)
583         kill_each_worker(:QUIT)
584         logger.info "done reloading config_file=#{@config.config_file}"
585       rescue Object => e
586         logger.error "error reloading config_file=#{@config.config_file}: " \
587                      "#{e.class} #{e.message}"
588       end
589     end
591     # returns an array of string names for the given listener array
592     def listener_names(listeners = LISTENERS)
593       listeners.map { |io| sock_name(io) }
594     end
596     def build_app!
597       @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0
598     end
600     def proc_name(tag)
601       $0 = ([ File.basename(START_CTX[:zero]), tag ] +
602               START_CTX[:argv]).join(' ')
603     end
605   end