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