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