cgi_wrapper: don't warn about stdoutput usage
[unicorn.git] / lib / unicorn.rb
blobde61c099d0d61fd7962e8f77f34c190c098512ea
1 # -*- encoding: binary -*-
3 require 'fcntl'
4 require 'unicorn/socket_helper'
5 autoload :Rack, 'rack'
7 # Unicorn module containing all of the classes (include C extensions) for running
8 # a Unicorn web server.  It contains a minimalist HTTP server with just enough
9 # functionality to service web application requests fast as possible.
10 module Unicorn
11   autoload :Const, 'unicorn/const'
12   autoload :HttpRequest, 'unicorn/http_request'
13   autoload :HttpResponse, 'unicorn/http_response'
14   autoload :Configurator, 'unicorn/configurator'
15   autoload :TeeInput, 'unicorn/tee_input'
16   autoload :Util, 'unicorn/util'
18   class << self
19     def run(app, options = {})
20       HttpServer.new(app, options).start.join
21     end
22   end
24   # This is the process manager of Unicorn. This manages worker
25   # processes which in turn handle the I/O and application process.
26   # Listener sockets are started in the master process and shared with
27   # forked worker children.
29   class HttpServer < Struct.new(:listener_opts, :timeout, :worker_processes,
30                                 :before_fork, :after_fork, :before_exec,
31                                 :logger, :pid, :app, :preload_app,
32                                 :reexec_pid, :orig_app, :init_listeners,
33                                 :master_pid, :config)
34     include ::Unicorn::SocketHelper
36     # prevents IO objects in here from being GC-ed
37     IO_PURGATORY = []
39     # all bound listener sockets
40     LISTENERS = []
42     # This hash maps PIDs to Workers
43     WORKERS = {}
45     # See: http://cr.yp.to/docs/selfpipe.html
46     SELF_PIPE = []
48     # signal queue used for self-piping
49     SIG_QUEUE = []
51     # constant lookups are faster and we're single-threaded/non-reentrant
52     REQUEST = HttpRequest.new
54     # We populate this at startup so we can figure out how to reexecute
55     # and upgrade the currently running instance of Unicorn
56     START_CTX = {
57       :argv => ARGV.map { |arg| arg.dup },
58       # don't rely on Dir.pwd here since it's not symlink-aware, and
59       # symlink dirs are the default with Capistrano...
60       :cwd => `/bin/sh -c pwd`.chomp("\n"),
61       0 => $0.dup,
62     }
64     class Worker < Struct.new(:nr, :tmp)
65       # worker objects may be compared to just plain numbers
66       def ==(other_nr)
67         self.nr == other_nr
68       end
69     end
71     # Creates a working server on host:port (strange things happen if
72     # port isn't a Number).  Use HttpServer::run to start the server and
73     # HttpServer.run.join to join the thread that's processing
74     # incoming requests on the socket.
75     def initialize(app, options = {})
76       self.app = app
77       self.reexec_pid = 0
78       self.init_listeners = options[:listeners] ? options[:listeners].dup : []
79       self.config = Configurator.new(options.merge(:use_defaults => true))
80       self.listener_opts = {}
81       config.commit!(self, :skip => [:listeners, :pid])
82       self.orig_app = app
83     end
85     # Runs the thing.  Returns self so you can run join on it
86     def start
87       BasicSocket.do_not_reverse_lookup = true
89       # inherit sockets from parents, they need to be plain Socket objects
90       # before they become UNIXServer or TCPServer
91       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
92         io = Socket.for_fd(fd.to_i)
93         set_server_sockopt(io, listener_opts[sock_name(io)])
94         IO_PURGATORY << io
95         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
96         server_cast(io)
97       end
99       config_listeners = config[:listeners].dup
100       LISTENERS.replace(inherited)
102       # we start out with generic Socket objects that get cast to either
103       # TCPServer or UNIXServer objects; but since the Socket objects
104       # share the same OS-level file descriptor as the higher-level *Server
105       # objects; we need to prevent Socket objects from being garbage-collected
106       config_listeners -= listener_names
107       if config_listeners.empty? && LISTENERS.empty?
108         config_listeners << Unicorn::Const::DEFAULT_LISTEN
109         init_listeners << Unicorn::Const::DEFAULT_LISTEN
110         START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
111       end
112       config_listeners.each { |addr| listen(addr) }
113       raise ArgumentError, "no listeners" if LISTENERS.empty?
114       self.pid = config[:pid]
115       self.master_pid = $$
116       build_app! if preload_app
117       maintain_worker_count
118       self
119     end
121     # replaces current listener set with +listeners+.  This will
122     # close the socket if it will not exist in the new listener set
123     def listeners=(listeners)
124       cur_names, dead_names = [], []
125       listener_names.each do |name|
126         if "/" == name[0..0]
127           # mark unlinked sockets as dead so we can rebind them
128           (File.socket?(name) ? cur_names : dead_names) << name
129         else
130           cur_names << name
131         end
132       end
133       set_names = listener_names(listeners)
134       dead_names.concat(cur_names - set_names).uniq!
136       LISTENERS.delete_if do |io|
137         if dead_names.include?(sock_name(io))
138           IO_PURGATORY.delete_if do |pio|
139             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
140           end
141           (io.close rescue nil).nil? # true
142         else
143           set_server_sockopt(io, listener_opts[sock_name(io)])
144           false
145         end
146       end
148       (set_names - cur_names).each { |addr| listen(addr) }
149     end
151     def stdout_path=(path); redirect_io($stdout, path); end
152     def stderr_path=(path); redirect_io($stderr, path); end
154     alias_method :set_pid, :pid=
155     undef_method :pid=
157     # sets the path for the PID file of the master process
158     def pid=(path)
159       if path
160         if x = valid_pid?(path)
161           return path if pid && path == pid && x == $$
162           raise ArgumentError, "Already running on PID:#{x} " \
163                                "(or pid=#{path} is stale)"
164         end
165       end
166       unlink_pid_safe(pid) if pid
167       File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
168       self.set_pid(path)
169     end
171     # add a given address to the +listeners+ set, idempotently
172     # Allows workers to add a private, per-process listener via the
173     # after_fork hook.  Very useful for debugging and testing.
174     # +:tries+ may be specified as an option for the number of times
175     # to retry, and +:delay+ may be specified as the time in seconds
176     # to delay between retries.
177     # A negative value for +:tries+ indicates the listen will be
178     # retried indefinitely, this is useful when workers belonging to
179     # different masters are spawned during a transparent upgrade.
180     def listen(address, opt = {}.merge(listener_opts[address] || {}))
181       address = config.expand_addr(address)
182       return if String === address && listener_names.include?(address)
184       delay = opt[:delay] || 0.5
185       tries = opt[:tries] || 5
186       begin
187         io = bind_listen(address, opt)
188         unless TCPServer === io || UNIXServer === io
189           IO_PURGATORY << io
190           io = server_cast(io)
191         end
192         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
193         LISTENERS << io
194         return io
195       rescue Errno::EADDRINUSE => err
196         logger.error "adding listener failed addr=#{address} (in use)"
197         raise err if tries == 0
198         tries -= 1
199         logger.error "retrying in #{delay} seconds " \
200                      "(#{tries < 0 ? 'infinite' : tries} tries left)"
201         sleep(delay)
202         retry
203       end
204     end
206     # monitors children and receives signals forever
207     # (or until a termination signal is sent).  This handles signals
208     # one-at-a-time time and we'll happily drop signals in case somebody
209     # is signalling us too often.
210     def join
211       # this pipe is used to wake us up from select(2) in #join when signals
212       # are trapped.  See trap_deferred
213       init_self_pipe!
214       respawn = true
216       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
217       trap(:CHLD) { |sig_nr| awaken_master }
218       proc_name 'master'
219       logger.info "master process ready" # test_exec.rb relies on this message
220       begin
221         loop do
222           reap_all_workers
223           case SIG_QUEUE.shift
224           when nil
225             murder_lazy_workers
226             maintain_worker_count if respawn
227             master_sleep
228           when :QUIT # graceful shutdown
229             break
230           when :TERM, :INT # immediate shutdown
231             stop(false)
232             break
233           when :USR1 # rotate logs
234             logger.info "master reopening logs..."
235             Unicorn::Util.reopen_logs
236             logger.info "master done reopening logs"
237             kill_each_worker(:USR1)
238           when :USR2 # exec binary, stay alive in case something went wrong
239             reexec
240           when :WINCH
241             if Process.ppid == 1 || Process.getpgrp != $$
242               respawn = false
243               logger.info "gracefully stopping all workers"
244               kill_each_worker(:QUIT)
245             else
246               logger.info "SIGWINCH ignored because we're not daemonized"
247             end
248           when :TTIN
249             self.worker_processes += 1
250           when :TTOU
251             self.worker_processes -= 1 if self.worker_processes > 0
252           when :HUP
253             respawn = true
254             if config.config_file
255               load_config!
256               redo # immediate reaping since we may have QUIT workers
257             else # exec binary and exit if there's no config file
258               logger.info "config_file not present, reexecuting binary"
259               reexec
260               break
261             end
262           end
263         end
264       rescue Errno::EINTR
265         retry
266       rescue Object => e
267         logger.error "Unhandled master loop exception #{e.inspect}."
268         logger.error e.backtrace.join("\n")
269         retry
270       end
271       stop # gracefully shutdown all workers on our way out
272       logger.info "master complete"
273       unlink_pid_safe(pid) if pid
274     end
276     # Terminates all workers, but does not exit master process
277     def stop(graceful = true)
278       self.listeners = []
279       kill_each_worker(graceful ? :QUIT : :TERM)
280       timeleft = timeout
281       step = 0.2
282       reap_all_workers
283       until WORKERS.empty?
284         sleep(step)
285         reap_all_workers
286         (timeleft -= step) > 0 and next
287         kill_each_worker(:KILL)
288       end
289     end
291     private
293     # list of signals we care about and trap in master.
294     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
295                    :TTIN, :TTOU ]
297     # defer a signal for later processing in #join (master process)
298     def trap_deferred(signal)
299       trap(signal) do |sig_nr|
300         if SIG_QUEUE.size < 5
301           SIG_QUEUE << signal
302           awaken_master
303         else
304           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
305         end
306       end
307     end
309     # wait for a signal hander to wake us up and then consume the pipe
310     # Wake up every second anyways to run murder_lazy_workers
311     def master_sleep
312       begin
313         ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
314         ready.first && ready.first.first or return
315         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
316       rescue Errno::EAGAIN, Errno::EINTR
317       end
318     end
320     def awaken_master
321       begin
322         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
323       rescue Errno::EAGAIN, Errno::EINTR
324         # pipe is full, master should wake up anyways
325         retry
326       end
327     end
329     # reaps all unreaped workers
330     def reap_all_workers
331       begin
332         loop do
333           wpid, status = Process.waitpid2(-1, Process::WNOHANG)
334           wpid or break
335           if reexec_pid == wpid
336             logger.error "reaped #{status.inspect} exec()-ed"
337             self.reexec_pid = 0
338             self.pid = pid.chomp('.oldbin') if pid
339             proc_name 'master'
340           else
341             worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
342             logger.info "reaped #{status.inspect} " \
343                         "worker=#{worker.nr rescue 'unknown'}"
344           end
345         end
346       rescue Errno::ECHILD
347       end
348     end
350     # reexecutes the START_CTX with a new binary
351     def reexec
352       if reexec_pid > 0
353         begin
354           Process.kill(0, reexec_pid)
355           logger.error "reexec-ed child already running PID:#{reexec_pid}"
356           return
357         rescue Errno::ESRCH
358           reexec_pid = 0
359         end
360       end
362       if pid
363         old_pid = "#{pid}.oldbin"
364         prev_pid = pid.dup
365         begin
366           self.pid = old_pid  # clear the path for a new pid file
367         rescue ArgumentError
368           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
369                        "existing pid=#{old_pid}, refusing rexec"
370           return
371         rescue Object => e
372           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
373           return
374         end
375       end
377       self.reexec_pid = fork do
378         listener_fds = LISTENERS.map { |sock| sock.fileno }
379         ENV['UNICORN_FD'] = listener_fds.join(',')
380         Dir.chdir(START_CTX[:cwd])
381         cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
383         # avoid leaking FDs we don't know about, but let before_exec
384         # unset FD_CLOEXEC, if anything else in the app eventually
385         # relies on FD inheritence.
386         (3..1024).each do |io|
387           next if listener_fds.include?(io)
388           io = IO.for_fd(io) rescue nil
389           io or next
390           IO_PURGATORY << io
391           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
392         end
393         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
394         before_exec.call(self)
395         exec(*cmd)
396       end
397       proc_name 'master (old)'
398     end
400     # forcibly terminate all workers that haven't checked in in timeout
401     # seconds.  The timeout is implemented using an unlinked File
402     # shared between the parent process and each worker.  The worker
403     # runs File#chmod to modify the ctime of the File.  If the ctime
404     # is stale for >timeout seconds, then we'll kill the corresponding
405     # worker.
406     def murder_lazy_workers
407       diff = stat = nil
408       WORKERS.dup.each_pair do |wpid, worker|
409         stat = begin
410           worker.tmp.stat
411         rescue => e
412           logger.warn "worker=#{worker.nr} PID:#{wpid} stat error: #{e.inspect}"
413           kill_worker(:QUIT, wpid)
414           next
415         end
416         stat.mode == 0100000 and next
417         (diff = (Time.now - stat.ctime)) <= timeout and next
418         logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
419                      "(#{diff}s > #{timeout}s), killing"
420         kill_worker(:KILL, wpid) # take no prisoners for timeout violations
421       end
422     end
424     def spawn_missing_workers
425       (0...worker_processes).each do |worker_nr|
426         WORKERS.values.include?(worker_nr) and next
427         begin
428           Dir.chdir(START_CTX[:cwd])
429         rescue Errno::ENOENT => err
430           logger.fatal "#{err.inspect} (#{START_CTX[:cwd]})"
431           SIG_QUEUE << :QUIT # forcibly emulate SIGQUIT
432           return
433         end
434         worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
435         before_fork.call(self, worker)
436         WORKERS[fork { worker_loop(worker) }] = worker
437       end
438     end
440     def maintain_worker_count
441       (off = WORKERS.size - worker_processes) == 0 and return
442       off < 0 and return spawn_missing_workers
443       WORKERS.dup.each_pair { |wpid,w|
444         w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
445       }
446     end
448     # once a client is accepted, it is processed in its entirety here
449     # in 3 easy steps: read request, call app, write app response
450     def process_client(client)
451       client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
452       response = app.call(env = REQUEST.read(client))
454       if 100 == response.first.to_i
455         client.write(Const::EXPECT_100_RESPONSE)
456         env.delete(Const::HTTP_EXPECT)
457         response = app.call(env)
458       end
459       HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
460     # if we get any error, try to write something back to the client
461     # assuming we haven't closed the socket, but don't get hung up
462     # if the socket is already closed or broken.  We'll always ensure
463     # the socket is closed at the end of this function
464     rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
465       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
466       client.close rescue nil
467     rescue HttpParserError # try to tell the client they're bad
468       client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
469       client.close rescue nil
470     rescue Object => e
471       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
472       client.close rescue nil
473       logger.error "Read error: #{e.inspect}"
474       logger.error e.backtrace.join("\n")
475     end
477     # gets rid of stuff the worker has no business keeping track of
478     # to free some resources and drops all sig handlers.
479     # traps for USR1, USR2, and HUP may be set in the after_fork Proc
480     # by the user.
481     def init_worker_process(worker)
482       QUEUE_SIGS.each { |sig| trap(sig, nil) }
483       trap(:CHLD, 'DEFAULT')
484       SIG_QUEUE.clear
485       proc_name "worker[#{worker.nr}]"
486       START_CTX.clear
487       init_self_pipe!
488       WORKERS.values.each { |other| other.tmp.close rescue nil }
489       WORKERS.clear
490       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
491       worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
492       after_fork.call(self, worker) # can drop perms
493       self.timeout /= 2.0 # halve it for select()
494       build_app! unless preload_app
495     end
497     def reopen_worker_logs(worker_nr)
498       logger.info "worker=#{worker_nr} reopening logs..."
499       Unicorn::Util.reopen_logs
500       logger.info "worker=#{worker_nr} done reopening logs"
501       init_self_pipe!
502     end
504     # runs inside each forked worker, this sits around and waits
505     # for connections and doesn't die until the parent dies (or is
506     # given a INT, QUIT, or TERM signal)
507     def worker_loop(worker)
508       ppid = master_pid
509       init_worker_process(worker)
510       nr = 0 # this becomes negative if we need to reopen logs
511       alive = worker.tmp # tmp is our lifeline to the master process
512       ready = LISTENERS
513       t = ti = 0
515       # closing anything we IO.select on will raise EBADF
516       trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
517       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
518       [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
519       logger.info "worker=#{worker.nr} ready"
521       begin
522         nr < 0 and reopen_worker_logs(worker.nr)
523         nr = 0
525         # we're a goner in timeout seconds anyways if alive.chmod
526         # breaks, so don't trap the exception.  Using fchmod() since
527         # futimes() is not available in base Ruby and I very strongly
528         # prefer temporary files to be unlinked for security,
529         # performance and reliability reasons, so utime is out.  No-op
530         # changes with chmod doesn't update ctime on all filesystems; so
531         # we change our counter each and every time (after process_client
532         # and before IO.select).
533         t == (ti = Time.now.to_i) or alive.chmod(t = ti)
535         ready.each do |sock|
536           begin
537             process_client(sock.accept_nonblock)
538             nr += 1
539             t == (ti = Time.now.to_i) or alive.chmod(t = ti)
540           rescue Errno::EAGAIN, Errno::ECONNABORTED
541           end
542           break if nr < 0
543         end
545         # make the following bet: if we accepted clients this round,
546         # we're probably reasonably busy, so avoid calling select()
547         # and do a speculative accept_nonblock on ready listeners
548         # before we sleep again in select().
549         redo unless nr == 0 # (nr < 0) => reopen logs
551         ppid == Process.ppid or return
552         alive.chmod(t = 0)
553         begin
554           # timeout used so we can detect parent death:
555           ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
556           ready = ret.first
557         rescue Errno::EINTR
558           ready = LISTENERS
559         rescue Errno::EBADF
560           nr < 0 or return
561         end
562       rescue Object => e
563         if alive
564           logger.error "Unhandled listen loop exception #{e.inspect}."
565           logger.error e.backtrace.join("\n")
566         end
567       end while alive
568     end
570     # delivers a signal to a worker and fails gracefully if the worker
571     # is no longer running.
572     def kill_worker(signal, wpid)
573       begin
574         Process.kill(signal, wpid)
575       rescue Errno::ESRCH
576         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
577       end
578     end
580     # delivers a signal to each worker
581     def kill_each_worker(signal)
582       WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
583     end
585     # unlinks a PID file at given +path+ if it contains the current PID
586     # useful as an at_exit handler.
587     def unlink_pid_safe(path)
588       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
589     end
591     # returns a PID if a given path contains a non-stale PID file,
592     # nil otherwise.
593     def valid_pid?(path)
594       if File.exist?(path) && (wpid = File.read(path).to_i) > 1
595         begin
596           Process.kill(0, wpid)
597           return wpid
598         rescue Errno::ESRCH
599         end
600       end
601       nil
602     end
604     def load_config!
605       begin
606         logger.info "reloading config_file=#{config.config_file}"
607         config[:listeners].replace(init_listeners)
608         config.reload
609         config.commit!(self)
610         kill_each_worker(:QUIT)
611         Unicorn::Util.reopen_logs
612         self.app = orig_app
613         build_app! if preload_app
614         logger.info "done reloading config_file=#{config.config_file}"
615       rescue Object => e
616         logger.error "error reloading config_file=#{config.config_file}: " \
617                      "#{e.class} #{e.message}"
618       end
619     end
621     # returns an array of string names for the given listener array
622     def listener_names(listeners = LISTENERS)
623       listeners.map { |io| sock_name(io) }
624     end
626     def build_app!
627       if app.respond_to?(:arity) && app.arity == 0
628         if defined?(Gem) && Gem.respond_to?(:refresh)
629           logger.info "Refreshing Gem list"
630           Gem.refresh
631         end
632         self.app = app.call
633       end
634     end
636     def proc_name(tag)
637       $0 = ([ File.basename(START_CTX[0]), tag
638             ]).concat(START_CTX[:argv]).join(' ')
639     end
641     def redirect_io(io, path)
642       File.open(path, 'ab') { |fp| io.reopen(fp) } if path
643       io.sync = true
644     end
646     def init_self_pipe!
647       SELF_PIPE.each { |io| io.close rescue nil }
648       SELF_PIPE.replace(IO.pipe)
649       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
650     end
652   end