http_server: fix HttpParserError constant resolution
[unicorn.git] / lib / unicorn / http_server.rb
blob74b2b249d798f7f5c82a714af5be40bc5dfc0179
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.
7 class Unicorn::HttpServer
8   attr_accessor :app, :request, :timeout, :worker_processes,
9                 :before_fork, :after_fork, :before_exec,
10                 :listener_opts, :preload_app,
11                 :reexec_pid, :orig_app, :init_listeners,
12                 :master_pid, :config, :ready_pipe, :user
13   attr_reader :pid, :logger
15   # :stopdoc:
16   include Unicorn::SocketHelper
17   include Unicorn::HttpResponse
19   # backwards compatibility with 1.x
20   Worker = Unicorn::Worker
22   # prevents IO objects in here from being GC-ed
23   IO_PURGATORY = []
25   # all bound listener sockets
26   LISTENERS = []
28   # This hash maps PIDs to Workers
29   WORKERS = {}
31   # We use SELF_PIPE differently in the master and worker processes:
32   #
33   # * The master process never closes or reinitializes this once
34   # initialized.  Signal handlers in the master process will write to
35   # it to wake up the master from IO.select in exactly the same manner
36   # djb describes in http://cr.yp.to/docs/selfpipe.html
37   #
38   # * The workers immediately close the pipe they inherit from the
39   # master and replace it with a new pipe after forking.  This new
40   # pipe is also used to wakeup from IO.select from inside (worker)
41   # signal handlers.  However, workers *close* the pipe descriptors in
42   # the signal handlers to raise EBADF in IO.select instead of writing
43   # like we do in the master.  We cannot easily use the reader set for
44   # IO.select because LISTENERS is already that set, and it's extra
45   # work (and cycles) to distinguish the pipe FD from the reader set
46   # once IO.select returns.  So we're lazy and just close the pipe when
47   # a (rare) signal arrives in the worker and reinitialize the pipe later.
48   SELF_PIPE = []
50   # signal queue used for self-piping
51   SIG_QUEUE = []
53   # list of signals we care about and trap in master.
54   QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
56   # :startdoc:
57   # We populate this at startup so we can figure out how to reexecute
58   # and upgrade the currently running instance of Unicorn
59   # This Hash is considered a stable interface and changing its contents
60   # will allow you to switch between different installations of Unicorn
61   # or even different installations of the same applications without
62   # downtime.  Keys of this constant Hash are described as follows:
63   #
64   # * 0 - the path to the unicorn/unicorn_rails executable
65   # * :argv - a deep copy of the ARGV array the executable originally saw
66   # * :cwd - the working directory of the application, this is where
67   # you originally started Unicorn.
68   #
69   # To change your unicorn executable to a different path without downtime,
70   # you can set the following in your Unicorn config file, HUP and then
71   # continue with the traditional USR2 + QUIT upgrade steps:
72   #
73   #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
74   START_CTX = {
75     :argv => ARGV.map { |arg| arg.dup },
76     :cwd => lambda {
77         # favor ENV['PWD'] since it is (usually) symlink aware for
78         # Capistrano and like systems
79         begin
80           a = File.stat(pwd = ENV['PWD'])
81           b = File.stat(Dir.pwd)
82           a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
83         rescue
84           Dir.pwd
85         end
86       }.call,
87     0 => $0.dup,
88   }
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     self.ready_pipe = options.delete(:ready_pipe)
100     self.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     BasicSocket.do_not_reverse_lookup = true
123     # inherit sockets from parents, they need to be plain Socket objects
124     # before they become Kgio::UNIXServer or Kgio::TCPServer
125     inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
126       io = Socket.for_fd(fd.to_i)
127       set_server_sockopt(io, listener_opts[sock_name(io)])
128       IO_PURGATORY << io
129       logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
130       server_cast(io)
131     end
133     config_listeners = config[:listeners].dup
134     LISTENERS.replace(inherited)
136     # we start out with generic Socket objects that get cast to either
137     # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
138     # objects share the same OS-level file descriptor as the higher-level
139     # *Server objects; we need to prevent Socket objects from being
140     # garbage-collected
141     config_listeners -= listener_names
142     if config_listeners.empty? && LISTENERS.empty?
143       config_listeners << Unicorn::Const::DEFAULT_LISTEN
144       init_listeners << Unicorn::Const::DEFAULT_LISTEN
145       START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
146     end
147     config_listeners.each { |addr| listen(addr) }
148     raise ArgumentError, "no listeners" if LISTENERS.empty?
150     # this pipe is used to wake us up from select(2) in #join when signals
151     # are trapped.  See trap_deferred.
152     init_self_pipe!
154     # setup signal handlers before writing pid file in case people get
155     # trigger happy and send signals as soon as the pid file exists.
156     # Note that signals don't actually get handled until the #join method
157     QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
158     trap(:CHLD) { awaken_master }
159     self.pid = config[:pid]
161     self.master_pid = $$
162     build_app! if preload_app
163     maintain_worker_count
164     self
165   end
167   # replaces current listener set with +listeners+.  This will
168   # close the socket if it will not exist in the new listener set
169   def listeners=(listeners)
170     cur_names, dead_names = [], []
171     listener_names.each do |name|
172       if ?/ == name[0]
173         # mark unlinked sockets as dead so we can rebind them
174         (File.socket?(name) ? cur_names : dead_names) << name
175       else
176         cur_names << name
177       end
178     end
179     set_names = listener_names(listeners)
180     dead_names.concat(cur_names - set_names).uniq!
182     LISTENERS.delete_if do |io|
183       if dead_names.include?(sock_name(io))
184         IO_PURGATORY.delete_if do |pio|
185           pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
186         end
187         (io.close rescue nil).nil? # true
188       else
189         set_server_sockopt(io, listener_opts[sock_name(io)])
190         false
191       end
192     end
194     (set_names - cur_names).each { |addr| listen(addr) }
195   end
197   def stdout_path=(path); redirect_io($stdout, path); end
198   def stderr_path=(path); redirect_io($stderr, path); end
200   def logger=(obj)
201     Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
202   end
204   # sets the path for the PID file of the master process
205   def pid=(path)
206     if path
207       if x = valid_pid?(path)
208         return path if pid && path == pid && x == $$
209         if x == reexec_pid && pid =~ /\.oldbin\z/
210           logger.warn("will not set pid=#{path} while reexec-ed "\
211                       "child is running PID:#{x}")
212           return
213         end
214         raise ArgumentError, "Already running on PID:#{x} " \
215                              "(or pid=#{path} is stale)"
216       end
217     end
218     unlink_pid_safe(pid) if pid
220     if path
221       fp = begin
222         tmp = "#{File.dirname(path)}/#{rand}.#$$"
223         File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
224       rescue Errno::EEXIST
225         retry
226       end
227       fp.syswrite("#$$\n")
228       File.rename(fp.path, path)
229       fp.close
230     end
231     @pid = path
232   end
234   # add a given address to the +listeners+ set, idempotently
235   # Allows workers to add a private, per-process listener via the
236   # after_fork hook.  Very useful for debugging and testing.
237   # +:tries+ may be specified as an option for the number of times
238   # to retry, and +:delay+ may be specified as the time in seconds
239   # to delay between retries.
240   # A negative value for +:tries+ indicates the listen will be
241   # retried indefinitely, this is useful when workers belonging to
242   # different masters are spawned during a transparent upgrade.
243   def listen(address, opt = {}.merge(listener_opts[address] || {}))
244     address = config.expand_addr(address)
245     return if String === address && listener_names.include?(address)
247     delay = opt[:delay] || 0.5
248     tries = opt[:tries] || 5
249     begin
250       io = bind_listen(address, opt)
251       unless Kgio::TCPServer === io || Kgio::UNIXServer === io
252         IO_PURGATORY << io
253         io = server_cast(io)
254       end
255       logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
256       LISTENERS << io
257       io
258     rescue Errno::EADDRINUSE => err
259       logger.error "adding listener failed addr=#{address} (in use)"
260       raise err if tries == 0
261       tries -= 1
262       logger.error "retrying in #{delay} seconds " \
263                    "(#{tries < 0 ? 'infinite' : tries} tries left)"
264       sleep(delay)
265       retry
266     rescue => err
267       logger.fatal "error adding listener addr=#{address}"
268       raise err
269     end
270   end
272   # monitors children and receives signals forever
273   # (or until a termination signal is sent).  This handles signals
274   # one-at-a-time time and we'll happily drop signals in case somebody
275   # is signalling us too often.
276   def join
277     respawn = true
278     last_check = Time.now
280     proc_name 'master'
281     logger.info "master process ready" # test_exec.rb relies on this message
282     if ready_pipe
283       ready_pipe.syswrite($$.to_s)
284       ready_pipe.close rescue nil
285       self.ready_pipe = nil
286     end
287     begin
288       reap_all_workers
289       case SIG_QUEUE.shift
290       when nil
291         # avoid murdering workers after our master process (or the
292         # machine) comes out of suspend/hibernation
293         if (last_check + @timeout) >= (last_check = Time.now)
294           sleep_time = murder_lazy_workers
295         else
296           # wait for workers to wakeup on suspend
297           sleep_time = @timeout/2.0 + 1
298         end
299         maintain_worker_count if respawn
300         master_sleep(sleep_time)
301       when :QUIT # graceful shutdown
302         break
303       when :TERM, :INT # immediate shutdown
304         stop(false)
305         break
306       when :USR1 # rotate logs
307         logger.info "master reopening logs..."
308         Unicorn::Util.reopen_logs
309         logger.info "master done reopening logs"
310         kill_each_worker(:USR1)
311       when :USR2 # exec binary, stay alive in case something went wrong
312         reexec
313       when :WINCH
314         if Process.ppid == 1 || Process.getpgrp != $$
315           respawn = false
316           logger.info "gracefully stopping all workers"
317           kill_each_worker(:QUIT)
318           self.worker_processes = 0
319         else
320           logger.info "SIGWINCH ignored because we're not daemonized"
321         end
322       when :TTIN
323         respawn = true
324         self.worker_processes += 1
325       when :TTOU
326         self.worker_processes -= 1 if self.worker_processes > 0
327       when :HUP
328         respawn = true
329         if config.config_file
330           load_config!
331         else # exec binary and exit if there's no config file
332           logger.info "config_file not present, reexecuting binary"
333           reexec
334         end
335       end
336     rescue Errno::EINTR
337     rescue => e
338       logger.error "Unhandled master loop exception #{e.inspect}."
339       logger.error e.backtrace.join("\n")
340     end while true
341     stop # gracefully shutdown all workers on our way out
342     logger.info "master complete"
343     unlink_pid_safe(pid) if pid
344   end
346   # Terminates all workers, but does not exit master process
347   def stop(graceful = true)
348     self.listeners = []
349     limit = Time.now + timeout
350     until WORKERS.empty? || Time.now > limit
351       kill_each_worker(graceful ? :QUIT : :TERM)
352       sleep(0.1)
353       reap_all_workers
354     end
355     kill_each_worker(:KILL)
356   end
358   private
360   # wait for a signal hander to wake us up and then consume the pipe
361   def master_sleep(sec)
362     IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
363     SELF_PIPE[0].kgio_tryread(11)
364   end
366   def awaken_master
367     SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
368   end
370   # reaps all unreaped workers
371   def reap_all_workers
372     begin
373       wpid, status = Process.waitpid2(-1, Process::WNOHANG)
374       wpid or return
375       if reexec_pid == wpid
376         logger.error "reaped #{status.inspect} exec()-ed"
377         self.reexec_pid = 0
378         self.pid = pid.chomp('.oldbin') if pid
379         proc_name 'master'
380       else
381         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
382         m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
383         status.success? ? logger.info(m) : logger.error(m)
384       end
385     rescue Errno::ECHILD
386       break
387     end while true
388   end
390   # reexecutes the START_CTX with a new binary
391   def reexec
392     if reexec_pid > 0
393       begin
394         Process.kill(0, reexec_pid)
395         logger.error "reexec-ed child already running PID:#{reexec_pid}"
396         return
397       rescue Errno::ESRCH
398         self.reexec_pid = 0
399       end
400     end
402     if pid
403       old_pid = "#{pid}.oldbin"
404       prev_pid = pid.dup
405       begin
406         self.pid = old_pid  # clear the path for a new pid file
407       rescue ArgumentError
408         logger.error "old PID:#{valid_pid?(old_pid)} running with " \
409                      "existing pid=#{old_pid}, refusing rexec"
410         return
411       rescue => e
412         logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
413         return
414       end
415     end
417     self.reexec_pid = fork do
418       listener_fds = LISTENERS.map { |sock| sock.fileno }
419       ENV['UNICORN_FD'] = listener_fds.join(',')
420       Dir.chdir(START_CTX[:cwd])
421       cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
423       # avoid leaking FDs we don't know about, but let before_exec
424       # unset FD_CLOEXEC, if anything else in the app eventually
425       # relies on FD inheritence.
426       (3..1024).each do |io|
427         next if listener_fds.include?(io)
428         io = IO.for_fd(io) rescue next
429         IO_PURGATORY << io
430         io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
431       end
432       logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
433       before_exec.call(self)
434       exec(*cmd)
435     end
436     proc_name 'master (old)'
437   end
439   # forcibly terminate all workers that haven't checked in in timeout
440   # seconds.  The timeout is implemented using an unlinked File
441   # shared between the parent process and each worker.  The worker
442   # runs File#chmod to modify the ctime of the File.  If the ctime
443   # is stale for >timeout seconds, then we'll kill the corresponding
444   # worker.
445   def murder_lazy_workers
446     t = @timeout
447     next_sleep = 1
448     WORKERS.dup.each_pair do |wpid, worker|
449       stat = worker.tmp.stat
450       # skip workers that disable fchmod or have never fchmod-ed
451       stat.mode == 0100600 and next
452       diff = Time.now - stat.ctime
453       if diff <= t
454         tmp = t - diff
455         next_sleep < tmp and next_sleep = tmp
456         next
457       end
458       logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
459                    "(#{diff}s > #{t}s), killing"
460       kill_worker(:KILL, wpid) # take no prisoners for timeout violations
461     end
462     next_sleep
463   end
465   def spawn_missing_workers
466     (0...worker_processes).each do |worker_nr|
467       WORKERS.values.include?(worker_nr) and next
468       worker = Worker.new(worker_nr, Unicorn::TmpIO.new)
469       before_fork.call(self, worker)
470       WORKERS[fork {
471         ready_pipe.close if ready_pipe
472         self.ready_pipe = nil
473         worker_loop(worker)
474       }] = worker
475     end
476   end
478   def maintain_worker_count
479     (off = WORKERS.size - worker_processes) == 0 and return
480     off < 0 and return spawn_missing_workers
481     WORKERS.dup.each_pair { |wpid,w|
482       w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
483     }
484   end
486   # if we get any error, try to write something back to the client
487   # assuming we haven't closed the socket, but don't get hung up
488   # if the socket is already closed or broken.  We'll always ensure
489   # the socket is closed at the end of this function
490   def handle_error(client, e)
491     msg = case e
492     when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
493       Unicorn::Const::ERROR_500_RESPONSE
494     when Unicorn::HttpParserError # try to tell the client they're bad
495       Unicorn::Const::ERROR_400_RESPONSE
496     else
497       logger.error "Read error: #{e.inspect}"
498       logger.error e.backtrace.join("\n")
499       Unicorn::Const::ERROR_500_RESPONSE
500     end
501     client.kgio_trywrite(msg)
502     client.close
503     rescue
504       nil
505   end
507   # once a client is accepted, it is processed in its entirety here
508   # in 3 easy steps: read request, call app, write app response
509   def process_client(client)
510     r = @app.call(env = @request.read(client))
512     if 100 == r[0].to_i
513       client.write(Unicorn::Const::EXPECT_100_RESPONSE)
514       env.delete(Unicorn::Const::HTTP_EXPECT)
515       r = @app.call(env)
516     end
517     # r may be frozen or const, so don't modify it
518     @request.headers? or r = [ r[0], nil, r[2] ]
519     http_response_write(client, r)
520   rescue => e
521     handle_error(client, e)
522   end
524   # gets rid of stuff the worker has no business keeping track of
525   # to free some resources and drops all sig handlers.
526   # traps for USR1, USR2, and HUP may be set in the after_fork Proc
527   # by the user.
528   def init_worker_process(worker)
529     QUEUE_SIGS.each { |sig| trap(sig, nil) }
530     trap(:CHLD, 'DEFAULT')
531     SIG_QUEUE.clear
532     proc_name "worker[#{worker.nr}]"
533     START_CTX.clear
534     init_self_pipe!
535     WORKERS.values.each { |other| other.tmp.close rescue nil }
536     WORKERS.clear
537     LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
538     worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
539     after_fork.call(self, worker) # can drop perms
540     worker.user(*user) if user.kind_of?(Array) && ! worker.switched
541     self.timeout /= 2.0 # halve it for select()
542     build_app! unless preload_app
543   end
545   def reopen_worker_logs(worker_nr)
546     logger.info "worker=#{worker_nr} reopening logs..."
547     Unicorn::Util.reopen_logs
548     logger.info "worker=#{worker_nr} done reopening logs"
549     init_self_pipe!
550   end
552   # runs inside each forked worker, this sits around and waits
553   # for connections and doesn't die until the parent dies (or is
554   # given a INT, QUIT, or TERM signal)
555   def worker_loop(worker)
556     ppid = master_pid
557     init_worker_process(worker)
558     nr = 0 # this becomes negative if we need to reopen logs
559     alive = worker.tmp # tmp is our lifeline to the master process
560     ready = LISTENERS
562     # closing anything we IO.select on will raise EBADF
563     trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
564     trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
565     [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
566     logger.info "worker=#{worker.nr} ready"
567     m = 0
569     begin
570       nr < 0 and reopen_worker_logs(worker.nr)
571       nr = 0
573       # we're a goner in timeout seconds anyways if alive.chmod
574       # breaks, so don't trap the exception.  Using fchmod() since
575       # futimes() is not available in base Ruby and I very strongly
576       # prefer temporary files to be unlinked for security,
577       # performance and reliability reasons, so utime is out.  No-op
578       # changes with chmod doesn't update ctime on all filesystems; so
579       # we change our counter each and every time (after process_client
580       # and before IO.select).
581       alive.chmod(m = 0 == m ? 1 : 0)
583       ready.each do |sock|
584         if client = sock.kgio_tryaccept
585           process_client(client)
586           nr += 1
587           alive.chmod(m = 0 == m ? 1 : 0)
588         end
589         break if nr < 0
590       end
592       # make the following bet: if we accepted clients this round,
593       # we're probably reasonably busy, so avoid calling select()
594       # and do a speculative non-blocking accept() on ready listeners
595       # before we sleep again in select().
596       redo unless nr == 0 # (nr < 0) => reopen logs
598       ppid == Process.ppid or return
599       alive.chmod(m = 0 == m ? 1 : 0)
601       # timeout used so we can detect parent death:
602       ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) and ready = ret[0]
603     rescue Errno::EINTR
604       ready = LISTENERS
605     rescue Errno::EBADF
606       nr < 0 or return
607     rescue => e
608       if alive
609         logger.error "Unhandled listen loop exception #{e.inspect}."
610         logger.error e.backtrace.join("\n")
611       end
612     end while alive
613   end
615   # delivers a signal to a worker and fails gracefully if the worker
616   # is no longer running.
617   def kill_worker(signal, wpid)
618     Process.kill(signal, wpid)
619     rescue Errno::ESRCH
620       worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
621   end
623   # delivers a signal to each worker
624   def kill_each_worker(signal)
625     WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
626   end
628   # unlinks a PID file at given +path+ if it contains the current PID
629   # still potentially racy without locking the directory (which is
630   # non-portable and may interact badly with other programs), but the
631   # window for hitting the race condition is small
632   def unlink_pid_safe(path)
633     (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
634   end
636   # returns a PID if a given path contains a non-stale PID file,
637   # nil otherwise.
638   def valid_pid?(path)
639     wpid = File.read(path).to_i
640     wpid <= 0 and return
641     Process.kill(0, wpid)
642     wpid
643     rescue Errno::ESRCH, Errno::ENOENT
644       # don't unlink stale pid files, racy without non-portable locking...
645   end
647   def load_config!
648     loaded_app = app
649     logger.info "reloading config_file=#{config.config_file}"
650     config[:listeners].replace(init_listeners)
651     config.reload
652     config.commit!(self)
653     kill_each_worker(:QUIT)
654     Unicorn::Util.reopen_logs
655     self.app = orig_app
656     build_app! if preload_app
657     logger.info "done reloading config_file=#{config.config_file}"
658   rescue StandardError, LoadError, SyntaxError => e
659     logger.error "error reloading config_file=#{config.config_file}: " \
660                  "#{e.class} #{e.message} #{e.backtrace}"
661     self.app = loaded_app
662   end
664   # returns an array of string names for the given listener array
665   def listener_names(listeners = LISTENERS)
666     listeners.map { |io| sock_name(io) }
667   end
669   def build_app!
670     if app.respond_to?(:arity) && app.arity == 0
671       if defined?(Gem) && Gem.respond_to?(:refresh)
672         logger.info "Refreshing Gem list"
673         Gem.refresh
674       end
675       self.app = app.call
676     end
677   end
679   def proc_name(tag)
680     $0 = ([ File.basename(START_CTX[0]), tag
681           ]).concat(START_CTX[:argv]).join(' ')
682   end
684   def redirect_io(io, path)
685     File.open(path, 'ab') { |fp| io.reopen(fp) } if path
686     io.sync = true
687   end
689   def init_self_pipe!
690     SELF_PIPE.each { |io| io.close rescue nil }
691     SELF_PIPE.replace(Kgio::Pipe.new)
692     SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
693   end