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