configurator: add :ipv6only directive
[unicorn.git] / lib / unicorn / http_server.rb
blob604854a458e497156419958fede9e27947863dd3
1 # -*- encoding: binary -*-
3 # This is the process manager of Unicorn. This manages worker
4 # processes which in turn handle the I/O and application process.
5 # Listener sockets are started in the master process and shared with
6 # forked worker children.
8 # Users do not need to know the internals of this class, but reading the
9 # {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb]
10 # is education for programmers wishing to learn how \Unicorn works.
11 # See Unicorn::Configurator for information on how to configure \Unicorn.
12 class Unicorn::HttpServer
13   # :stopdoc:
14   attr_accessor :app, :request, :timeout, :worker_processes,
15                 :before_fork, :after_fork, :before_exec,
16                 :listener_opts, :preload_app,
17                 :reexec_pid, :orig_app, :init_listeners,
18                 :master_pid, :config, :ready_pipe, :user
19   attr_reader :pid, :logger
20   include Unicorn::SocketHelper
21   include Unicorn::HttpResponse
23   # backwards compatibility with 1.x
24   Worker = Unicorn::Worker
26   # all bound listener sockets
27   LISTENERS = []
29   # This hash maps PIDs to Workers
30   WORKERS = {}
32   # We use SELF_PIPE differently in the master and worker processes:
33   #
34   # * The master process never closes or reinitializes this once
35   # initialized.  Signal handlers in the master process will write to
36   # it to wake up the master from IO.select in exactly the same manner
37   # djb describes in http://cr.yp.to/docs/selfpipe.html
38   #
39   # * The workers immediately close the pipe they inherit from the
40   # master and replace it with a new pipe after forking.  This new
41   # pipe is also used to wakeup from IO.select from inside (worker)
42   # signal handlers.  However, workers *close* the pipe descriptors in
43   # the signal handlers to raise EBADF in IO.select instead of writing
44   # like we do in the master.  We cannot easily use the reader set for
45   # IO.select because LISTENERS is already that set, and it's extra
46   # work (and cycles) to distinguish the pipe FD from the reader set
47   # once IO.select returns.  So we're lazy and just close the pipe when
48   # a (rare) signal arrives in the worker and reinitialize the pipe later.
49   SELF_PIPE = []
51   # signal queue used for self-piping
52   SIG_QUEUE = []
54   # list of signals we care about and trap in master.
55   QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
57   # :startdoc:
58   # We populate this at startup so we can figure out how to reexecute
59   # and upgrade the currently running instance of Unicorn
60   # This Hash is considered a stable interface and changing its contents
61   # will allow you to switch between different installations of Unicorn
62   # or even different installations of the same applications without
63   # downtime.  Keys of this constant Hash are described as follows:
64   #
65   # * 0 - the path to the unicorn/unicorn_rails executable
66   # * :argv - a deep copy of the ARGV array the executable originally saw
67   # * :cwd - the working directory of the application, this is where
68   # you originally started Unicorn.
69   #
70   # To change your unicorn executable to a different path without downtime,
71   # you can set the following in your Unicorn config file, HUP and then
72   # continue with the traditional USR2 + QUIT upgrade steps:
73   #
74   #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
75   START_CTX = {
76     :argv => ARGV.map { |arg| arg.dup },
77     0 => $0.dup,
78   }
79   # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
80   # and like systems
81   START_CTX[:cwd] = begin
82     a = File.stat(pwd = ENV['PWD'])
83     b = File.stat(Dir.pwd)
84     a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
85   rescue
86     Dir.pwd
87   end
88   # :stopdoc:
90   # Creates a working server on host:port (strange things happen if
91   # port isn't a Number).  Use HttpServer::run to start the server and
92   # HttpServer.run.join to join the thread that's processing
93   # incoming requests on the socket.
94   def initialize(app, options = {})
95     @app = app
96     @request = Unicorn::HttpRequest.new
97     self.reexec_pid = 0
98     options = options.dup
99     @ready_pipe = options.delete(:ready_pipe)
100     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       @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   def rewindable_input
359     Unicorn::HttpRequest.input_class.method_defined?(:rewind)
360   end
362   def rewindable_input=(bool)
363     Unicorn::HttpRequest.input_class = bool ?
364                                 Unicorn::TeeInput : Unicorn::StreamInput
365   end
367   def client_body_buffer_size
368     Unicorn::TeeInput.client_body_buffer_size
369   end
371   def client_body_buffer_size=(bytes)
372     Unicorn::TeeInput.client_body_buffer_size = bytes
373   end
375   def trust_x_forwarded
376     Unicorn::HttpParser.trust_x_forwarded?
377   end
379   def trust_x_forwarded=(bool)
380     Unicorn::HttpParser.trust_x_forwarded = bool
381   end
383   private
385   # wait for a signal hander to wake us up and then consume the pipe
386   def master_sleep(sec)
387     IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
388     SELF_PIPE[0].kgio_tryread(11)
389   end
391   def awaken_master
392     SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
393   end
395   # reaps all unreaped workers
396   def reap_all_workers
397     begin
398       wpid, status = Process.waitpid2(-1, Process::WNOHANG)
399       wpid or return
400       if reexec_pid == wpid
401         logger.error "reaped #{status.inspect} exec()-ed"
402         self.reexec_pid = 0
403         self.pid = pid.chomp('.oldbin') if pid
404         proc_name 'master'
405       else
406         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
407         m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
408         status.success? ? logger.info(m) : logger.error(m)
409       end
410     rescue Errno::ECHILD
411       break
412     end while true
413   end
415   # reexecutes the START_CTX with a new binary
416   def reexec
417     if reexec_pid > 0
418       begin
419         Process.kill(0, reexec_pid)
420         logger.error "reexec-ed child already running PID:#{reexec_pid}"
421         return
422       rescue Errno::ESRCH
423         self.reexec_pid = 0
424       end
425     end
427     if pid
428       old_pid = "#{pid}.oldbin"
429       begin
430         self.pid = old_pid  # clear the path for a new pid file
431       rescue ArgumentError
432         logger.error "old PID:#{valid_pid?(old_pid)} running with " \
433                      "existing pid=#{old_pid}, refusing rexec"
434         return
435       rescue => e
436         logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
437         return
438       end
439     end
441     self.reexec_pid = fork do
442       listener_fds = LISTENERS.map { |sock| sock.fileno }
443       ENV['UNICORN_FD'] = listener_fds.join(',')
444       Dir.chdir(START_CTX[:cwd])
445       cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
447       # avoid leaking FDs we don't know about, but let before_exec
448       # unset FD_CLOEXEC, if anything else in the app eventually
449       # relies on FD inheritence.
450       (3..1024).each do |io|
451         next if listener_fds.include?(io)
452         io = IO.for_fd(io) rescue next
453         IO_PURGATORY << io
454         io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
455       end
456       logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
457       before_exec.call(self)
458       exec(*cmd)
459     end
460     proc_name 'master (old)'
461   end
463   # forcibly terminate all workers that haven't checked in in timeout
464   # seconds.  The timeout is implemented using an unlinked File
465   # shared between the parent process and each worker.  The worker
466   # runs File#chmod to modify the ctime of the File.  If the ctime
467   # is stale for >timeout seconds, then we'll kill the corresponding
468   # worker.
469   def murder_lazy_workers
470     t = @timeout
471     next_sleep = 1
472     WORKERS.dup.each_pair do |wpid, worker|
473       stat = worker.tmp.stat
474       # skip workers that disable fchmod or have never fchmod-ed
475       stat.mode == 0100600 and next
476       diff = Time.now - stat.ctime
477       if diff <= t
478         tmp = t - diff
479         next_sleep < tmp and next_sleep = tmp
480         next
481       end
482       logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
483                    "(#{diff}s > #{t}s), killing"
484       kill_worker(:KILL, wpid) # take no prisoners for timeout violations
485     end
486     next_sleep
487   end
489   def after_fork_internal
490     @ready_pipe.close if @ready_pipe
491     self.ready_pipe = nil # XXX Rainbows! compat, change for Unicorn 4.x
492     srand # http://redmine.ruby-lang.org/issues/4338
494     # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
495     # dying workers can recycle pids
496     OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
497   end
499   def spawn_missing_workers
500     (0...worker_processes).each do |worker_nr|
501       WORKERS.values.include?(worker_nr) and next
502       worker = Worker.new(worker_nr, Unicorn::TmpIO.new)
503       before_fork.call(self, worker)
504       WORKERS[fork {
505         after_fork_internal
506         worker_loop(worker)
507       }] = worker
508     end
509   end
511   def maintain_worker_count
512     (off = WORKERS.size - worker_processes) == 0 and return
513     off < 0 and return spawn_missing_workers
514     WORKERS.dup.each_pair { |wpid,w|
515       w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
516     }
517   end
519   # if we get any error, try to write something back to the client
520   # assuming we haven't closed the socket, but don't get hung up
521   # if the socket is already closed or broken.  We'll always ensure
522   # the socket is closed at the end of this function
523   def handle_error(client, e)
524     msg = case e
525     when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
526       Unicorn::Const::ERROR_500_RESPONSE
527     when Unicorn::RequestURITooLongError
528       Unicorn::Const::ERROR_414_RESPONSE
529     when Unicorn::RequestEntityTooLargeError
530       Unicorn::Const::ERROR_413_RESPONSE
531     when Unicorn::HttpParserError # try to tell the client they're bad
532       Unicorn::Const::ERROR_400_RESPONSE
533     else
534       logger.error "Read error: #{e.inspect}"
535       logger.error e.backtrace.join("\n")
536       Unicorn::Const::ERROR_500_RESPONSE
537     end
538     client.kgio_trywrite(msg)
539     client.close
540     rescue
541   end
543   # once a client is accepted, it is processed in its entirety here
544   # in 3 easy steps: read request, call app, write app response
545   def process_client(client)
546     status, headers, body = @app.call(env = @request.read(client))
548     if 100 == status.to_i
549       client.write(Unicorn::Const::EXPECT_100_RESPONSE)
550       env.delete(Unicorn::Const::HTTP_EXPECT)
551       status, headers, body = @app.call(env)
552     end
553     @request.headers? or headers = nil
554     http_response_write(client, status, headers, body)
555     client.close # flush and uncork socket immediately, no keepalive
556   rescue => e
557     handle_error(client, e)
558   end
560   # gets rid of stuff the worker has no business keeping track of
561   # to free some resources and drops all sig handlers.
562   # traps for USR1, USR2, and HUP may be set in the after_fork Proc
563   # by the user.
564   def init_worker_process(worker)
565     QUEUE_SIGS.each { |sig| trap(sig, nil) }
566     trap(:CHLD, 'DEFAULT')
567     SIG_QUEUE.clear
568     proc_name "worker[#{worker.nr}]"
569     START_CTX.clear
570     init_self_pipe!
571     WORKERS.values.each { |other| other.tmp.close rescue nil }
572     WORKERS.clear
573     LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
574     worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
575     after_fork.call(self, worker) # can drop perms
576     worker.user(*user) if user.kind_of?(Array) && ! worker.switched
577     self.timeout /= 2.0 # halve it for select()
578     build_app! unless preload_app
579   end
581   def reopen_worker_logs(worker_nr)
582     logger.info "worker=#{worker_nr} reopening logs..."
583     Unicorn::Util.reopen_logs
584     logger.info "worker=#{worker_nr} done reopening logs"
585     init_self_pipe!
586     rescue => e
587       logger.error(e) rescue nil
588       exit!(77) # EX_NOPERM in sysexits.h
589   end
591   # runs inside each forked worker, this sits around and waits
592   # for connections and doesn't die until the parent dies (or is
593   # given a INT, QUIT, or TERM signal)
594   def worker_loop(worker)
595     ppid = master_pid
596     init_worker_process(worker)
597     nr = 0 # this becomes negative if we need to reopen logs
598     alive = worker.tmp # tmp is our lifeline to the master process
599     ready = LISTENERS
601     # closing anything we IO.select on will raise EBADF
602     trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
603     trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil }.clear }
604     [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
605     logger.info "worker=#{worker.nr} ready"
606     m = 0
608     begin
609       nr < 0 and reopen_worker_logs(worker.nr)
610       nr = 0
612       # we're a goner in timeout seconds anyways if alive.chmod
613       # breaks, so don't trap the exception.  Using fchmod() since
614       # futimes() is not available in base Ruby and I very strongly
615       # prefer temporary files to be unlinked for security,
616       # performance and reliability reasons, so utime is out.  No-op
617       # changes with chmod doesn't update ctime on all filesystems; so
618       # we change our counter each and every time (after process_client
619       # and before IO.select).
620       alive.chmod(m = 0 == m ? 1 : 0)
622       ready.each do |sock|
623         if client = sock.kgio_tryaccept
624           process_client(client)
625           nr += 1
626           alive.chmod(m = 0 == m ? 1 : 0)
627         end
628         break if nr < 0
629       end
631       # make the following bet: if we accepted clients this round,
632       # we're probably reasonably busy, so avoid calling select()
633       # and do a speculative non-blocking accept() on ready listeners
634       # before we sleep again in select().
635       redo unless nr == 0 # (nr < 0) => reopen logs
637       ppid == Process.ppid or return
638       alive.chmod(m = 0 == m ? 1 : 0)
640       # timeout used so we can detect parent death:
641       ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) and ready = ret[0]
642     rescue Errno::EINTR
643       ready = LISTENERS
644     rescue Errno::EBADF
645       nr < 0 or return
646     rescue => e
647       if alive
648         logger.error "Unhandled listen loop exception #{e.inspect}."
649         logger.error e.backtrace.join("\n")
650       end
651     end while alive
652   end
654   # delivers a signal to a worker and fails gracefully if the worker
655   # is no longer running.
656   def kill_worker(signal, wpid)
657     Process.kill(signal, wpid)
658     rescue Errno::ESRCH
659       worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
660   end
662   # delivers a signal to each worker
663   def kill_each_worker(signal)
664     WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
665   end
667   # unlinks a PID file at given +path+ if it contains the current PID
668   # still potentially racy without locking the directory (which is
669   # non-portable and may interact badly with other programs), but the
670   # window for hitting the race condition is small
671   def unlink_pid_safe(path)
672     (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
673   end
675   # returns a PID if a given path contains a non-stale PID file,
676   # nil otherwise.
677   def valid_pid?(path)
678     wpid = File.read(path).to_i
679     wpid <= 0 and return
680     Process.kill(0, wpid)
681     wpid
682     rescue Errno::ESRCH, Errno::ENOENT
683       # don't unlink stale pid files, racy without non-portable locking...
684   end
686   def load_config!
687     loaded_app = app
688     logger.info "reloading config_file=#{config.config_file}"
689     config[:listeners].replace(init_listeners)
690     config.reload
691     config.commit!(self)
692     kill_each_worker(:QUIT)
693     Unicorn::Util.reopen_logs
694     self.app = orig_app
695     build_app! if preload_app
696     logger.info "done reloading config_file=#{config.config_file}"
697   rescue StandardError, LoadError, SyntaxError => e
698     logger.error "error reloading config_file=#{config.config_file}: " \
699                  "#{e.class} #{e.message} #{e.backtrace}"
700     self.app = loaded_app
701   end
703   # returns an array of string names for the given listener array
704   def listener_names(listeners = LISTENERS)
705     listeners.map { |io| sock_name(io) }
706   end
708   def build_app!
709     if app.respond_to?(:arity) && app.arity == 0
710       if defined?(Gem) && Gem.respond_to?(:refresh)
711         logger.info "Refreshing Gem list"
712         Gem.refresh
713       end
714       self.app = app.call
715     end
716   end
718   def proc_name(tag)
719     $0 = ([ File.basename(START_CTX[0]), tag
720           ]).concat(START_CTX[:argv]).join(' ')
721   end
723   def redirect_io(io, path)
724     File.open(path, 'ab') { |fp| io.reopen(fp) } if path
725     io.sync = true
726   end
728   def init_self_pipe!
729     SELF_PIPE.each { |io| io.close rescue nil }
730     SELF_PIPE.replace(Kgio::Pipe.new)
731     SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
732   end