initialize signal handlers before writing pid file
[unicorn.git] / lib / unicorn.rb
blobe3e4315d43cd412b4fb04d825698aaba88837af1
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, :ready_pipe)
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.ready_pipe = options.delete(:ready_pipe)
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?
214       # this pipe is used to wake us up from select(2) in #join when signals
215       # are trapped.  See trap_deferred.
216       init_self_pipe!
218       # setup signal handlers before writing pid file in case people get
219       # trigger happy and send signals as soon as the pid file exists.
220       # Note that signals don't actually get handled until the #join method
221       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
222       trap(:CHLD) { |_| awaken_master }
223       self.pid = config[:pid]
225       self.master_pid = $$
226       build_app! if preload_app
227       maintain_worker_count
228       self
229     end
231     # replaces current listener set with +listeners+.  This will
232     # close the socket if it will not exist in the new listener set
233     def listeners=(listeners)
234       cur_names, dead_names = [], []
235       listener_names.each do |name|
236         if ?/ == name[0]
237           # mark unlinked sockets as dead so we can rebind them
238           (File.socket?(name) ? cur_names : dead_names) << name
239         else
240           cur_names << name
241         end
242       end
243       set_names = listener_names(listeners)
244       dead_names.concat(cur_names - set_names).uniq!
246       LISTENERS.delete_if do |io|
247         if dead_names.include?(sock_name(io))
248           IO_PURGATORY.delete_if do |pio|
249             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
250           end
251           (io.close rescue nil).nil? # true
252         else
253           set_server_sockopt(io, listener_opts[sock_name(io)])
254           false
255         end
256       end
258       (set_names - cur_names).each { |addr| listen(addr) }
259     end
261     def stdout_path=(path); redirect_io($stdout, path); end
262     def stderr_path=(path); redirect_io($stderr, path); end
264     def logger=(obj)
265       HttpRequest::DEFAULTS["rack.logger"] = super
266     end
268     # sets the path for the PID file of the master process
269     def pid=(path)
270       if path
271         if x = valid_pid?(path)
272           return path if pid && path == pid && x == $$
273           raise ArgumentError, "Already running on PID:#{x} " \
274                                "(or pid=#{path} is stale)"
275         end
276       end
277       unlink_pid_safe(pid) if pid
279       if path
280         fp = begin
281           tmp = "#{File.dirname(path)}/#{rand}.#$$"
282           File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
283         rescue Errno::EEXIST
284           retry
285         end
286         fp.syswrite("#$$\n")
287         File.rename(fp.path, path)
288         fp.close
289       end
290       super(path)
291     end
293     # add a given address to the +listeners+ set, idempotently
294     # Allows workers to add a private, per-process listener via the
295     # after_fork hook.  Very useful for debugging and testing.
296     # +:tries+ may be specified as an option for the number of times
297     # to retry, and +:delay+ may be specified as the time in seconds
298     # to delay between retries.
299     # A negative value for +:tries+ indicates the listen will be
300     # retried indefinitely, this is useful when workers belonging to
301     # different masters are spawned during a transparent upgrade.
302     def listen(address, opt = {}.merge(listener_opts[address] || {}))
303       address = config.expand_addr(address)
304       return if String === address && listener_names.include?(address)
306       delay = opt[:delay] || 0.5
307       tries = opt[:tries] || 5
308       begin
309         io = bind_listen(address, opt)
310         unless TCPServer === io || UNIXServer === io
311           IO_PURGATORY << io
312           io = server_cast(io)
313         end
314         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
315         LISTENERS << io
316         io
317       rescue Errno::EADDRINUSE => err
318         logger.error "adding listener failed addr=#{address} (in use)"
319         raise err if tries == 0
320         tries -= 1
321         logger.error "retrying in #{delay} seconds " \
322                      "(#{tries < 0 ? 'infinite' : tries} tries left)"
323         sleep(delay)
324         retry
325       rescue => err
326         logger.fatal "error adding listener addr=#{address}"
327         raise err
328       end
329     end
331     # monitors children and receives signals forever
332     # (or until a termination signal is sent).  This handles signals
333     # one-at-a-time time and we'll happily drop signals in case somebody
334     # is signalling us too often.
335     def join
336       respawn = true
337       last_check = Time.now
339       proc_name 'master'
340       logger.info "master process ready" # test_exec.rb relies on this message
341       if ready_pipe
342         ready_pipe.syswrite($$.to_s)
343         ready_pipe.close rescue nil
344         self.ready_pipe = nil
345       end
346       begin
347         loop do
348           reap_all_workers
349           case SIG_QUEUE.shift
350           when nil
351             # avoid murdering workers after our master process (or the
352             # machine) comes out of suspend/hibernation
353             if (last_check + timeout) >= (last_check = Time.now)
354               murder_lazy_workers
355             end
356             maintain_worker_count if respawn
357             master_sleep
358           when :QUIT # graceful shutdown
359             break
360           when :TERM, :INT # immediate shutdown
361             stop(false)
362             break
363           when :USR1 # rotate logs
364             logger.info "master reopening logs..."
365             Unicorn::Util.reopen_logs
366             logger.info "master done reopening logs"
367             kill_each_worker(:USR1)
368           when :USR2 # exec binary, stay alive in case something went wrong
369             reexec
370           when :WINCH
371             if Process.ppid == 1 || Process.getpgrp != $$
372               respawn = false
373               logger.info "gracefully stopping all workers"
374               kill_each_worker(:QUIT)
375             else
376               logger.info "SIGWINCH ignored because we're not daemonized"
377             end
378           when :TTIN
379             self.worker_processes += 1
380           when :TTOU
381             self.worker_processes -= 1 if self.worker_processes > 0
382           when :HUP
383             respawn = true
384             if config.config_file
385               load_config!
386               redo # immediate reaping since we may have QUIT workers
387             else # exec binary and exit if there's no config file
388               logger.info "config_file not present, reexecuting binary"
389               reexec
390               break
391             end
392           end
393         end
394       rescue Errno::EINTR
395         retry
396       rescue => e
397         logger.error "Unhandled master loop exception #{e.inspect}."
398         logger.error e.backtrace.join("\n")
399         retry
400       end
401       stop # gracefully shutdown all workers on our way out
402       logger.info "master complete"
403       unlink_pid_safe(pid) if pid
404     end
406     # Terminates all workers, but does not exit master process
407     def stop(graceful = true)
408       self.listeners = []
409       limit = Time.now + timeout
410       until WORKERS.empty? || Time.now > limit
411         kill_each_worker(graceful ? :QUIT : :TERM)
412         sleep(0.1)
413         reap_all_workers
414       end
415       kill_each_worker(:KILL)
416     end
418     private
420     # list of signals we care about and trap in master.
421     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
422                    :TTIN, :TTOU ]
424     # defer a signal for later processing in #join (master process)
425     def trap_deferred(signal)
426       trap(signal) do |sig_nr|
427         if SIG_QUEUE.size < 5
428           SIG_QUEUE << signal
429           awaken_master
430         else
431           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
432         end
433       end
434     end
436     # wait for a signal hander to wake us up and then consume the pipe
437     # Wake up every second anyways to run murder_lazy_workers
438     def master_sleep
439       begin
440         ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
441         ready.first && ready.first.first or return
442         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
443       rescue Errno::EAGAIN, Errno::EINTR
444       end
445     end
447     def awaken_master
448       begin
449         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
450       rescue Errno::EAGAIN, Errno::EINTR
451         # pipe is full, master should wake up anyways
452         retry
453       end
454     end
456     # reaps all unreaped workers
457     def reap_all_workers
458       begin
459         loop do
460           wpid, status = Process.waitpid2(-1, Process::WNOHANG)
461           wpid or break
462           if reexec_pid == wpid
463             logger.error "reaped #{status.inspect} exec()-ed"
464             self.reexec_pid = 0
465             self.pid = pid.chomp('.oldbin') if pid
466             proc_name 'master'
467           else
468             worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
469             logger.info "reaped #{status.inspect} " \
470                         "worker=#{worker.nr rescue 'unknown'}"
471           end
472         end
473       rescue Errno::ECHILD
474       end
475     end
477     # reexecutes the START_CTX with a new binary
478     def reexec
479       if reexec_pid > 0
480         begin
481           Process.kill(0, reexec_pid)
482           logger.error "reexec-ed child already running PID:#{reexec_pid}"
483           return
484         rescue Errno::ESRCH
485           self.reexec_pid = 0
486         end
487       end
489       if pid
490         old_pid = "#{pid}.oldbin"
491         prev_pid = pid.dup
492         begin
493           self.pid = old_pid  # clear the path for a new pid file
494         rescue ArgumentError
495           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
496                        "existing pid=#{old_pid}, refusing rexec"
497           return
498         rescue => e
499           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
500           return
501         end
502       end
504       self.reexec_pid = fork do
505         listener_fds = LISTENERS.map { |sock| sock.fileno }
506         ENV['UNICORN_FD'] = listener_fds.join(',')
507         Dir.chdir(START_CTX[:cwd])
508         cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
510         # avoid leaking FDs we don't know about, but let before_exec
511         # unset FD_CLOEXEC, if anything else in the app eventually
512         # relies on FD inheritence.
513         (3..1024).each do |io|
514           next if listener_fds.include?(io)
515           io = IO.for_fd(io) rescue nil
516           io or next
517           IO_PURGATORY << io
518           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
519         end
520         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
521         before_exec.call(self)
522         exec(*cmd)
523       end
524       proc_name 'master (old)'
525     end
527     # forcibly terminate all workers that haven't checked in in timeout
528     # seconds.  The timeout is implemented using an unlinked File
529     # shared between the parent process and each worker.  The worker
530     # runs File#chmod to modify the ctime of the File.  If the ctime
531     # is stale for >timeout seconds, then we'll kill the corresponding
532     # worker.
533     def murder_lazy_workers
534       WORKERS.dup.each_pair do |wpid, worker|
535         stat = worker.tmp.stat
536         # skip workers that disable fchmod or have never fchmod-ed
537         stat.mode == 0100600 and next
538         (diff = (Time.now - stat.ctime)) <= timeout and next
539         logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
540                      "(#{diff}s > #{timeout}s), killing"
541         kill_worker(:KILL, wpid) # take no prisoners for timeout violations
542       end
543     end
545     def spawn_missing_workers
546       (0...worker_processes).each do |worker_nr|
547         WORKERS.values.include?(worker_nr) and next
548         worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
549         before_fork.call(self, worker)
550         WORKERS[fork {
551           ready_pipe.close if ready_pipe
552           self.ready_pipe = nil
553           worker_loop(worker)
554         }] = worker
555       end
556     end
558     def maintain_worker_count
559       (off = WORKERS.size - worker_processes) == 0 and return
560       off < 0 and return spawn_missing_workers
561       WORKERS.dup.each_pair { |wpid,w|
562         w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
563       }
564     end
566     # if we get any error, try to write something back to the client
567     # assuming we haven't closed the socket, but don't get hung up
568     # if the socket is already closed or broken.  We'll always ensure
569     # the socket is closed at the end of this function
570     def handle_error(client, e)
571       msg = case e
572       when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
573         Const::ERROR_500_RESPONSE
574       when HttpParserError # try to tell the client they're bad
575         Const::ERROR_400_RESPONSE
576       else
577         logger.error "Read error: #{e.inspect}"
578         logger.error e.backtrace.join("\n")
579         Const::ERROR_500_RESPONSE
580       end
581       client.write_nonblock(msg)
582       client.close
583       rescue
584         nil
585     end
587     # once a client is accepted, it is processed in its entirety here
588     # in 3 easy steps: read request, call app, write app response
589     def process_client(client)
590       client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
591       response = app.call(env = REQUEST.read(client))
593       if 100 == response.first.to_i
594         client.write(Const::EXPECT_100_RESPONSE)
595         env.delete(Const::HTTP_EXPECT)
596         response = app.call(env)
597       end
598       HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
599     rescue => e
600       handle_error(client, e)
601     end
603     # gets rid of stuff the worker has no business keeping track of
604     # to free some resources and drops all sig handlers.
605     # traps for USR1, USR2, and HUP may be set in the after_fork Proc
606     # by the user.
607     def init_worker_process(worker)
608       QUEUE_SIGS.each { |sig| trap(sig, nil) }
609       trap(:CHLD, 'DEFAULT')
610       SIG_QUEUE.clear
611       proc_name "worker[#{worker.nr}]"
612       START_CTX.clear
613       init_self_pipe!
614       WORKERS.values.each { |other| other.tmp.close rescue nil }
615       WORKERS.clear
616       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
617       worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
618       after_fork.call(self, worker) # can drop perms
619       self.timeout /= 2.0 # halve it for select()
620       build_app! unless preload_app
621     end
623     def reopen_worker_logs(worker_nr)
624       logger.info "worker=#{worker_nr} reopening logs..."
625       Unicorn::Util.reopen_logs
626       logger.info "worker=#{worker_nr} done reopening logs"
627       init_self_pipe!
628     end
630     # runs inside each forked worker, this sits around and waits
631     # for connections and doesn't die until the parent dies (or is
632     # given a INT, QUIT, or TERM signal)
633     def worker_loop(worker)
634       ppid = master_pid
635       init_worker_process(worker)
636       nr = 0 # this becomes negative if we need to reopen logs
637       alive = worker.tmp # tmp is our lifeline to the master process
638       ready = LISTENERS
640       # closing anything we IO.select on will raise EBADF
641       trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
642       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
643       [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
644       logger.info "worker=#{worker.nr} ready"
645       m = 0
647       begin
648         nr < 0 and reopen_worker_logs(worker.nr)
649         nr = 0
651         # we're a goner in timeout seconds anyways if alive.chmod
652         # breaks, so don't trap the exception.  Using fchmod() since
653         # futimes() is not available in base Ruby and I very strongly
654         # prefer temporary files to be unlinked for security,
655         # performance and reliability reasons, so utime is out.  No-op
656         # changes with chmod doesn't update ctime on all filesystems; so
657         # we change our counter each and every time (after process_client
658         # and before IO.select).
659         alive.chmod(m = 0 == m ? 1 : 0)
661         ready.each do |sock|
662           begin
663             process_client(sock.accept_nonblock)
664             nr += 1
665             alive.chmod(m = 0 == m ? 1 : 0)
666           rescue Errno::EAGAIN, Errno::ECONNABORTED
667           end
668           break if nr < 0
669         end
671         # make the following bet: if we accepted clients this round,
672         # we're probably reasonably busy, so avoid calling select()
673         # and do a speculative accept_nonblock on ready listeners
674         # before we sleep again in select().
675         redo unless nr == 0 # (nr < 0) => reopen logs
677         ppid == Process.ppid or return
678         alive.chmod(m = 0 == m ? 1 : 0)
679         begin
680           # timeout used so we can detect parent death:
681           ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
682           ready = ret.first
683         rescue Errno::EINTR
684           ready = LISTENERS
685         rescue Errno::EBADF
686           nr < 0 or return
687         end
688       rescue => e
689         if alive
690           logger.error "Unhandled listen loop exception #{e.inspect}."
691           logger.error e.backtrace.join("\n")
692         end
693       end while alive
694     end
696     # delivers a signal to a worker and fails gracefully if the worker
697     # is no longer running.
698     def kill_worker(signal, wpid)
699       begin
700         Process.kill(signal, wpid)
701       rescue Errno::ESRCH
702         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
703       end
704     end
706     # delivers a signal to each worker
707     def kill_each_worker(signal)
708       WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
709     end
711     # unlinks a PID file at given +path+ if it contains the current PID
712     # still potentially racy without locking the directory (which is
713     # non-portable and may interact badly with other programs), but the
714     # window for hitting the race condition is small
715     def unlink_pid_safe(path)
716       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
717     end
719     # returns a PID if a given path contains a non-stale PID file,
720     # nil otherwise.
721     def valid_pid?(path)
722       wpid = File.read(path).to_i
723       wpid <= 0 and return nil
724       begin
725         Process.kill(0, wpid)
726         wpid
727       rescue Errno::ESRCH
728         # don't unlink stale pid files, racy without non-portable locking...
729       end
730       rescue Errno::ENOENT
731     end
733     def load_config!
734       begin
735         logger.info "reloading config_file=#{config.config_file}"
736         config[:listeners].replace(init_listeners)
737         config.reload
738         config.commit!(self)
739         kill_each_worker(:QUIT)
740         Unicorn::Util.reopen_logs
741         self.app = orig_app
742         build_app! if preload_app
743         logger.info "done reloading config_file=#{config.config_file}"
744       rescue => e
745         logger.error "error reloading config_file=#{config.config_file}: " \
746                      "#{e.class} #{e.message}"
747       end
748     end
750     # returns an array of string names for the given listener array
751     def listener_names(listeners = LISTENERS)
752       listeners.map { |io| sock_name(io) }
753     end
755     def build_app!
756       if app.respond_to?(:arity) && app.arity == 0
757         # exploit COW in case of preload_app.  Also avoids race
758         # conditions in Rainbows! since load/require are not thread-safe
759         Unicorn.constants.each { |x| Unicorn.const_get(x) }
761         if defined?(Gem) && Gem.respond_to?(:refresh)
762           logger.info "Refreshing Gem list"
763           Gem.refresh
764         end
765         self.app = app.call
766       end
767     end
769     def proc_name(tag)
770       $0 = ([ File.basename(START_CTX[0]), tag
771             ]).concat(START_CTX[:argv]).join(' ')
772     end
774     def redirect_io(io, path)
775       File.open(path, 'ab') { |fp| io.reopen(fp) } if path
776       io.sync = true
777     end
779     def init_self_pipe!
780       SELF_PIPE.each { |io| io.close rescue nil }
781       SELF_PIPE.replace(IO.pipe)
782       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
783     end
785   end