Use File.basename instead of a regexp
[unicorn.git] / lib / unicorn.rb
blobd73317dd194a21dd39054fa4949a7573b360f984
1 require 'logger'
2 require 'fcntl'
4 require 'unicorn/socket'
5 require 'unicorn/const'
6 require 'unicorn/http_request'
7 require 'unicorn/http_response'
8 require 'unicorn/configurator'
9 require 'unicorn/util'
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.
14 module Unicorn
15   class << self
16     def run(app, options = {})
17       HttpServer.new(app, options).start.join
18     end
19   end
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.
25   class HttpServer
26     attr_reader :logger
27     include ::Unicorn::SocketHelper
29     DEFAULT_START_CTX = {
30       :argv => ARGV.map { |arg| arg.dup },
31       # don't rely on Dir.pwd here since it's not symlink-aware, and
32       # symlink dirs are the default with Capistrano...
33       :cwd => `/bin/sh -c pwd`.chomp("\n"),
34       :zero => $0.dup,
35       :environ => {}.merge!(ENV),
36       :umask => File.umask,
37     }.freeze
39     Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
40     class Worker
41       # worker objects may be compared to just plain numbers
42       def ==(other_nr)
43         self.nr == other_nr
44       end
45     end
47     # Creates a working server on host:port (strange things happen if
48     # port isn't a Number).  Use HttpServer::run to start the server and
49     # HttpServer.workers.join to join the thread that's processing
50     # incoming requests on the socket.
51     def initialize(app, options = {})
52       start_ctx = options.delete(:start_ctx)
53       @start_ctx = DEFAULT_START_CTX.dup
54       @start_ctx.merge!(start_ctx) if start_ctx
55       @app = app
56       @sig_queue = []
57       @master_pid = $$
58       @workers = Hash.new
59       @io_purgatory = [] # prevents IO objects in here from being GC-ed
60       @request = @rd_sig = @wr_sig = nil
61       @reexec_pid = 0
62       @config = Configurator.new(options.merge(:use_defaults => true))
63       @listener_opts = {}
64       @config.commit!(self, :skip => [:listeners, :pid])
65       @listeners = []
66     end
68     # Runs the thing.  Returns self so you can run join on it
69     def start
70       BasicSocket.do_not_reverse_lookup = true
72       # inherit sockets from parents, they need to be plain Socket objects
73       # before they become UNIXServer or TCPServer
74       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
75         io = Socket.for_fd(fd.to_i)
76         set_server_sockopt(io)
77         @io_purgatory << io
78         logger.info "inherited: #{io} fd=#{fd} addr=#{sock_name(io)}"
79         server_cast(io)
80       end
82       config_listeners = @config[:listeners].dup
83       @listeners.replace(inherited)
85       # we start out with generic Socket objects that get cast to either
86       # TCPServer or UNIXServer objects; but since the Socket objects
87       # share the same OS-level file descriptor as the higher-level *Server
88       # objects; we need to prevent Socket objects from being garbage-collected
89       config_listeners -= listener_names
90       if config_listeners.empty? && @listeners.empty?
91         config_listeners << Unicorn::Const::DEFAULT_LISTEN
92       end
93       config_listeners.each { |addr| listen(addr) }
94       raise ArgumentError, "no listeners" if @listeners.empty?
95       self.pid = @config[:pid]
96       build_app! if @preload_app
97       File.open(@stderr_path, "a") { |fp| $stderr.reopen(fp) } if @stderr_path
98       File.open(@stdout_path, "a") { |fp| $stdout.reopen(fp) } if @stdout_path
99       $stderr.sync = $stdout.sync = true
100       spawn_missing_workers
101       self
102     end
104     # replaces current listener set with +listeners+.  This will
105     # close the socket if it will not exist in the new listener set
106     def listeners=(listeners)
107       cur_names = listener_names
108       set_names = listener_names(listeners)
109       dead_names = cur_names - set_names
111       @listeners.delete_if do |io|
112         if dead_names.include?(sock_name(io))
113           @io_purgatory.delete_if { |pio| pio.fileno == io.fileno }
114           true
115         else
116           false
117         end
118       end
120       (set_names - cur_names).each { |addr| listen(addr) }
121     end
123     # sets the path for the PID file of the master process
124     def pid=(path)
125       if path
126         if x = valid_pid?(path)
127           return path if @pid && path == @pid && x == $$
128           raise ArgumentError, "Already running on PID:#{x} " \
129                                "(or pid=#{path} is stale)"
130         end
131       end
132       unlink_pid_safe(@pid) if @pid
133       File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
134       @pid = path
135     end
137     # add a given address to the +listeners+ set, idempotently
138     # Allows workers to add a private, per-process listener via the
139     # @after_fork hook.  Very useful for debugging and testing.
140     def listen(address, opt = {}.merge(@listener_opts[address] || {}))
141       return if String === address && listener_names.include?(address)
143       if io = bind_listen(address, opt)
144         if Socket == io.class
145           @io_purgatory << io
146           io = server_cast(io)
147         end
148         logger.info "#{io} listening on PID:#{$$} " \
149                     "fd=#{io.fileno} addr=#{sock_name(io)}"
150         @listeners << io
151       else
152         logger.error "adding listener failed addr=#{address} (in use)"
153         raise Errno::EADDRINUSE, address
154       end
155     end
157     # monitors children and receives signals forever
158     # (or until a termination signal is sent).  This handles signals
159     # one-at-a-time time and we'll happily drop signals in case somebody
160     # is signalling us too often.
161     def join
162       # this pipe is used to wake us up from select(2) in #join when signals
163       # are trapped.  See trap_deferred
164       @rd_sig, @wr_sig = IO.pipe unless (@rd_sig && @wr_sig)
165       mode = nil
166       respawn = true
168       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
169       trap(:CHLD) { |sig_nr| awaken_master }
170       proc_name 'master'
171       logger.info "master process ready" # test_exec.rb relies on this message
172       begin
173         loop do
174           reap_all_workers
175           case (mode = @sig_queue.shift)
176           when nil
177             murder_lazy_workers
178             spawn_missing_workers if respawn
179             master_sleep
180           when :QUIT # graceful shutdown
181             break
182           when :TERM, :INT # immediate shutdown
183             stop(false)
184             break
185           when :USR1 # rotate logs
186             logger.info "master rotating logs..."
187             Unicorn::Util.reopen_logs
188             logger.info "master done rotating logs"
189             kill_each_worker(:USR1)
190           when :USR2 # exec binary, stay alive in case something went wrong
191             reexec
192           when :WINCH
193             if Process.ppid == 1 || Process.getpgrp != $$
194               respawn = false
195               logger.info "gracefully stopping all workers"
196               kill_each_worker(:QUIT)
197             else
198               logger.info "SIGWINCH ignored because we're not daemonized"
199             end
200           when :HUP
201             respawn = true
202             if @config.config_file
203               load_config!
204               redo # immediate reaping since we may have QUIT workers
205             else # exec binary and exit if there's no config file
206               logger.info "config_file not present, reexecuting binary"
207               reexec
208               break
209             end
210           else
211             logger.error "master process in unknown mode: #{mode}"
212           end
213         end
214       rescue Errno::EINTR
215         retry
216       rescue Object => e
217         logger.error "Unhandled master loop exception #{e.inspect}."
218         logger.error e.backtrace.join("\n")
219         retry
220       end
221       stop # gracefully shutdown all workers on our way out
222       logger.info "master PID:#{$$} join complete"
223       unlink_pid_safe(@pid) if @pid
224     end
226     # Terminates all workers, but does not exit master process
227     def stop(graceful = true)
228       kill_each_worker(graceful ? :QUIT : :TERM)
229       timeleft = @timeout
230       step = 0.2
231       reap_all_workers
232       until @workers.empty?
233         sleep(step)
234         reap_all_workers
235         (timeleft -= step) > 0 and next
236         kill_each_worker(:KILL)
237       end
238     ensure
239       self.listeners = []
240     end
242     private
244     # list of signals we care about and trap in master.
245     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP ].freeze
247     # defer a signal for later processing in #join (master process)
248     def trap_deferred(signal)
249       trap(signal) do |sig_nr|
250         if @sig_queue.size < 5
251           @sig_queue << signal
252           awaken_master
253         else
254           logger.error "ignoring SIG#{signal}, queue=#{@sig_queue.inspect}"
255         end
256       end
257     end
259     # wait for a signal hander to wake us up and then consume the pipe
260     # Wake up every second anyways to run murder_lazy_workers
261     def master_sleep
262       begin
263         ready = IO.select([@rd_sig], nil, nil, 1)
264         ready && ready[0] && ready[0][0] or return
265         loop { @rd_sig.read_nonblock(Const::CHUNK_SIZE) }
266       rescue Errno::EAGAIN, Errno::EINTR
267       end
268     end
270     def awaken_master
271       begin
272         @wr_sig.write_nonblock('.') # wakeup master process from IO.select
273       rescue Errno::EAGAIN, Errno::EINTR
274         # pipe is full, master should wake up anyways
275         retry
276       end
277     end
279     # reaps all unreaped workers
280     def reap_all_workers
281       begin
282         loop do
283           pid, status = Process.waitpid2(-1, Process::WNOHANG)
284           pid or break
285           if @reexec_pid == pid
286             logger.error "reaped #{status.inspect} exec()-ed"
287             @reexec_pid = 0
288             self.pid = @pid.chomp('.oldbin') if @pid
289             proc_name 'master'
290           else
291             worker = @workers.delete(pid)
292             worker.tempfile.close rescue nil
293             logger.info "reaped #{status.inspect} " \
294                         "worker=#{worker.nr rescue 'unknown'}"
295           end
296         end
297       rescue Errno::ECHILD
298       end
299     end
301     # reexecutes the @start_ctx with a new binary
302     def reexec
303       if @reexec_pid > 0
304         begin
305           Process.kill(0, @reexec_pid)
306           logger.error "reexec-ed child already running PID:#{@reexec_pid}"
307           return
308         rescue Errno::ESRCH
309           @reexec_pid = 0
310         end
311       end
313       if @pid
314         old_pid = "#{@pid}.oldbin"
315         prev_pid = @pid.dup
316         begin
317           self.pid = old_pid  # clear the path for a new pid file
318         rescue ArgumentError
319           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
320                        "existing pid=#{old_pid}, refusing rexec"
321           return
322         rescue Object => e
323           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
324           return
325         end
326       end
328       @reexec_pid = fork do
329         ENV.replace(@start_ctx[:environ])
330         listener_fds = @listeners.map { |sock| sock.fileno }
331         ENV['UNICORN_FD'] = listener_fds.join(',')
332         File.umask(@start_ctx[:umask])
333         Dir.chdir(@start_ctx[:cwd])
334         cmd = [ @start_ctx[:zero] ] + @start_ctx[:argv]
336         # avoid leaking FDs we don't know about, but let before_exec
337         # unset FD_CLOEXEC, if anything else in the app eventually
338         # relies on FD inheritence.
339         purgatory = [] # prevent GC of IO objects
340         (3..1024).each do |io|
341           next if listener_fds.include?(io)
342           io = IO.for_fd(io) rescue nil
343           io or next
344           purgatory << io
345           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
346         end
347         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
348         @before_exec.call(self) if @before_exec
349         exec(*cmd)
350       end
351       proc_name 'master (old)'
352     end
354     # forcibly terminate all workers that haven't checked in in @timeout
355     # seconds.  The timeout is implemented using an unlinked tempfile
356     # shared between the parent process and each worker.  The worker
357     # runs File#chmod to modify the ctime of the tempfile.  If the ctime
358     # is stale for >@timeout seconds, then we'll kill the corresponding
359     # worker.
360     def murder_lazy_workers
361       now = Time.now
362       @workers.each_pair do |pid, worker|
363         (now - worker.tempfile.ctime) <= @timeout and next
364         logger.error "worker=#{worker.nr} PID:#{pid} is too old, killing"
365         kill_worker(:KILL, pid) # take no prisoners for @timeout violations
366         worker.tempfile.close rescue nil
367       end
368     end
370     def spawn_missing_workers
371       return if @workers.size == @worker_processes
372       (0...@worker_processes).each do |worker_nr|
373         @workers.values.include?(worker_nr) and next
374         begin
375           Dir.chdir(@start_ctx[:cwd])
376         rescue Errno::ENOENT => err
377           logger.fatal "#{err.inspect} (#{@start_ctx[:cwd]})"
378           @sig_queue << :QUIT # forcibly emulate SIGQUIT
379           return
380         end
381         tempfile = Tempfile.new('') # as short as possible to save dir space
382         tempfile.unlink # don't allow other processes to find or see it
383         tempfile.sync = true
384         worker = Worker.new(worker_nr, tempfile)
385         @before_fork.call(self, worker.nr)
386         pid = fork { worker_loop(worker) }
387         @workers[pid] = worker
388       end
389     end
391     # once a client is accepted, it is processed in its entirety here
392     # in 3 easy steps: read request, call app, write app response
393     def process_client(client)
394       client.nonblock = false
395       set_client_sockopt(client) if TCPSocket === client
396       env = @request.read(client)
397       app_response = @app.call(env)
398       HttpResponse.write(client, app_response)
399     # if we get any error, try to write something back to the client
400     # assuming we haven't closed the socket, but don't get hung up
401     # if the socket is already closed or broken.  We'll always ensure
402     # the socket is closed at the end of this function
403     rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
404       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
405     rescue HttpParserError # try to tell the client they're bad
406       client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
407     rescue Object => e
408       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
409       logger.error "Read error: #{e.inspect}"
410       logger.error e.backtrace.join("\n")
411     ensure
412       begin
413         client.closed? or client.close
414       rescue Object => e
415         logger.error "Client error: #{e.inspect}"
416         logger.error e.backtrace.join("\n")
417       end
418       @request.reset
419     end
421     # gets rid of stuff the worker has no business keeping track of
422     # to free some resources and drops all sig handlers.
423     # traps for USR1, USR2, and HUP may be set in the @after_fork Proc
424     # by the user.
425     def init_worker_process(worker)
426       build_app! unless @preload_app
427       @sig_queue.clear
428       QUEUE_SIGS.each { |sig| trap(sig, 'IGNORE') }
429       trap(:CHLD, 'DEFAULT')
431       proc_name "worker[#{worker.nr}]"
432       @rd_sig.close if @rd_sig
433       @wr_sig.close if @wr_sig
434       @workers.values.each { |other| other.tempfile.close rescue nil }
435       @workers.clear
436       @start_ctx.clear
437       @start_ctx = @workers = @rd_sig = @wr_sig = nil
438       @listeners.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
439       ENV.delete('UNICORN_FD')
440       @after_fork.call(self, worker.nr) if @after_fork
441       worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
442       @request = HttpRequest.new(logger)
443     end
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       init_worker_process(worker)
450       nr = 0
451       tempfile = worker.tempfile
452       alive = true
453       ready = @listeners
454       client = nil
455       [:TERM, :INT].each { |sig| trap(sig) { exit(0) } } # instant shutdown
456       trap(:QUIT) do
457         alive = false
458         @listeners.each { |sock| sock.close rescue nil } # break IO.select
459       end
460       reopen_logs, (rd, wr) = false, IO.pipe
461       rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
462       wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
463       trap(:USR1) { reopen_logs = true; rd.close rescue nil } # break IO.select
464       @logger.info "worker=#{worker.nr} ready"
466       while alive && @master_pid == Process.ppid
467         if reopen_logs
468           reopen_logs = false
469           @logger.info "worker=#{worker.nr} rotating logs..."
470           Unicorn::Util.reopen_logs
471           @logger.info "worker=#{worker.nr} done rotating logs"
472           wr.close rescue nil
473           rd, wr = IO.pipe
474           rd.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
475           wr.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
476         end
477         # we're a goner in @timeout seconds anyways if tempfile.chmod
478         # breaks, so don't trap the exception.  Using fchmod() since
479         # futimes() is not available in base Ruby and I very strongly
480         # prefer temporary files to be unlinked for security,
481         # performance and reliability reasons, so utime is out.  No-op
482         # changes with chmod doesn't update ctime on all filesystems; so
483         # we increment our counter each and every time.
484         tempfile.chmod(nr += 1)
486         begin
487           accepted = false
488           ready.each do |sock|
489             begin
490               client = begin
491                 sock.accept_nonblock
492               rescue Errno::EAGAIN
493                 next
494               end
495               accepted = true
496               process_client(client)
497             rescue Errno::ECONNABORTED
498               # client closed the socket even before accept
499               client.close rescue nil
500             end
501             tempfile.chmod(nr += 1)
502             break if reopen_logs
503           end
504           client = nil
506           # make the following bet: if we accepted clients this round,
507           # we're probably reasonably busy, so avoid calling select(2)
508           # and try to do a blind non-blocking accept(2) on everything
509           # before we sleep again in select
510           if accepted || reopen_logs
511             ready = @listeners
512           else
513             begin
514               tempfile.chmod(nr += 1)
515               # timeout used so we can detect parent death:
516               ret = IO.select(@listeners, nil, [rd], @timeout/2.0) or next
517               ready = ret[0]
518             rescue Errno::EINTR
519               ready = @listeners
520             rescue Errno::EBADF => e
521               reopen_logs or exit(alive ? 1 : 0)
522             end
523           end
524         rescue SystemExit => e
525           exit(e.status)
526         rescue Object => e
527           if alive
528             logger.error "Unhandled listen loop exception #{e.inspect}."
529             logger.error e.backtrace.join("\n")
530           end
531         end
532       end
533     end
535     # delivers a signal to a worker and fails gracefully if the worker
536     # is no longer running.
537     def kill_worker(signal, pid)
538       begin
539         Process.kill(signal, pid)
540       rescue Errno::ESRCH
541         worker = @workers.delete(pid) and worker.tempfile.close rescue nil
542       end
543     end
545     # delivers a signal to each worker
546     def kill_each_worker(signal)
547       @workers.keys.each { |pid| kill_worker(signal, pid) }
548     end
550     # unlinks a PID file at given +path+ if it contains the current PID
551     # useful as an at_exit handler.
552     def unlink_pid_safe(path)
553       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
554     end
556     # returns a PID if a given path contains a non-stale PID file,
557     # nil otherwise.
558     def valid_pid?(path)
559       if File.exist?(path) && (pid = File.read(path).to_i) > 1
560         begin
561           Process.kill(0, pid)
562           return pid
563         rescue Errno::ESRCH
564         end
565       end
566       nil
567     end
569     def load_config!
570       begin
571         logger.info "reloading config_file=#{@config.config_file}"
572         @config.reload
573         @config.commit!(self)
574         kill_each_worker(:QUIT)
575         logger.info "done reloading config_file=#{@config.config_file}"
576       rescue Object => e
577         logger.error "error reloading config_file=#{@config.config_file}: " \
578                      "#{e.class} #{e.message}"
579       end
580     end
582     # returns an array of string names for the given listener array
583     def listener_names(listeners = @listeners)
584       listeners.map { |io| sock_name(io) }
585     end
587     def build_app!
588       @app = @app.call if @app.respond_to?(:arity) && @app.arity == 0
589     end
591     def proc_name(tag)
592       $0 = ([ File.basename(@start_ctx[:zero]), tag ] +
593               @start_ctx[:argv]).join(' ')
594     end
596   end