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