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