http_response: simplify the status == 100 comparison
[unicorn.git] / lib / unicorn / http_server.rb
blobe2a4db73f81ba7649eb4371f1b7e2166cbc979bd
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     0 => $0.dup,
77   }
78   # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
79   # and like systems
80   START_CTX[:cwd] = begin
81     a = File.stat(pwd = ENV['PWD'])
82     b = File.stat(Dir.pwd)
83     a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
84   rescue
85     Dir.pwd
86   end
88   # Creates a working server on host:port (strange things happen if
89   # port isn't a Number).  Use HttpServer::run to start the server and
90   # HttpServer.run.join to join the thread that's processing
91   # incoming requests on the socket.
92   def initialize(app, options = {})
93     @app = app
94     @request = Unicorn::HttpRequest.new
95     self.reexec_pid = 0
96     options = options.dup
97     self.ready_pipe = options.delete(:ready_pipe)
98     self.init_listeners = options[:listeners] ? options[:listeners].dup : []
99     options[:use_defaults] = true
100     self.config = Unicorn::Configurator.new(options)
101     self.listener_opts = {}
103     # we try inheriting listeners first, so we bind them later.
104     # we don't write the pid file until we've bound listeners in case
105     # unicorn was started twice by mistake.  Even though our #pid= method
106     # checks for stale/existing pid files, race conditions are still
107     # possible (and difficult/non-portable to avoid) and can be likely
108     # to clobber the pid if the second start was in quick succession
109     # after the first, so we rely on the listener binding to fail in
110     # that case.  Some tests (in and outside of this source tree) and
111     # monitoring tools may also rely on pid files existing before we
112     # attempt to connect to the listener(s)
113     config.commit!(self, :skip => [:listeners, :pid])
114     self.orig_app = app
115   end
117   # Runs the thing.  Returns self so you can run join on it
118   def start
119     BasicSocket.do_not_reverse_lookup = true
121     # inherit sockets from parents, they need to be plain Socket objects
122     # before they become Kgio::UNIXServer or Kgio::TCPServer
123     inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
124       io = Socket.for_fd(fd.to_i)
125       set_server_sockopt(io, listener_opts[sock_name(io)])
126       IO_PURGATORY << io
127       logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
128       server_cast(io)
129     end
131     config_listeners = config[:listeners].dup
132     LISTENERS.replace(inherited)
134     # we start out with generic Socket objects that get cast to either
135     # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
136     # objects share the same OS-level file descriptor as the higher-level
137     # *Server objects; we need to prevent Socket objects from being
138     # garbage-collected
139     config_listeners -= listener_names
140     if config_listeners.empty? && LISTENERS.empty?
141       config_listeners << Unicorn::Const::DEFAULT_LISTEN
142       init_listeners << Unicorn::Const::DEFAULT_LISTEN
143       START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
144     end
145     config_listeners.each { |addr| listen(addr) }
146     raise ArgumentError, "no listeners" if LISTENERS.empty?
148     # this pipe is used to wake us up from select(2) in #join when signals
149     # are trapped.  See trap_deferred.
150     init_self_pipe!
152     # setup signal handlers before writing pid file in case people get
153     # trigger happy and send signals as soon as the pid file exists.
154     # Note that signals don't actually get handled until the #join method
155     QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
156     trap(:CHLD) { awaken_master }
157     self.pid = config[:pid]
159     self.master_pid = $$
160     build_app! if preload_app
161     maintain_worker_count
162     self
163   end
165   # replaces current listener set with +listeners+.  This will
166   # close the socket if it will not exist in the new listener set
167   def listeners=(listeners)
168     cur_names, dead_names = [], []
169     listener_names.each do |name|
170       if ?/ == name[0]
171         # mark unlinked sockets as dead so we can rebind them
172         (File.socket?(name) ? cur_names : dead_names) << name
173       else
174         cur_names << name
175       end
176     end
177     set_names = listener_names(listeners)
178     dead_names.concat(cur_names - set_names).uniq!
180     LISTENERS.delete_if do |io|
181       if dead_names.include?(sock_name(io))
182         IO_PURGATORY.delete_if do |pio|
183           pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
184         end
185         (io.close rescue nil).nil? # true
186       else
187         set_server_sockopt(io, listener_opts[sock_name(io)])
188         false
189       end
190     end
192     (set_names - cur_names).each { |addr| listen(addr) }
193   end
195   def stdout_path=(path); redirect_io($stdout, path); end
196   def stderr_path=(path); redirect_io($stderr, path); end
198   def logger=(obj)
199     Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
200   end
202   # sets the path for the PID file of the master process
203   def pid=(path)
204     if path
205       if x = valid_pid?(path)
206         return path if pid && path == pid && x == $$
207         if x == reexec_pid && pid =~ /\.oldbin\z/
208           logger.warn("will not set pid=#{path} while reexec-ed "\
209                       "child is running PID:#{x}")
210           return
211         end
212         raise ArgumentError, "Already running on PID:#{x} " \
213                              "(or pid=#{path} is stale)"
214       end
215     end
216     unlink_pid_safe(pid) if pid
218     if path
219       fp = begin
220         tmp = "#{File.dirname(path)}/#{rand}.#$$"
221         File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
222       rescue Errno::EEXIST
223         retry
224       end
225       fp.syswrite("#$$\n")
226       File.rename(fp.path, path)
227       fp.close
228     end
229     @pid = path
230   end
232   # add a given address to the +listeners+ set, idempotently
233   # Allows workers to add a private, per-process listener via the
234   # after_fork hook.  Very useful for debugging and testing.
235   # +:tries+ may be specified as an option for the number of times
236   # to retry, and +:delay+ may be specified as the time in seconds
237   # to delay between retries.
238   # A negative value for +:tries+ indicates the listen will be
239   # retried indefinitely, this is useful when workers belonging to
240   # different masters are spawned during a transparent upgrade.
241   def listen(address, opt = {}.merge(listener_opts[address] || {}))
242     address = config.expand_addr(address)
243     return if String === address && listener_names.include?(address)
245     delay = opt[:delay] || 0.5
246     tries = opt[:tries] || 5
247     begin
248       io = bind_listen(address, opt)
249       unless Kgio::TCPServer === io || Kgio::UNIXServer === io
250         IO_PURGATORY << io
251         io = server_cast(io)
252       end
253       logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
254       LISTENERS << io
255       io
256     rescue Errno::EADDRINUSE => err
257       logger.error "adding listener failed addr=#{address} (in use)"
258       raise err if tries == 0
259       tries -= 1
260       logger.error "retrying in #{delay} seconds " \
261                    "(#{tries < 0 ? 'infinite' : tries} tries left)"
262       sleep(delay)
263       retry
264     rescue => err
265       logger.fatal "error adding listener addr=#{address}"
266       raise err
267     end
268   end
270   # monitors children and receives signals forever
271   # (or until a termination signal is sent).  This handles signals
272   # one-at-a-time time and we'll happily drop signals in case somebody
273   # is signalling us too often.
274   def join
275     respawn = true
276     last_check = Time.now
278     proc_name 'master'
279     logger.info "master process ready" # test_exec.rb relies on this message
280     if ready_pipe
281       ready_pipe.syswrite($$.to_s)
282       ready_pipe.close rescue nil
283       self.ready_pipe = nil
284     end
285     begin
286       reap_all_workers
287       case SIG_QUEUE.shift
288       when nil
289         # avoid murdering workers after our master process (or the
290         # machine) comes out of suspend/hibernation
291         if (last_check + @timeout) >= (last_check = Time.now)
292           sleep_time = murder_lazy_workers
293         else
294           # wait for workers to wakeup on suspend
295           sleep_time = @timeout/2.0 + 1
296         end
297         maintain_worker_count if respawn
298         master_sleep(sleep_time)
299       when :QUIT # graceful shutdown
300         break
301       when :TERM, :INT # immediate shutdown
302         stop(false)
303         break
304       when :USR1 # rotate logs
305         logger.info "master reopening logs..."
306         Unicorn::Util.reopen_logs
307         logger.info "master done reopening logs"
308         kill_each_worker(:USR1)
309       when :USR2 # exec binary, stay alive in case something went wrong
310         reexec
311       when :WINCH
312         if Process.ppid == 1 || Process.getpgrp != $$
313           respawn = false
314           logger.info "gracefully stopping all workers"
315           kill_each_worker(:QUIT)
316           self.worker_processes = 0
317         else
318           logger.info "SIGWINCH ignored because we're not daemonized"
319         end
320       when :TTIN
321         respawn = true
322         self.worker_processes += 1
323       when :TTOU
324         self.worker_processes -= 1 if self.worker_processes > 0
325       when :HUP
326         respawn = true
327         if config.config_file
328           load_config!
329         else # exec binary and exit if there's no config file
330           logger.info "config_file not present, reexecuting binary"
331           reexec
332         end
333       end
334     rescue Errno::EINTR
335     rescue => e
336       logger.error "Unhandled master loop exception #{e.inspect}."
337       logger.error e.backtrace.join("\n")
338     end while true
339     stop # gracefully shutdown all workers on our way out
340     logger.info "master complete"
341     unlink_pid_safe(pid) if pid
342   end
344   # Terminates all workers, but does not exit master process
345   def stop(graceful = true)
346     self.listeners = []
347     limit = Time.now + timeout
348     until WORKERS.empty? || Time.now > limit
349       kill_each_worker(graceful ? :QUIT : :TERM)
350       sleep(0.1)
351       reap_all_workers
352     end
353     kill_each_worker(:KILL)
354   end
356   def rewindable_input
357     Unicorn::HttpRequest.input_class.method_defined?(:rewind)
358   end
360   def rewindable_input=(bool)
361     Unicorn::HttpRequest.input_class = bool ?
362                                 Unicorn::TeeInput : Unicorn::StreamInput
363   end
365   def client_body_buffer_size
366     Unicorn::TeeInput.client_body_buffer_size
367   end
369   def client_body_buffer_size=(bytes)
370     Unicorn::TeeInput.client_body_buffer_size = bytes
371   end
373   def trust_x_forwarded
374     Unicorn::HttpParser.trust_x_forwarded?
375   end
377   def trust_x_forwarded=(bool)
378     Unicorn::HttpParser.trust_x_forwarded = bool
379   end
381   private
383   # wait for a signal hander to wake us up and then consume the pipe
384   def master_sleep(sec)
385     IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
386     SELF_PIPE[0].kgio_tryread(11)
387   end
389   def awaken_master
390     SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
391   end
393   # reaps all unreaped workers
394   def reap_all_workers
395     begin
396       wpid, status = Process.waitpid2(-1, Process::WNOHANG)
397       wpid or return
398       if reexec_pid == wpid
399         logger.error "reaped #{status.inspect} exec()-ed"
400         self.reexec_pid = 0
401         self.pid = pid.chomp('.oldbin') if pid
402         proc_name 'master'
403       else
404         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
405         m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
406         status.success? ? logger.info(m) : logger.error(m)
407       end
408     rescue Errno::ECHILD
409       break
410     end while true
411   end
413   # reexecutes the START_CTX with a new binary
414   def reexec
415     if reexec_pid > 0
416       begin
417         Process.kill(0, reexec_pid)
418         logger.error "reexec-ed child already running PID:#{reexec_pid}"
419         return
420       rescue Errno::ESRCH
421         self.reexec_pid = 0
422       end
423     end
425     if pid
426       old_pid = "#{pid}.oldbin"
427       prev_pid = pid.dup
428       begin
429         self.pid = old_pid  # clear the path for a new pid file
430       rescue ArgumentError
431         logger.error "old PID:#{valid_pid?(old_pid)} running with " \
432                      "existing pid=#{old_pid}, refusing rexec"
433         return
434       rescue => e
435         logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
436         return
437       end
438     end
440     self.reexec_pid = fork do
441       listener_fds = LISTENERS.map { |sock| sock.fileno }
442       ENV['UNICORN_FD'] = listener_fds.join(',')
443       Dir.chdir(START_CTX[:cwd])
444       cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
446       # avoid leaking FDs we don't know about, but let before_exec
447       # unset FD_CLOEXEC, if anything else in the app eventually
448       # relies on FD inheritence.
449       (3..1024).each do |io|
450         next if listener_fds.include?(io)
451         io = IO.for_fd(io) rescue next
452         IO_PURGATORY << io
453         io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
454       end
455       logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
456       before_exec.call(self)
457       exec(*cmd)
458     end
459     proc_name 'master (old)'
460   end
462   # forcibly terminate all workers that haven't checked in in timeout
463   # seconds.  The timeout is implemented using an unlinked File
464   # shared between the parent process and each worker.  The worker
465   # runs File#chmod to modify the ctime of the File.  If the ctime
466   # is stale for >timeout seconds, then we'll kill the corresponding
467   # worker.
468   def murder_lazy_workers
469     t = @timeout
470     next_sleep = 1
471     WORKERS.dup.each_pair do |wpid, worker|
472       stat = worker.tmp.stat
473       # skip workers that disable fchmod or have never fchmod-ed
474       stat.mode == 0100600 and next
475       diff = Time.now - stat.ctime
476       if diff <= t
477         tmp = t - diff
478         next_sleep < tmp and next_sleep = tmp
479         next
480       end
481       logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
482                    "(#{diff}s > #{t}s), killing"
483       kill_worker(:KILL, wpid) # take no prisoners for timeout violations
484     end
485     next_sleep
486   end
488   def spawn_missing_workers
489     (0...worker_processes).each do |worker_nr|
490       WORKERS.values.include?(worker_nr) and next
491       worker = Worker.new(worker_nr, Unicorn::TmpIO.new)
492       before_fork.call(self, worker)
493       WORKERS[fork {
494         ready_pipe.close if ready_pipe
495         self.ready_pipe = nil
496         worker_loop(worker)
497       }] = worker
498     end
499   end
501   def maintain_worker_count
502     (off = WORKERS.size - worker_processes) == 0 and return
503     off < 0 and return spawn_missing_workers
504     WORKERS.dup.each_pair { |wpid,w|
505       w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
506     }
507   end
509   # if we get any error, try to write something back to the client
510   # assuming we haven't closed the socket, but don't get hung up
511   # if the socket is already closed or broken.  We'll always ensure
512   # the socket is closed at the end of this function
513   def handle_error(client, e)
514     msg = case e
515     when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
516       Unicorn::Const::ERROR_500_RESPONSE
517     when Unicorn::HttpParserError # try to tell the client they're bad
518       Unicorn::Const::ERROR_400_RESPONSE
519     else
520       logger.error "Read error: #{e.inspect}"
521       logger.error e.backtrace.join("\n")
522       Unicorn::Const::ERROR_500_RESPONSE
523     end
524     client.kgio_trywrite(msg)
525     client.close
526     rescue
527   end
529   # once a client is accepted, it is processed in its entirety here
530   # in 3 easy steps: read request, call app, write app response
531   def process_client(client)
532     status, headers, body = @app.call(env = @request.read(client))
534     if 100 == status.to_i
535       client.write(Unicorn::Const::EXPECT_100_RESPONSE)
536       env.delete(Unicorn::Const::HTTP_EXPECT)
537       status, headers, body = @app.call(env)
538     end
539     @request.headers? or headers = nil
540     http_response_write(client, status, headers, body)
541   rescue => e
542     handle_error(client, e)
543   end
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     QUEUE_SIGS.each { |sig| trap(sig, nil) }
551     trap(:CHLD, 'DEFAULT')
552     SIG_QUEUE.clear
553     proc_name "worker[#{worker.nr}]"
554     START_CTX.clear
555     init_self_pipe!
556     WORKERS.values.each { |other| other.tmp.close rescue nil }
557     WORKERS.clear
558     LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
559     worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
560     after_fork.call(self, worker) # can drop perms
561     worker.user(*user) if user.kind_of?(Array) && ! worker.switched
562     self.timeout /= 2.0 # halve it for select()
563     build_app! unless preload_app
564   end
566   def reopen_worker_logs(worker_nr)
567     logger.info "worker=#{worker_nr} reopening logs..."
568     Unicorn::Util.reopen_logs
569     logger.info "worker=#{worker_nr} done reopening logs"
570     init_self_pipe!
571   end
573   # runs inside each forked worker, this sits around and waits
574   # for connections and doesn't die until the parent dies (or is
575   # given a INT, QUIT, or TERM signal)
576   def worker_loop(worker)
577     ppid = master_pid
578     init_worker_process(worker)
579     nr = 0 # this becomes negative if we need to reopen logs
580     alive = worker.tmp # tmp is our lifeline to the master process
581     ready = LISTENERS
583     # closing anything we IO.select on will raise EBADF
584     trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
585     trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
586     [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
587     logger.info "worker=#{worker.nr} ready"
588     m = 0
590     begin
591       nr < 0 and reopen_worker_logs(worker.nr)
592       nr = 0
594       # we're a goner in timeout seconds anyways if alive.chmod
595       # breaks, so don't trap the exception.  Using fchmod() since
596       # futimes() is not available in base Ruby and I very strongly
597       # prefer temporary files to be unlinked for security,
598       # performance and reliability reasons, so utime is out.  No-op
599       # changes with chmod doesn't update ctime on all filesystems; so
600       # we change our counter each and every time (after process_client
601       # and before IO.select).
602       alive.chmod(m = 0 == m ? 1 : 0)
604       ready.each do |sock|
605         if client = sock.kgio_tryaccept
606           process_client(client)
607           nr += 1
608           alive.chmod(m = 0 == m ? 1 : 0)
609         end
610         break if nr < 0
611       end
613       # make the following bet: if we accepted clients this round,
614       # we're probably reasonably busy, so avoid calling select()
615       # and do a speculative non-blocking accept() on ready listeners
616       # before we sleep again in select().
617       redo unless nr == 0 # (nr < 0) => reopen logs
619       ppid == Process.ppid or return
620       alive.chmod(m = 0 == m ? 1 : 0)
622       # timeout used so we can detect parent death:
623       ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) and ready = ret[0]
624     rescue Errno::EINTR
625       ready = LISTENERS
626     rescue Errno::EBADF
627       nr < 0 or return
628     rescue => e
629       if alive
630         logger.error "Unhandled listen loop exception #{e.inspect}."
631         logger.error e.backtrace.join("\n")
632       end
633     end while alive
634   end
636   # delivers a signal to a worker and fails gracefully if the worker
637   # is no longer running.
638   def kill_worker(signal, wpid)
639     Process.kill(signal, wpid)
640     rescue Errno::ESRCH
641       worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
642   end
644   # delivers a signal to each worker
645   def kill_each_worker(signal)
646     WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
647   end
649   # unlinks a PID file at given +path+ if it contains the current PID
650   # still potentially racy without locking the directory (which is
651   # non-portable and may interact badly with other programs), but the
652   # window for hitting the race condition is small
653   def unlink_pid_safe(path)
654     (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
655   end
657   # returns a PID if a given path contains a non-stale PID file,
658   # nil otherwise.
659   def valid_pid?(path)
660     wpid = File.read(path).to_i
661     wpid <= 0 and return
662     Process.kill(0, wpid)
663     wpid
664     rescue Errno::ESRCH, Errno::ENOENT
665       # don't unlink stale pid files, racy without non-portable locking...
666   end
668   def load_config!
669     loaded_app = app
670     logger.info "reloading config_file=#{config.config_file}"
671     config[:listeners].replace(init_listeners)
672     config.reload
673     config.commit!(self)
674     kill_each_worker(:QUIT)
675     Unicorn::Util.reopen_logs
676     self.app = orig_app
677     build_app! if preload_app
678     logger.info "done reloading config_file=#{config.config_file}"
679   rescue StandardError, LoadError, SyntaxError => e
680     logger.error "error reloading config_file=#{config.config_file}: " \
681                  "#{e.class} #{e.message} #{e.backtrace}"
682     self.app = loaded_app
683   end
685   # returns an array of string names for the given listener array
686   def listener_names(listeners = LISTENERS)
687     listeners.map { |io| sock_name(io) }
688   end
690   def build_app!
691     if app.respond_to?(:arity) && app.arity == 0
692       if defined?(Gem) && Gem.respond_to?(:refresh)
693         logger.info "Refreshing Gem list"
694         Gem.refresh
695       end
696       self.app = app.call
697     end
698   end
700   def proc_name(tag)
701     $0 = ([ File.basename(START_CTX[0]), tag
702           ]).concat(START_CTX[:argv]).join(' ')
703   end
705   def redirect_io(io, path)
706     File.open(path, 'ab') { |fp| io.reopen(fp) } if path
707     io.sync = true
708   end
710   def init_self_pipe!
711     SELF_PIPE.each { |io| io.close rescue nil }
712     SELF_PIPE.replace(Kgio::Pipe.new)
713     SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
714   end