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