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