ClientShutdown: RDoc
[unicorn.git] / lib / unicorn.rb
blobcfc6413fe427c78559237e53c8cda40d8fe35295
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
12   # raised inside TeeInput when a client closes the socket inside the
13   # application dispatch.  This is always raised with an empty backtrace
14   # since there is nothing in the application stack that is responsible
15   # for client shutdowns/disconnects.
16   class ClientShutdown < EOFError
17   end
19   autoload :Const, 'unicorn/const'
20   autoload :HttpRequest, 'unicorn/http_request'
21   autoload :HttpResponse, 'unicorn/http_response'
22   autoload :Configurator, 'unicorn/configurator'
23   autoload :TeeInput, 'unicorn/tee_input'
24   autoload :Util, 'unicorn/util'
26   class << self
27     def run(app, options = {})
28       HttpServer.new(app, options).start.join
29     end
30   end
32   # This is the process manager of Unicorn. This manages worker
33   # processes which in turn handle the I/O and application process.
34   # Listener sockets are started in the master process and shared with
35   # forked worker children.
37   class HttpServer < Struct.new(:listener_opts, :timeout, :worker_processes,
38                                 :before_fork, :after_fork, :before_exec,
39                                 :logger, :pid, :app, :preload_app,
40                                 :reexec_pid, :orig_app, :init_listeners,
41                                 :master_pid, :config)
42     include ::Unicorn::SocketHelper
44     # prevents IO objects in here from being GC-ed
45     IO_PURGATORY = []
47     # all bound listener sockets
48     LISTENERS = []
50     # This hash maps PIDs to Workers
51     WORKERS = {}
53     # We use SELF_PIPE differently in the master and worker processes:
54     #
55     # * The master process never closes or reinitializes this once
56     # initialized.  Signal handlers in the master process will write to
57     # it to wake up the master from IO.select in exactly the same manner
58     # djb describes in http://cr.yp.to/docs/selfpipe.html
59     #
60     # * The workers immediately close the pipe they inherit from the
61     # master and replace it with a new pipe after forking.  This new
62     # pipe is also used to wakeup from IO.select from inside (worker)
63     # signal handlers.  However, workers *close* the pipe descriptors in
64     # the signal handlers to raise EBADF in IO.select instead of writing
65     # like we do in the master.  We cannot easily use the reader set for
66     # IO.select because LISTENERS is already that set, and it's extra
67     # work (and cycles) to distinguish the pipe FD from the reader set
68     # once IO.select returns.  So we're lazy and just close the pipe when
69     # a (rare) signal arrives in the worker and reinitialize the pipe later.
70     SELF_PIPE = []
72     # signal queue used for self-piping
73     SIG_QUEUE = []
75     # constant lookups are faster and we're single-threaded/non-reentrant
76     REQUEST = HttpRequest.new
78     # We populate this at startup so we can figure out how to reexecute
79     # and upgrade the currently running instance of Unicorn
80     # This Hash is considered a stable interface and changing its contents
81     # will allow you to switch between different installations of Unicorn
82     # or even different installations of the same applications without
83     # downtime.  Keys of this constant Hash are described as follows:
84     #
85     # * 0 - the path to the unicorn/unicorn_rails executable
86     # * :argv - a deep copy of the ARGV array the executable originally saw
87     # * :cwd - the working directory of the application, this is where
88     # you originally started Unicorn.
89     #
90     # The following example may be used in your Unicorn config file to
91     # change your working directory during a config reload (HUP) without
92     # upgrading or restarting:
93     #
94     #   Dir.chdir(Unicorn::HttpServer::START_CTX[:cwd] = path)
95     #
96     # To change your unicorn executable to a different path without downtime,
97     # you can set the following in your Unicorn config file, HUP and then
98     # continue with the traditional USR2 + QUIT upgrade steps:
99     #
100     #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
101     START_CTX = {
102       :argv => ARGV.map { |arg| arg.dup },
103       :cwd => lambda {
104           # favor ENV['PWD'] since it is (usually) symlink aware for
105           # Capistrano and like systems
106           begin
107             a = File.stat(pwd = ENV['PWD'])
108             b = File.stat(Dir.pwd)
109             a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
110           rescue
111             Dir.pwd
112           end
113         }.call,
114       0 => $0.dup,
115     }
117     # This class and its members can be considered a stable interface
118     # and will not change in a backwards-incompatible fashion between
119     # releases of Unicorn.  You may need to access it in the
120     # before_fork/after_fork hooks.  See the Unicorn::Configurator RDoc
121     # for examples.
122     class Worker < Struct.new(:nr, :tmp)
124       autoload :Etc, 'etc'
126       # worker objects may be compared to just plain numbers
127       def ==(other_nr)
128         self.nr == other_nr
129       end
131       # Changes the worker process to the specified +user+ and +group+
132       # This is only intended to be called from within the worker
133       # process from the +after_fork+ hook.  This should be called in
134       # the +after_fork+ hook after any priviledged functions need to be
135       # run (e.g. to set per-worker CPU affinity, niceness, etc)
136       #
137       # Any and all errors raised within this method will be propagated
138       # directly back to the caller (usually the +after_fork+ hook.
139       # These errors commonly include ArgumentError for specifying an
140       # invalid user/group and Errno::EPERM for insufficient priviledges
141       def user(user, group = nil)
142         # we do not protect the caller, checking Process.euid == 0 is
143         # insufficient because modern systems have fine-grained
144         # capabilities.  Let the caller handle any and all errors.
145         uid = Etc.getpwnam(user).uid
146         gid = Etc.getgrnam(group).gid if group
147         Unicorn::Util.chown_logs(uid, gid)
148         tmp.chown(uid, gid)
149         if gid && Process.egid != gid
150           Process.initgroups(user, gid)
151           Process::GID.change_privilege(gid)
152         end
153         Process.euid != uid and Process::UID.change_privilege(uid)
154       end
156     end
158     # Creates a working server on host:port (strange things happen if
159     # port isn't a Number).  Use HttpServer::run to start the server and
160     # HttpServer.run.join to join the thread that's processing
161     # incoming requests on the socket.
162     def initialize(app, options = {})
163       self.app = app
164       self.reexec_pid = 0
165       self.init_listeners = options[:listeners] ? options[:listeners].dup : []
166       self.config = Configurator.new(options.merge(:use_defaults => true))
167       self.listener_opts = {}
169       # we try inheriting listeners first, so we bind them later.
170       # we don't write the pid file until we've bound listeners in case
171       # unicorn was started twice by mistake.  Even though our #pid= method
172       # checks for stale/existing pid files, race conditions are still
173       # possible (and difficult/non-portable to avoid) and can be likely
174       # to clobber the pid if the second start was in quick succession
175       # after the first, so we rely on the listener binding to fail in
176       # that case.  Some tests (in and outside of this source tree) and
177       # monitoring tools may also rely on pid files existing before we
178       # attempt to connect to the listener(s)
179       config.commit!(self, :skip => [:listeners, :pid])
180       self.orig_app = app
181     end
183     # Runs the thing.  Returns self so you can run join on it
184     def start
185       BasicSocket.do_not_reverse_lookup = true
187       # inherit sockets from parents, they need to be plain Socket objects
188       # before they become UNIXServer or TCPServer
189       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
190         io = Socket.for_fd(fd.to_i)
191         set_server_sockopt(io, listener_opts[sock_name(io)])
192         IO_PURGATORY << io
193         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
194         server_cast(io)
195       end
197       config_listeners = config[:listeners].dup
198       LISTENERS.replace(inherited)
200       # we start out with generic Socket objects that get cast to either
201       # TCPServer or UNIXServer objects; but since the Socket objects
202       # share the same OS-level file descriptor as the higher-level *Server
203       # objects; we need to prevent Socket objects from being garbage-collected
204       config_listeners -= listener_names
205       if config_listeners.empty? && LISTENERS.empty?
206         config_listeners << Unicorn::Const::DEFAULT_LISTEN
207         init_listeners << Unicorn::Const::DEFAULT_LISTEN
208         START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
209       end
210       config_listeners.each { |addr| listen(addr) }
211       raise ArgumentError, "no listeners" if LISTENERS.empty?
212       self.pid = config[:pid]
213       self.master_pid = $$
214       build_app! if preload_app
215       maintain_worker_count
216       self
217     end
219     # replaces current listener set with +listeners+.  This will
220     # close the socket if it will not exist in the new listener set
221     def listeners=(listeners)
222       cur_names, dead_names = [], []
223       listener_names.each do |name|
224         if ?/ == name[0]
225           # mark unlinked sockets as dead so we can rebind them
226           (File.socket?(name) ? cur_names : dead_names) << name
227         else
228           cur_names << name
229         end
230       end
231       set_names = listener_names(listeners)
232       dead_names.concat(cur_names - set_names).uniq!
234       LISTENERS.delete_if do |io|
235         if dead_names.include?(sock_name(io))
236           IO_PURGATORY.delete_if do |pio|
237             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
238           end
239           (io.close rescue nil).nil? # true
240         else
241           set_server_sockopt(io, listener_opts[sock_name(io)])
242           false
243         end
244       end
246       (set_names - cur_names).each { |addr| listen(addr) }
247     end
249     def stdout_path=(path); redirect_io($stdout, path); end
250     def stderr_path=(path); redirect_io($stderr, path); end
252     alias_method :set_pid, :pid=
253     undef_method :pid=
255     # sets the path for the PID file of the master process
256     def pid=(path)
257       if path
258         if x = valid_pid?(path)
259           return path if pid && path == pid && x == $$
260           raise ArgumentError, "Already running on PID:#{x} " \
261                                "(or pid=#{path} is stale)"
262         end
263       end
264       unlink_pid_safe(pid) if pid
266       if path
267         fp = begin
268           tmp = "#{File.dirname(path)}/#{rand}.#$$"
269           File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
270         rescue Errno::EEXIST
271           retry
272         end
273         fp.syswrite("#$$\n")
274         File.rename(fp.path, path)
275         fp.close
276       end
277       self.set_pid(path)
278     end
280     # add a given address to the +listeners+ set, idempotently
281     # Allows workers to add a private, per-process listener via the
282     # after_fork hook.  Very useful for debugging and testing.
283     # +:tries+ may be specified as an option for the number of times
284     # to retry, and +:delay+ may be specified as the time in seconds
285     # to delay between retries.
286     # A negative value for +:tries+ indicates the listen will be
287     # retried indefinitely, this is useful when workers belonging to
288     # different masters are spawned during a transparent upgrade.
289     def listen(address, opt = {}.merge(listener_opts[address] || {}))
290       address = config.expand_addr(address)
291       return if String === address && listener_names.include?(address)
293       delay = opt[:delay] || 0.5
294       tries = opt[:tries] || 5
295       begin
296         io = bind_listen(address, opt)
297         unless TCPServer === io || UNIXServer === io
298           IO_PURGATORY << io
299           io = server_cast(io)
300         end
301         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
302         LISTENERS << io
303         return io
304       rescue Errno::EADDRINUSE => err
305         logger.error "adding listener failed addr=#{address} (in use)"
306         raise err if tries == 0
307         tries -= 1
308         logger.error "retrying in #{delay} seconds " \
309                      "(#{tries < 0 ? 'infinite' : tries} tries left)"
310         sleep(delay)
311         retry
312       end
313     end
315     # monitors children and receives signals forever
316     # (or until a termination signal is sent).  This handles signals
317     # one-at-a-time time and we'll happily drop signals in case somebody
318     # is signalling us too often.
319     def join
320       # this pipe is used to wake us up from select(2) in #join when signals
321       # are trapped.  See trap_deferred
322       init_self_pipe!
323       respawn = true
324       last_check = Time.now
326       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
327       trap(:CHLD) { |sig_nr| awaken_master }
328       proc_name 'master'
329       logger.info "master process ready" # test_exec.rb relies on this message
330       begin
331         loop do
332           reap_all_workers
333           case SIG_QUEUE.shift
334           when nil
335             # avoid murdering workers after our master process (or the
336             # machine) comes out of suspend/hibernation
337             if (last_check + timeout) >= (last_check = Time.now)
338               murder_lazy_workers
339             end
340             maintain_worker_count if respawn
341             master_sleep
342           when :QUIT # graceful shutdown
343             break
344           when :TERM, :INT # immediate shutdown
345             stop(false)
346             break
347           when :USR1 # rotate logs
348             logger.info "master reopening logs..."
349             Unicorn::Util.reopen_logs
350             logger.info "master done reopening logs"
351             kill_each_worker(:USR1)
352           when :USR2 # exec binary, stay alive in case something went wrong
353             reexec
354           when :WINCH
355             if Process.ppid == 1 || Process.getpgrp != $$
356               respawn = false
357               logger.info "gracefully stopping all workers"
358               kill_each_worker(:QUIT)
359             else
360               logger.info "SIGWINCH ignored because we're not daemonized"
361             end
362           when :TTIN
363             self.worker_processes += 1
364           when :TTOU
365             self.worker_processes -= 1 if self.worker_processes > 0
366           when :HUP
367             respawn = true
368             if config.config_file
369               load_config!
370               redo # immediate reaping since we may have QUIT workers
371             else # exec binary and exit if there's no config file
372               logger.info "config_file not present, reexecuting binary"
373               reexec
374               break
375             end
376           end
377         end
378       rescue Errno::EINTR
379         retry
380       rescue => e
381         logger.error "Unhandled master loop exception #{e.inspect}."
382         logger.error e.backtrace.join("\n")
383         retry
384       end
385       stop # gracefully shutdown all workers on our way out
386       logger.info "master complete"
387       unlink_pid_safe(pid) if pid
388     end
390     # Terminates all workers, but does not exit master process
391     def stop(graceful = true)
392       self.listeners = []
393       limit = Time.now + timeout
394       until WORKERS.empty? || Time.now > limit
395         kill_each_worker(graceful ? :QUIT : :TERM)
396         sleep(0.1)
397         reap_all_workers
398       end
399       kill_each_worker(:KILL)
400     end
402     private
404     # list of signals we care about and trap in master.
405     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
406                    :TTIN, :TTOU ]
408     # defer a signal for later processing in #join (master process)
409     def trap_deferred(signal)
410       trap(signal) do |sig_nr|
411         if SIG_QUEUE.size < 5
412           SIG_QUEUE << signal
413           awaken_master
414         else
415           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
416         end
417       end
418     end
420     # wait for a signal hander to wake us up and then consume the pipe
421     # Wake up every second anyways to run murder_lazy_workers
422     def master_sleep
423       begin
424         ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
425         ready.first && ready.first.first or return
426         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
427       rescue Errno::EAGAIN, Errno::EINTR
428       end
429     end
431     def awaken_master
432       begin
433         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
434       rescue Errno::EAGAIN, Errno::EINTR
435         # pipe is full, master should wake up anyways
436         retry
437       end
438     end
440     # reaps all unreaped workers
441     def reap_all_workers
442       begin
443         loop do
444           wpid, status = Process.waitpid2(-1, Process::WNOHANG)
445           wpid or break
446           if reexec_pid == wpid
447             logger.error "reaped #{status.inspect} exec()-ed"
448             self.reexec_pid = 0
449             self.pid = pid.chomp('.oldbin') if pid
450             proc_name 'master'
451           else
452             worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
453             logger.info "reaped #{status.inspect} " \
454                         "worker=#{worker.nr rescue 'unknown'}"
455           end
456         end
457       rescue Errno::ECHILD
458       end
459     end
461     # reexecutes the START_CTX with a new binary
462     def reexec
463       if reexec_pid > 0
464         begin
465           Process.kill(0, reexec_pid)
466           logger.error "reexec-ed child already running PID:#{reexec_pid}"
467           return
468         rescue Errno::ESRCH
469           self.reexec_pid = 0
470         end
471       end
473       if pid
474         old_pid = "#{pid}.oldbin"
475         prev_pid = pid.dup
476         begin
477           self.pid = old_pid  # clear the path for a new pid file
478         rescue ArgumentError
479           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
480                        "existing pid=#{old_pid}, refusing rexec"
481           return
482         rescue => e
483           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
484           return
485         end
486       end
488       self.reexec_pid = fork do
489         listener_fds = LISTENERS.map { |sock| sock.fileno }
490         ENV['UNICORN_FD'] = listener_fds.join(',')
491         Dir.chdir(START_CTX[:cwd])
492         cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
494         # avoid leaking FDs we don't know about, but let before_exec
495         # unset FD_CLOEXEC, if anything else in the app eventually
496         # relies on FD inheritence.
497         (3..1024).each do |io|
498           next if listener_fds.include?(io)
499           io = IO.for_fd(io) rescue nil
500           io or next
501           IO_PURGATORY << io
502           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
503         end
504         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
505         before_exec.call(self)
506         exec(*cmd)
507       end
508       proc_name 'master (old)'
509     end
511     # forcibly terminate all workers that haven't checked in in timeout
512     # seconds.  The timeout is implemented using an unlinked File
513     # shared between the parent process and each worker.  The worker
514     # runs File#chmod to modify the ctime of the File.  If the ctime
515     # is stale for >timeout seconds, then we'll kill the corresponding
516     # worker.
517     def murder_lazy_workers
518       WORKERS.dup.each_pair do |wpid, worker|
519         stat = worker.tmp.stat
520         # skip workers that disable fchmod or have never fchmod-ed
521         stat.mode == 0100600 and next
522         (diff = (Time.now - stat.ctime)) <= timeout and next
523         logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
524                      "(#{diff}s > #{timeout}s), killing"
525         kill_worker(:KILL, wpid) # take no prisoners for timeout violations
526       end
527     end
529     def spawn_missing_workers
530       (0...worker_processes).each do |worker_nr|
531         WORKERS.values.include?(worker_nr) and next
532         worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
533         before_fork.call(self, worker)
534         WORKERS[fork { worker_loop(worker) }] = worker
535       end
536     end
538     def maintain_worker_count
539       (off = WORKERS.size - worker_processes) == 0 and return
540       off < 0 and return spawn_missing_workers
541       WORKERS.dup.each_pair { |wpid,w|
542         w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
543       }
544     end
546     # if we get any error, try to write something back to the client
547     # assuming we haven't closed the socket, but don't get hung up
548     # if the socket is already closed or broken.  We'll always ensure
549     # the socket is closed at the end of this function
550     def handle_error(client, e)
551       msg = case e
552       when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
553         Const::ERROR_500_RESPONSE
554       when HttpParserError # try to tell the client they're bad
555         Const::ERROR_400_RESPONSE
556       else
557         logger.error "Read error: #{e.inspect}"
558         logger.error e.backtrace.join("\n")
559         Const::ERROR_500_RESPONSE
560       end
561       client.write_nonblock(msg)
562       client.close
563       rescue
564         nil
565     end
567     # once a client is accepted, it is processed in its entirety here
568     # in 3 easy steps: read request, call app, write app response
569     def process_client(client)
570       client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
571       response = app.call(env = REQUEST.read(client))
573       if 100 == response.first.to_i
574         client.write(Const::EXPECT_100_RESPONSE)
575         env.delete(Const::HTTP_EXPECT)
576         response = app.call(env)
577       end
578       HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
579     rescue => e
580       handle_error(client, e)
581     end
583     # gets rid of stuff the worker has no business keeping track of
584     # to free some resources and drops all sig handlers.
585     # traps for USR1, USR2, and HUP may be set in the after_fork Proc
586     # by the user.
587     def init_worker_process(worker)
588       QUEUE_SIGS.each { |sig| trap(sig, nil) }
589       trap(:CHLD, 'DEFAULT')
590       SIG_QUEUE.clear
591       proc_name "worker[#{worker.nr}]"
592       START_CTX.clear
593       init_self_pipe!
594       WORKERS.values.each { |other| other.tmp.close rescue nil }
595       WORKERS.clear
596       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
597       worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
598       after_fork.call(self, worker) # can drop perms
599       self.timeout /= 2.0 # halve it for select()
600       build_app! unless preload_app
601     end
603     def reopen_worker_logs(worker_nr)
604       logger.info "worker=#{worker_nr} reopening logs..."
605       Unicorn::Util.reopen_logs
606       logger.info "worker=#{worker_nr} done reopening logs"
607       init_self_pipe!
608     end
610     # runs inside each forked worker, this sits around and waits
611     # for connections and doesn't die until the parent dies (or is
612     # given a INT, QUIT, or TERM signal)
613     def worker_loop(worker)
614       ppid = master_pid
615       init_worker_process(worker)
616       nr = 0 # this becomes negative if we need to reopen logs
617       alive = worker.tmp # tmp is our lifeline to the master process
618       ready = LISTENERS
620       # closing anything we IO.select on will raise EBADF
621       trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
622       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
623       [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
624       logger.info "worker=#{worker.nr} ready"
625       m = 0
627       begin
628         nr < 0 and reopen_worker_logs(worker.nr)
629         nr = 0
631         # we're a goner in timeout seconds anyways if alive.chmod
632         # breaks, so don't trap the exception.  Using fchmod() since
633         # futimes() is not available in base Ruby and I very strongly
634         # prefer temporary files to be unlinked for security,
635         # performance and reliability reasons, so utime is out.  No-op
636         # changes with chmod doesn't update ctime on all filesystems; so
637         # we change our counter each and every time (after process_client
638         # and before IO.select).
639         alive.chmod(m = 0 == m ? 1 : 0)
641         ready.each do |sock|
642           begin
643             process_client(sock.accept_nonblock)
644             nr += 1
645             alive.chmod(m = 0 == m ? 1 : 0)
646           rescue Errno::EAGAIN, Errno::ECONNABORTED
647           end
648           break if nr < 0
649         end
651         # make the following bet: if we accepted clients this round,
652         # we're probably reasonably busy, so avoid calling select()
653         # and do a speculative accept_nonblock on ready listeners
654         # before we sleep again in select().
655         redo unless nr == 0 # (nr < 0) => reopen logs
657         ppid == Process.ppid or return
658         alive.chmod(m = 0 == m ? 1 : 0)
659         begin
660           # timeout used so we can detect parent death:
661           ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
662           ready = ret.first
663         rescue Errno::EINTR
664           ready = LISTENERS
665         rescue Errno::EBADF
666           nr < 0 or return
667         end
668       rescue => e
669         if alive
670           logger.error "Unhandled listen loop exception #{e.inspect}."
671           logger.error e.backtrace.join("\n")
672         end
673       end while alive
674     end
676     # delivers a signal to a worker and fails gracefully if the worker
677     # is no longer running.
678     def kill_worker(signal, wpid)
679       begin
680         Process.kill(signal, wpid)
681       rescue Errno::ESRCH
682         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
683       end
684     end
686     # delivers a signal to each worker
687     def kill_each_worker(signal)
688       WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
689     end
691     # unlinks a PID file at given +path+ if it contains the current PID
692     # still potentially racy without locking the directory (which is
693     # non-portable and may interact badly with other programs), but the
694     # window for hitting the race condition is small
695     def unlink_pid_safe(path)
696       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
697     end
699     # returns a PID if a given path contains a non-stale PID file,
700     # nil otherwise.
701     def valid_pid?(path)
702       wpid = File.read(path).to_i
703       wpid <= 0 and return nil
704       begin
705         Process.kill(0, wpid)
706         return wpid
707       rescue Errno::ESRCH
708         # don't unlink stale pid files, racy without non-portable locking...
709       end
710       rescue Errno::ENOENT
711     end
713     def load_config!
714       begin
715         logger.info "reloading config_file=#{config.config_file}"
716         config[:listeners].replace(init_listeners)
717         config.reload
718         config.commit!(self)
719         kill_each_worker(:QUIT)
720         Unicorn::Util.reopen_logs
721         self.app = orig_app
722         build_app! if preload_app
723         logger.info "done reloading config_file=#{config.config_file}"
724       rescue => e
725         logger.error "error reloading config_file=#{config.config_file}: " \
726                      "#{e.class} #{e.message}"
727       end
728     end
730     # returns an array of string names for the given listener array
731     def listener_names(listeners = LISTENERS)
732       listeners.map { |io| sock_name(io) }
733     end
735     def build_app!
736       if app.respond_to?(:arity) && app.arity == 0
737         # exploit COW in case of preload_app.  Also avoids race
738         # conditions in Rainbows! since load/require are not thread-safe
739         Unicorn.constants.each { |x| Unicorn.const_get(x) }
741         if defined?(Gem) && Gem.respond_to?(:refresh)
742           logger.info "Refreshing Gem list"
743           Gem.refresh
744         end
745         self.app = app.call
746       end
747     end
749     def proc_name(tag)
750       $0 = ([ File.basename(START_CTX[0]), tag
751             ]).concat(START_CTX[:argv]).join(' ')
752     end
754     def redirect_io(io, path)
755       File.open(path, 'ab') { |fp| io.reopen(fp) } if path
756       io.sync = true
757     end
759     def init_self_pipe!
760       SELF_PIPE.each { |io| io.close rescue nil }
761       SELF_PIPE.replace(IO.pipe)
762       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
763     end
765   end