http_server: a few more things eligible for GC in worker
[unicorn.git] / lib / unicorn / http_server.rb
blob95f0e6ecb8a5bdd79e7b7c1988de915f347755a1
1 # -*- encoding: binary -*-
3 # This is the process manager of Unicorn. This manages worker
4 # processes which in turn handle the I/O and application process.
5 # Listener sockets are started in the master process and shared with
6 # forked worker children.
8 # Users do not need to know the internals of this class, but reading the
9 # {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb]
10 # is education for programmers wishing to learn how \Unicorn works.
11 # See Unicorn::Configurator for information on how to configure \Unicorn.
12 class Unicorn::HttpServer
13   # :stopdoc:
14   attr_accessor :app, :request, :timeout, :worker_processes,
15                 :before_fork, :after_fork, :before_exec,
16                 :listener_opts, :preload_app,
17                 :reexec_pid, :orig_app, :init_listeners,
18                 :master_pid, :config, :ready_pipe, :user
19   attr_reader :pid, :logger
20   include Unicorn::SocketHelper
21   include Unicorn::HttpResponse
23   # backwards compatibility with 1.x
24   Worker = Unicorn::Worker
26   # all bound listener sockets
27   LISTENERS = []
29   # This hash maps PIDs to Workers
30   WORKERS = {}
32   # We use SELF_PIPE differently in the master and worker processes:
33   #
34   # * The master process never closes or reinitializes this once
35   # initialized.  Signal handlers in the master process will write to
36   # it to wake up the master from IO.select in exactly the same manner
37   # djb describes in http://cr.yp.to/docs/selfpipe.html
38   #
39   # * The workers immediately close the pipe they inherit from the
40   # master and replace it with a new pipe after forking.  This new
41   # pipe is also used to wakeup from IO.select from inside (worker)
42   # signal handlers.  However, workers *close* the pipe descriptors in
43   # the signal handlers to raise EBADF in IO.select instead of writing
44   # like we do in the master.  We cannot easily use the reader set for
45   # IO.select because LISTENERS is already that set, and it's extra
46   # work (and cycles) to distinguish the pipe FD from the reader set
47   # once IO.select returns.  So we're lazy and just close the pipe when
48   # a (rare) signal arrives in the worker and reinitialize the pipe later.
49   SELF_PIPE = []
51   # signal queue used for self-piping
52   SIG_QUEUE = []
54   # list of signals we care about and trap in master.
55   QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
57   # :startdoc:
58   # We populate this at startup so we can figure out how to reexecute
59   # and upgrade the currently running instance of Unicorn
60   # This Hash is considered a stable interface and changing its contents
61   # will allow you to switch between different installations of Unicorn
62   # or even different installations of the same applications without
63   # downtime.  Keys of this constant Hash are described as follows:
64   #
65   # * 0 - the path to the unicorn/unicorn_rails executable
66   # * :argv - a deep copy of the ARGV array the executable originally saw
67   # * :cwd - the working directory of the application, this is where
68   # you originally started Unicorn.
69   #
70   # To change your unicorn executable to a different path without downtime,
71   # you can set the following in your Unicorn config file, HUP and then
72   # continue with the traditional USR2 + QUIT upgrade steps:
73   #
74   #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
75   START_CTX = {
76     :argv => ARGV.map { |arg| arg.dup },
77     0 => $0.dup,
78   }
79   # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
80   # and like systems
81   START_CTX[:cwd] = begin
82     a = File.stat(pwd = ENV['PWD'])
83     b = File.stat(Dir.pwd)
84     a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
85   rescue
86     Dir.pwd
87   end
88   # :stopdoc:
90   # Creates a working server on host:port (strange things happen if
91   # port isn't a Number).  Use HttpServer::run to start the server and
92   # HttpServer.run.join to join the thread that's processing
93   # incoming requests on the socket.
94   def initialize(app, options = {})
95     @app = app
96     @request = Unicorn::HttpRequest.new
97     self.reexec_pid = 0
98     options = options.dup
99     @ready_pipe = options.delete(:ready_pipe)
100     @init_listeners = options[:listeners] ? options[:listeners].dup : []
101     options[:use_defaults] = true
102     self.config = Unicorn::Configurator.new(options)
103     self.listener_opts = {}
105     # we try inheriting listeners first, so we bind them later.
106     # we don't write the pid file until we've bound listeners in case
107     # unicorn was started twice by mistake.  Even though our #pid= method
108     # checks for stale/existing pid files, race conditions are still
109     # possible (and difficult/non-portable to avoid) and can be likely
110     # to clobber the pid if the second start was in quick succession
111     # after the first, so we rely on the listener binding to fail in
112     # that case.  Some tests (in and outside of this source tree) and
113     # monitoring tools may also rely on pid files existing before we
114     # attempt to connect to the listener(s)
115     config.commit!(self, :skip => [:listeners, :pid])
116     self.orig_app = app
117   end
119   # Runs the thing.  Returns self so you can run join on it
120   def start
121     inherit_listeners!
122     # this pipe is used to wake us up from select(2) in #join when signals
123     # are trapped.  See trap_deferred.
124     init_self_pipe!
126     # setup signal handlers before writing pid file in case people get
127     # trigger happy and send signals as soon as the pid file exists.
128     # Note that signals don't actually get handled until the #join method
129     QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
130     trap(:CHLD) { awaken_master }
131     self.pid = config[:pid]
133     self.master_pid = $$
134     build_app! if preload_app
135     spawn_missing_workers
136     self
137   end
139   # replaces current listener set with +listeners+.  This will
140   # close the socket if it will not exist in the new listener set
141   def listeners=(listeners)
142     cur_names, dead_names = [], []
143     listener_names.each do |name|
144       if ?/ == name[0]
145         # mark unlinked sockets as dead so we can rebind them
146         (File.socket?(name) ? cur_names : dead_names) << name
147       else
148         cur_names << name
149       end
150     end
151     set_names = listener_names(listeners)
152     dead_names.concat(cur_names - set_names).uniq!
154     LISTENERS.delete_if do |io|
155       if dead_names.include?(sock_name(io))
156         IO_PURGATORY.delete_if do |pio|
157           pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
158         end
159         (io.close rescue nil).nil? # true
160       else
161         set_server_sockopt(io, listener_opts[sock_name(io)])
162         false
163       end
164     end
166     (set_names - cur_names).each { |addr| listen(addr) }
167   end
169   def stdout_path=(path); redirect_io($stdout, path); end
170   def stderr_path=(path); redirect_io($stderr, path); end
172   def logger=(obj)
173     Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
174   end
176   # sets the path for the PID file of the master process
177   def pid=(path)
178     if path
179       if x = valid_pid?(path)
180         return path if pid && path == pid && x == $$
181         if x == reexec_pid && pid =~ /\.oldbin\z/
182           logger.warn("will not set pid=#{path} while reexec-ed "\
183                       "child is running PID:#{x}")
184           return
185         end
186         raise ArgumentError, "Already running on PID:#{x} " \
187                              "(or pid=#{path} is stale)"
188       end
189     end
190     unlink_pid_safe(pid) if pid
192     if path
193       fp = begin
194         tmp = "#{File.dirname(path)}/#{rand}.#$$"
195         File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
196       rescue Errno::EEXIST
197         retry
198       end
199       fp.syswrite("#$$\n")
200       File.rename(fp.path, path)
201       fp.close
202     end
203     @pid = path
204   end
206   # add a given address to the +listeners+ set, idempotently
207   # Allows workers to add a private, per-process listener via the
208   # after_fork hook.  Very useful for debugging and testing.
209   # +:tries+ may be specified as an option for the number of times
210   # to retry, and +:delay+ may be specified as the time in seconds
211   # to delay between retries.
212   # A negative value for +:tries+ indicates the listen will be
213   # retried indefinitely, this is useful when workers belonging to
214   # different masters are spawned during a transparent upgrade.
215   def listen(address, opt = {}.merge(listener_opts[address] || {}))
216     address = config.expand_addr(address)
217     return if String === address && listener_names.include?(address)
219     delay = opt[:delay] || 0.5
220     tries = opt[:tries] || 5
221     begin
222       io = bind_listen(address, opt)
223       unless Kgio::TCPServer === io || Kgio::UNIXServer === io
224         IO_PURGATORY << io
225         io = server_cast(io)
226       end
227       logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
228       LISTENERS << io
229       io
230     rescue Errno::EADDRINUSE => err
231       logger.error "adding listener failed addr=#{address} (in use)"
232       raise err if tries == 0
233       tries -= 1
234       logger.error "retrying in #{delay} seconds " \
235                    "(#{tries < 0 ? 'infinite' : tries} tries left)"
236       sleep(delay)
237       retry
238     rescue => err
239       logger.fatal "error adding listener addr=#{address}"
240       raise err
241     end
242   end
244   # monitors children and receives signals forever
245   # (or until a termination signal is sent).  This handles signals
246   # one-at-a-time time and we'll happily drop signals in case somebody
247   # is signalling us too often.
248   def join
249     respawn = true
250     last_check = Time.now
252     proc_name 'master'
253     logger.info "master process ready" # test_exec.rb relies on this message
254     if @ready_pipe
255       @ready_pipe.syswrite($$.to_s)
256       @ready_pipe = @ready_pipe.close rescue nil
257     end
258     begin
259       reap_all_workers
260       case SIG_QUEUE.shift
261       when nil
262         # avoid murdering workers after our master process (or the
263         # machine) comes out of suspend/hibernation
264         if (last_check + @timeout) >= (last_check = Time.now)
265           sleep_time = murder_lazy_workers
266         else
267           sleep_time = @timeout/2.0 + 1
268           @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
269         end
270         maintain_worker_count if respawn
271         master_sleep(sleep_time)
272       when :QUIT # graceful shutdown
273         break
274       when :TERM, :INT # immediate shutdown
275         stop(false)
276         break
277       when :USR1 # rotate logs
278         logger.info "master reopening logs..."
279         Unicorn::Util.reopen_logs
280         logger.info "master done reopening logs"
281         kill_each_worker(:USR1)
282       when :USR2 # exec binary, stay alive in case something went wrong
283         reexec
284       when :WINCH
285         if Process.ppid == 1 || Process.getpgrp != $$
286           respawn = false
287           logger.info "gracefully stopping all workers"
288           kill_each_worker(:QUIT)
289           self.worker_processes = 0
290         else
291           logger.info "SIGWINCH ignored because we're not daemonized"
292         end
293       when :TTIN
294         respawn = true
295         self.worker_processes += 1
296       when :TTOU
297         self.worker_processes -= 1 if self.worker_processes > 0
298       when :HUP
299         respawn = true
300         if config.config_file
301           load_config!
302         else # exec binary and exit if there's no config file
303           logger.info "config_file not present, reexecuting binary"
304           reexec
305         end
306       end
307     rescue => e
308       Unicorn.log_error(@logger, "master loop error", e)
309     end while true
310     stop # gracefully shutdown all workers on our way out
311     logger.info "master complete"
312     unlink_pid_safe(pid) if pid
313   end
315   # Terminates all workers, but does not exit master process
316   def stop(graceful = true)
317     self.listeners = []
318     limit = Time.now + timeout
319     until WORKERS.empty? || Time.now > limit
320       kill_each_worker(graceful ? :QUIT : :TERM)
321       sleep(0.1)
322       reap_all_workers
323     end
324     kill_each_worker(:KILL)
325   end
327   def rewindable_input
328     Unicorn::HttpRequest.input_class.method_defined?(:rewind)
329   end
331   def rewindable_input=(bool)
332     Unicorn::HttpRequest.input_class = bool ?
333                                 Unicorn::TeeInput : Unicorn::StreamInput
334   end
336   def client_body_buffer_size
337     Unicorn::TeeInput.client_body_buffer_size
338   end
340   def client_body_buffer_size=(bytes)
341     Unicorn::TeeInput.client_body_buffer_size = bytes
342   end
344   def trust_x_forwarded
345     Unicorn::HttpParser.trust_x_forwarded?
346   end
348   def trust_x_forwarded=(bool)
349     Unicorn::HttpParser.trust_x_forwarded = bool
350   end
352   private
354   # wait for a signal hander to wake us up and then consume the pipe
355   def master_sleep(sec)
356     IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
357     SELF_PIPE[0].kgio_tryread(11)
358   end
360   def awaken_master
361     SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
362   end
364   # reaps all unreaped workers
365   def reap_all_workers
366     begin
367       wpid, status = Process.waitpid2(-1, Process::WNOHANG)
368       wpid or return
369       if reexec_pid == wpid
370         logger.error "reaped #{status.inspect} exec()-ed"
371         self.reexec_pid = 0
372         self.pid = pid.chomp('.oldbin') if pid
373         proc_name 'master'
374       else
375         worker = WORKERS.delete(wpid) and worker.close rescue nil
376         m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
377         status.success? ? logger.info(m) : logger.error(m)
378       end
379     rescue Errno::ECHILD
380       break
381     end while true
382   end
384   # reexecutes the START_CTX with a new binary
385   def reexec
386     if reexec_pid > 0
387       begin
388         Process.kill(0, reexec_pid)
389         logger.error "reexec-ed child already running PID:#{reexec_pid}"
390         return
391       rescue Errno::ESRCH
392         self.reexec_pid = 0
393       end
394     end
396     if pid
397       old_pid = "#{pid}.oldbin"
398       begin
399         self.pid = old_pid  # clear the path for a new pid file
400       rescue ArgumentError
401         logger.error "old PID:#{valid_pid?(old_pid)} running with " \
402                      "existing pid=#{old_pid}, refusing rexec"
403         return
404       rescue => e
405         logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
406         return
407       end
408     end
410     self.reexec_pid = fork do
411       listener_fds = Hash[LISTENERS.map do |sock|
412         # IO#close_on_exec= will be available on any future version of
413         # Ruby that sets FD_CLOEXEC by default on new file descriptors
414         # ref: http://redmine.ruby-lang.org/issues/5041
415         sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
416         [ sock.fileno, sock ]
417       end]
418       ENV['UNICORN_FD'] = listener_fds.keys.join(',')
419       Dir.chdir(START_CTX[:cwd])
420       cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
422       # avoid leaking FDs we don't know about, but let before_exec
423       # unset FD_CLOEXEC, if anything else in the app eventually
424       # relies on FD inheritence.
425       (3..1024).each do |io|
426         next if listener_fds.include?(io)
427         io = IO.for_fd(io) rescue next
428         IO_PURGATORY << io
429         io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
430       end
432       # exec(command, hash) works in at least 1.9.1+, but will only be
433       # required in 1.9.4/2.0.0 at earliest.
434       cmd << listener_fds if RUBY_VERSION >= "1.9.1"
435       logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
436       before_exec.call(self)
437       exec(*cmd)
438     end
439     proc_name 'master (old)'
440   end
442   # forcibly terminate all workers that haven't checked in in timeout seconds.  The timeout is implemented using an unlinked File
443   def murder_lazy_workers
444     next_sleep = @timeout - 1
445     now = Time.now.to_i
446     WORKERS.dup.each_pair do |wpid, worker|
447       tick = worker.tick
448       0 == tick and next # skip workers that are sleeping
449       diff = now - tick
450       tmp = @timeout - diff
451       if tmp >= 0
452         next_sleep > tmp and next_sleep = tmp
453         next
454       end
455       next_sleep = 0
456       logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
457                    "(#{diff}s > #{@timeout}s), killing"
458       kill_worker(:KILL, wpid) # take no prisoners for timeout violations
459     end
460     next_sleep <= 0 ? 1 : next_sleep
461   end
463   def after_fork_internal
464     @ready_pipe.close if @ready_pipe
465     Unicorn::Configurator::RACKUP.clear
466     @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
468     srand # http://redmine.ruby-lang.org/issues/4338
470     # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
471     # dying workers can recycle pids
472     OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
473   end
475   def spawn_missing_workers
476     worker_nr = -1
477     until (worker_nr += 1) == @worker_processes
478       WORKERS.value?(worker_nr) and next
479       worker = Worker.new(worker_nr)
480       before_fork.call(self, worker)
481       if pid = fork
482         WORKERS[pid] = worker
483       else
484         after_fork_internal
485         worker_loop(worker)
486         exit
487       end
488     end
489     rescue => e
490       @logger.error(e) rescue nil
491       exit!
492   end
494   def maintain_worker_count
495     (off = WORKERS.size - worker_processes) == 0 and return
496     off < 0 and return spawn_missing_workers
497     WORKERS.dup.each_pair { |wpid,w|
498       w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
499     }
500   end
502   # if we get any error, try to write something back to the client
503   # assuming we haven't closed the socket, but don't get hung up
504   # if the socket is already closed or broken.  We'll always ensure
505   # the socket is closed at the end of this function
506   def handle_error(client, e)
507     msg = case e
508     when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
509       Unicorn::Const::ERROR_500_RESPONSE
510     when Unicorn::RequestURITooLongError
511       Unicorn::Const::ERROR_414_RESPONSE
512     when Unicorn::RequestEntityTooLargeError
513       Unicorn::Const::ERROR_413_RESPONSE
514     when Unicorn::HttpParserError # try to tell the client they're bad
515       Unicorn::Const::ERROR_400_RESPONSE
516     else
517       Unicorn.log_error(@logger, "app error", e)
518       Unicorn::Const::ERROR_500_RESPONSE
519     end
520     client.kgio_trywrite(msg)
521     client.close
522     rescue
523   end
525   # once a client is accepted, it is processed in its entirety here
526   # in 3 easy steps: read request, call app, write app response
527   def process_client(client)
528     status, headers, body = @app.call(env = @request.read(client))
530     if 100 == status.to_i
531       client.write(Unicorn::Const::EXPECT_100_RESPONSE)
532       env.delete(Unicorn::Const::HTTP_EXPECT)
533       status, headers, body = @app.call(env)
534     end
535     @request.headers? or headers = nil
536     http_response_write(client, status, headers, body)
537     client.close # flush and uncork socket immediately, no keepalive
538   rescue => e
539     handle_error(client, e)
540   end
542   EXIT_SIGS = [ :QUIT, :TERM, :INT ]
543   WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
545   # gets rid of stuff the worker has no business keeping track of
546   # to free some resources and drops all sig handlers.
547   # traps for USR1, USR2, and HUP may be set in the after_fork Proc
548   # by the user.
549   def init_worker_process(worker)
550     # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
551     EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
552     exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
553     WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
554     trap(:CHLD, 'DEFAULT')
555     SIG_QUEUE.clear
556     proc_name "worker[#{worker.nr}]"
557     START_CTX.clear
558     init_self_pipe!
559     WORKERS.clear
560     LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
561     after_fork.call(self, worker) # can drop perms
562     worker.user(*user) if user.kind_of?(Array) && ! worker.switched
563     self.timeout /= 2.0 # halve it for select()
564     @config = nil
565     build_app! unless preload_app
566     @after_fork = @listener_opts = @orig_app = nil
567   end
569   def reopen_worker_logs(worker_nr)
570     logger.info "worker=#{worker_nr} reopening logs..."
571     Unicorn::Util.reopen_logs
572     logger.info "worker=#{worker_nr} done reopening logs"
573     init_self_pipe!
574     rescue => e
575       logger.error(e) rescue nil
576       exit!(77) # EX_NOPERM in sysexits.h
577   end
579   # runs inside each forked worker, this sits around and waits
580   # for connections and doesn't die until the parent dies (or is
581   # given a INT, QUIT, or TERM signal)
582   def worker_loop(worker)
583     ppid = master_pid
584     init_worker_process(worker)
585     nr = 0 # this becomes negative if we need to reopen logs
586     l = LISTENERS.dup
587     ready = l.dup
589     # closing anything we IO.select on will raise EBADF
590     trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
591     trap(:QUIT) { worker = nil; LISTENERS.each { |s| s.close rescue nil }.clear }
592     logger.info "worker=#{worker.nr} ready"
594     begin
595       nr < 0 and reopen_worker_logs(worker.nr)
596       nr = 0
598       worker.tick = Time.now.to_i
599       while sock = ready.shift
600         if client = sock.kgio_tryaccept
601           process_client(client)
602           nr += 1
603           worker.tick = Time.now.to_i
604         end
605         break if nr < 0
606       end
608       # make the following bet: if we accepted clients this round,
609       # we're probably reasonably busy, so avoid calling select()
610       # and do a speculative non-blocking accept() on ready listeners
611       # before we sleep again in select().
612       unless nr == 0 # (nr < 0) => reopen logs (unlikely)
613         ready = l.dup
614         redo
615       end
617       ppid == Process.ppid or return
619       # timeout used so we can detect parent death:
620       worker.tick = Time.now.to_i
621       ret = IO.select(l, nil, SELF_PIPE, @timeout) and ready = ret[0]
622     rescue Errno::EBADF
623       nr < 0 or return
624     rescue => e
625       Unicorn.log_error(@logger, "listen loop error", e) if worker
626     end while worker
627   end
629   # delivers a signal to a worker and fails gracefully if the worker
630   # is no longer running.
631   def kill_worker(signal, wpid)
632     Process.kill(signal, wpid)
633     rescue Errno::ESRCH
634       worker = WORKERS.delete(wpid) and worker.close rescue nil
635   end
637   # delivers a signal to each worker
638   def kill_each_worker(signal)
639     WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
640   end
642   # unlinks a PID file at given +path+ if it contains the current PID
643   # still potentially racy without locking the directory (which is
644   # non-portable and may interact badly with other programs), but the
645   # window for hitting the race condition is small
646   def unlink_pid_safe(path)
647     (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
648   end
650   # returns a PID if a given path contains a non-stale PID file,
651   # nil otherwise.
652   def valid_pid?(path)
653     wpid = File.read(path).to_i
654     wpid <= 0 and return
655     Process.kill(0, wpid)
656     wpid
657     rescue Errno::ESRCH, Errno::ENOENT
658       # don't unlink stale pid files, racy without non-portable locking...
659   end
661   def load_config!
662     loaded_app = app
663     logger.info "reloading config_file=#{config.config_file}"
664     config[:listeners].replace(@init_listeners)
665     config.reload
666     config.commit!(self)
667     kill_each_worker(:QUIT)
668     Unicorn::Util.reopen_logs
669     self.app = orig_app
670     build_app! if preload_app
671     logger.info "done reloading config_file=#{config.config_file}"
672   rescue StandardError, LoadError, SyntaxError => e
673     Unicorn.log_error(@logger,
674         "error reloading config_file=#{config.config_file}", e)
675     self.app = loaded_app
676   end
678   # returns an array of string names for the given listener array
679   def listener_names(listeners = LISTENERS)
680     listeners.map { |io| sock_name(io) }
681   end
683   def build_app!
684     if app.respond_to?(:arity) && app.arity == 0
685       if defined?(Gem) && Gem.respond_to?(:refresh)
686         logger.info "Refreshing Gem list"
687         Gem.refresh
688       end
689       self.app = app.call
690     end
691   end
693   def proc_name(tag)
694     $0 = ([ File.basename(START_CTX[0]), tag
695           ]).concat(START_CTX[:argv]).join(' ')
696   end
698   def redirect_io(io, path)
699     File.open(path, 'ab') { |fp| io.reopen(fp) } if path
700     io.sync = true
701   end
703   def init_self_pipe!
704     SELF_PIPE.each { |io| io.close rescue nil }
705     SELF_PIPE.replace(Kgio::Pipe.new)
706     SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
707   end
709   def inherit_listeners!
710     # inherit sockets from parents, they need to be plain Socket objects
711     # before they become Kgio::UNIXServer or Kgio::TCPServer
712     inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
713       io = Socket.for_fd(fd.to_i)
714       set_server_sockopt(io, listener_opts[sock_name(io)])
715       IO_PURGATORY << io
716       logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
717       server_cast(io)
718     end
720     config_listeners = config[:listeners].dup
721     LISTENERS.replace(inherited)
723     # we start out with generic Socket objects that get cast to either
724     # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
725     # objects share the same OS-level file descriptor as the higher-level
726     # *Server objects; we need to prevent Socket objects from being
727     # garbage-collected
728     config_listeners -= listener_names
729     if config_listeners.empty? && LISTENERS.empty?
730       config_listeners << Unicorn::Const::DEFAULT_LISTEN
731       @init_listeners << Unicorn::Const::DEFAULT_LISTEN
732       START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
733     end
734     config_listeners.each { |addr| listen(addr) }
735     raise ArgumentError, "no listeners" if LISTENERS.empty?
736   end