miscellaneous loop and begin cleanups
[unicorn.git] / lib / unicorn.rb
blob7f9135227fd946c27a588f06cab9ddb1dbb15920
1 # -*- encoding: binary -*-
3 require 'fcntl'
4 require 'etc'
5 require 'stringio'
6 require 'rack'
7 require 'unicorn/socket_helper'
8 require 'unicorn/const'
9 require 'unicorn/http_request'
10 require 'unicorn/configurator'
11 require 'unicorn/util'
12 require 'unicorn/tee_input'
13 require 'unicorn/http_response'
15 # Unicorn module containing all of the classes (include C extensions) for running
16 # a Unicorn web server.  It contains a minimalist HTTP server with just enough
17 # functionality to service web application requests fast as possible.
18 module Unicorn
20   # raised inside TeeInput when a client closes the socket inside the
21   # application dispatch.  This is always raised with an empty backtrace
22   # since there is nothing in the application stack that is responsible
23   # for client shutdowns/disconnects.
24   class ClientShutdown < EOFError
25   end
27   class << self
28     def run(app, options = {})
29       HttpServer.new(app, options).start.join
30     end
32     # This returns a lambda to pass in as the app, this does not "build" the
33     # app (which we defer based on the outcome of "preload_app" in the
34     # Unicorn config).  The returned lambda will be called when it is
35     # time to build the app.
36     def builder(ru, opts)
37       # allow Configurator to parse cli switches embedded in the ru file
38       Unicorn::Configurator::RACKUP.update(:file => ru, :optparse => opts)
40       # always called after config file parsing, may be called after forking
41       lambda do ||
42         inner_app = case ru
43         when /\.ru$/
44           raw = File.read(ru)
45           raw.sub!(/^__END__\n.*/, '')
46           eval("Rack::Builder.new {(#{raw}\n)}.to_app", TOPLEVEL_BINDING, ru)
47         else
48           require ru
49           Object.const_get(File.basename(ru, '.rb').capitalize)
50         end
52         pp({ :inner_app => inner_app }) if $DEBUG
54         # return value, matches rackup defaults based on env
55         case ENV["RACK_ENV"]
56         when "development"
57           Rack::Builder.new do
58             use Rack::CommonLogger, $stderr
59             use Rack::ShowExceptions
60             use Rack::Lint
61             run inner_app
62           end.to_app
63         when "deployment"
64           Rack::Builder.new do
65             use Rack::CommonLogger, $stderr
66             run inner_app
67           end.to_app
68         else
69           inner_app
70         end
71       end
72     end
74     # returns an array of strings representing TCP listen socket addresses
75     # and Unix domain socket paths.  This is useful for use with
76     # Raindrops::Middleware under Linux: http://raindrops.bogomips.org/
77     def listener_names
78       HttpServer::LISTENERS.map { |io| SocketHelper.sock_name(io) }
79     end
80   end
82   # This is the process manager of Unicorn. This manages worker
83   # processes which in turn handle the I/O and application process.
84   # Listener sockets are started in the master process and shared with
85   # forked worker children.
87   class HttpServer < Struct.new(:app, :timeout, :worker_processes,
88                                 :before_fork, :after_fork, :before_exec,
89                                 :logger, :pid, :listener_opts, :preload_app,
90                                 :reexec_pid, :orig_app, :init_listeners,
91                                 :master_pid, :config, :ready_pipe, :user)
92     include ::Unicorn::SocketHelper
94     # prevents IO objects in here from being GC-ed
95     IO_PURGATORY = []
97     # all bound listener sockets
98     LISTENERS = []
100     # This hash maps PIDs to Workers
101     WORKERS = {}
103     # We use SELF_PIPE differently in the master and worker processes:
104     #
105     # * The master process never closes or reinitializes this once
106     # initialized.  Signal handlers in the master process will write to
107     # it to wake up the master from IO.select in exactly the same manner
108     # djb describes in http://cr.yp.to/docs/selfpipe.html
109     #
110     # * The workers immediately close the pipe they inherit from the
111     # master and replace it with a new pipe after forking.  This new
112     # pipe is also used to wakeup from IO.select from inside (worker)
113     # signal handlers.  However, workers *close* the pipe descriptors in
114     # the signal handlers to raise EBADF in IO.select instead of writing
115     # like we do in the master.  We cannot easily use the reader set for
116     # IO.select because LISTENERS is already that set, and it's extra
117     # work (and cycles) to distinguish the pipe FD from the reader set
118     # once IO.select returns.  So we're lazy and just close the pipe when
119     # a (rare) signal arrives in the worker and reinitialize the pipe later.
120     SELF_PIPE = []
122     # signal queue used for self-piping
123     SIG_QUEUE = []
125     # constant lookups are faster and we're single-threaded/non-reentrant
126     REQUEST = HttpRequest.new
128     # We populate this at startup so we can figure out how to reexecute
129     # and upgrade the currently running instance of Unicorn
130     # This Hash is considered a stable interface and changing its contents
131     # will allow you to switch between different installations of Unicorn
132     # or even different installations of the same applications without
133     # downtime.  Keys of this constant Hash are described as follows:
134     #
135     # * 0 - the path to the unicorn/unicorn_rails executable
136     # * :argv - a deep copy of the ARGV array the executable originally saw
137     # * :cwd - the working directory of the application, this is where
138     # you originally started Unicorn.
139     #
140     # To change your unicorn executable to a different path without downtime,
141     # you can set the following in your Unicorn config file, HUP and then
142     # continue with the traditional USR2 + QUIT upgrade steps:
143     #
144     #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
145     START_CTX = {
146       :argv => ARGV.map { |arg| arg.dup },
147       :cwd => lambda {
148           # favor ENV['PWD'] since it is (usually) symlink aware for
149           # Capistrano and like systems
150           begin
151             a = File.stat(pwd = ENV['PWD'])
152             b = File.stat(Dir.pwd)
153             a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
154           rescue
155             Dir.pwd
156           end
157         }.call,
158       0 => $0.dup,
159     }
161     # This class and its members can be considered a stable interface
162     # and will not change in a backwards-incompatible fashion between
163     # releases of Unicorn.  You may need to access it in the
164     # before_fork/after_fork hooks.  See the Unicorn::Configurator RDoc
165     # for examples.
166     class Worker < Struct.new(:nr, :tmp, :switched)
168       # worker objects may be compared to just plain numbers
169       def ==(other_nr)
170         self.nr == other_nr
171       end
173       # Changes the worker process to the specified +user+ and +group+
174       # This is only intended to be called from within the worker
175       # process from the +after_fork+ hook.  This should be called in
176       # the +after_fork+ hook after any priviledged functions need to be
177       # run (e.g. to set per-worker CPU affinity, niceness, etc)
178       #
179       # Any and all errors raised within this method will be propagated
180       # directly back to the caller (usually the +after_fork+ hook.
181       # These errors commonly include ArgumentError for specifying an
182       # invalid user/group and Errno::EPERM for insufficient priviledges
183       def user(user, group = nil)
184         # we do not protect the caller, checking Process.euid == 0 is
185         # insufficient because modern systems have fine-grained
186         # capabilities.  Let the caller handle any and all errors.
187         uid = Etc.getpwnam(user).uid
188         gid = Etc.getgrnam(group).gid if group
189         Unicorn::Util.chown_logs(uid, gid)
190         tmp.chown(uid, gid)
191         if gid && Process.egid != gid
192           Process.initgroups(user, gid)
193           Process::GID.change_privilege(gid)
194         end
195         Process.euid != uid and Process::UID.change_privilege(uid)
196         self.switched = true
197       end
199     end
201     # Creates a working server on host:port (strange things happen if
202     # port isn't a Number).  Use HttpServer::run to start the server and
203     # HttpServer.run.join to join the thread that's processing
204     # incoming requests on the socket.
205     def initialize(app, options = {})
206       self.app = app
207       self.reexec_pid = 0
208       self.ready_pipe = options.delete(:ready_pipe)
209       self.init_listeners = options[:listeners] ? options[:listeners].dup : []
210       self.config = Configurator.new(options.merge(:use_defaults => true))
211       self.listener_opts = {}
213       # we try inheriting listeners first, so we bind them later.
214       # we don't write the pid file until we've bound listeners in case
215       # unicorn was started twice by mistake.  Even though our #pid= method
216       # checks for stale/existing pid files, race conditions are still
217       # possible (and difficult/non-portable to avoid) and can be likely
218       # to clobber the pid if the second start was in quick succession
219       # after the first, so we rely on the listener binding to fail in
220       # that case.  Some tests (in and outside of this source tree) and
221       # monitoring tools may also rely on pid files existing before we
222       # attempt to connect to the listener(s)
223       config.commit!(self, :skip => [:listeners, :pid])
224       self.orig_app = app
225     end
227     # Runs the thing.  Returns self so you can run join on it
228     def start
229       BasicSocket.do_not_reverse_lookup = true
231       # inherit sockets from parents, they need to be plain Socket objects
232       # before they become UNIXServer or TCPServer
233       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
234         io = Socket.for_fd(fd.to_i)
235         set_server_sockopt(io, listener_opts[sock_name(io)])
236         IO_PURGATORY << io
237         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
238         server_cast(io)
239       end
241       config_listeners = config[:listeners].dup
242       LISTENERS.replace(inherited)
244       # we start out with generic Socket objects that get cast to either
245       # TCPServer or UNIXServer objects; but since the Socket objects
246       # share the same OS-level file descriptor as the higher-level *Server
247       # objects; we need to prevent Socket objects from being garbage-collected
248       config_listeners -= listener_names
249       if config_listeners.empty? && LISTENERS.empty?
250         config_listeners << Unicorn::Const::DEFAULT_LISTEN
251         init_listeners << Unicorn::Const::DEFAULT_LISTEN
252         START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
253       end
254       config_listeners.each { |addr| listen(addr) }
255       raise ArgumentError, "no listeners" if LISTENERS.empty?
257       # this pipe is used to wake us up from select(2) in #join when signals
258       # are trapped.  See trap_deferred.
259       init_self_pipe!
261       # setup signal handlers before writing pid file in case people get
262       # trigger happy and send signals as soon as the pid file exists.
263       # Note that signals don't actually get handled until the #join method
264       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
265       trap(:CHLD) { |_| awaken_master }
266       self.pid = config[:pid]
268       self.master_pid = $$
269       build_app! if preload_app
270       maintain_worker_count
271       self
272     end
274     # replaces current listener set with +listeners+.  This will
275     # close the socket if it will not exist in the new listener set
276     def listeners=(listeners)
277       cur_names, dead_names = [], []
278       listener_names.each do |name|
279         if ?/ == name[0]
280           # mark unlinked sockets as dead so we can rebind them
281           (File.socket?(name) ? cur_names : dead_names) << name
282         else
283           cur_names << name
284         end
285       end
286       set_names = listener_names(listeners)
287       dead_names.concat(cur_names - set_names).uniq!
289       LISTENERS.delete_if do |io|
290         if dead_names.include?(sock_name(io))
291           IO_PURGATORY.delete_if do |pio|
292             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
293           end
294           (io.close rescue nil).nil? # true
295         else
296           set_server_sockopt(io, listener_opts[sock_name(io)])
297           false
298         end
299       end
301       (set_names - cur_names).each { |addr| listen(addr) }
302     end
304     def stdout_path=(path); redirect_io($stdout, path); end
305     def stderr_path=(path); redirect_io($stderr, path); end
307     def logger=(obj)
308       HttpRequest::DEFAULTS["rack.logger"] = super
309     end
311     # sets the path for the PID file of the master process
312     def pid=(path)
313       if path
314         if x = valid_pid?(path)
315           return path if pid && path == pid && x == $$
316           if x == reexec_pid && pid =~ /\.oldbin\z/
317             logger.warn("will not set pid=#{path} while reexec-ed "\
318                         "child is running PID:#{x}")
319             return
320           end
321           raise ArgumentError, "Already running on PID:#{x} " \
322                                "(or pid=#{path} is stale)"
323         end
324       end
325       unlink_pid_safe(pid) if pid
327       if path
328         fp = begin
329           tmp = "#{File.dirname(path)}/#{rand}.#$$"
330           File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
331         rescue Errno::EEXIST
332           retry
333         end
334         fp.syswrite("#$$\n")
335         File.rename(fp.path, path)
336         fp.close
337       end
338       super(path)
339     end
341     # add a given address to the +listeners+ set, idempotently
342     # Allows workers to add a private, per-process listener via the
343     # after_fork hook.  Very useful for debugging and testing.
344     # +:tries+ may be specified as an option for the number of times
345     # to retry, and +:delay+ may be specified as the time in seconds
346     # to delay between retries.
347     # A negative value for +:tries+ indicates the listen will be
348     # retried indefinitely, this is useful when workers belonging to
349     # different masters are spawned during a transparent upgrade.
350     def listen(address, opt = {}.merge(listener_opts[address] || {}))
351       address = config.expand_addr(address)
352       return if String === address && listener_names.include?(address)
354       delay = opt[:delay] || 0.5
355       tries = opt[:tries] || 5
356       begin
357         io = bind_listen(address, opt)
358         unless TCPServer === io || UNIXServer === io
359           IO_PURGATORY << io
360           io = server_cast(io)
361         end
362         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
363         LISTENERS << io
364         io
365       rescue Errno::EADDRINUSE => err
366         logger.error "adding listener failed addr=#{address} (in use)"
367         raise err if tries == 0
368         tries -= 1
369         logger.error "retrying in #{delay} seconds " \
370                      "(#{tries < 0 ? 'infinite' : tries} tries left)"
371         sleep(delay)
372         retry
373       rescue => err
374         logger.fatal "error adding listener addr=#{address}"
375         raise err
376       end
377     end
379     # monitors children and receives signals forever
380     # (or until a termination signal is sent).  This handles signals
381     # one-at-a-time time and we'll happily drop signals in case somebody
382     # is signalling us too often.
383     def join
384       respawn = true
385       last_check = Time.now
387       proc_name 'master'
388       logger.info "master process ready" # test_exec.rb relies on this message
389       if ready_pipe
390         ready_pipe.syswrite($$.to_s)
391         ready_pipe.close rescue nil
392         self.ready_pipe = nil
393       end
394       begin
395         reap_all_workers
396         case SIG_QUEUE.shift
397         when nil
398           # avoid murdering workers after our master process (or the
399           # machine) comes out of suspend/hibernation
400           if (last_check + timeout) >= (last_check = Time.now)
401             murder_lazy_workers
402           else
403             # wait for workers to wakeup on suspend
404             master_sleep(timeout/2.0 + 1)
405           end
406           maintain_worker_count if respawn
407           master_sleep(1)
408         when :QUIT # graceful shutdown
409           break
410         when :TERM, :INT # immediate shutdown
411           stop(false)
412           break
413         when :USR1 # rotate logs
414           logger.info "master reopening logs..."
415           Unicorn::Util.reopen_logs
416           logger.info "master done reopening logs"
417           kill_each_worker(:USR1)
418         when :USR2 # exec binary, stay alive in case something went wrong
419           reexec
420         when :WINCH
421           if Process.ppid == 1 || Process.getpgrp != $$
422             respawn = false
423             logger.info "gracefully stopping all workers"
424             kill_each_worker(:QUIT)
425             self.worker_processes = 0
426           else
427             logger.info "SIGWINCH ignored because we're not daemonized"
428           end
429         when :TTIN
430           respawn = true
431           self.worker_processes += 1
432         when :TTOU
433           self.worker_processes -= 1 if self.worker_processes > 0
434         when :HUP
435           respawn = true
436           if config.config_file
437             load_config!
438           else # exec binary and exit if there's no config file
439             logger.info "config_file not present, reexecuting binary"
440             reexec
441           end
442         end
443       rescue Errno::EINTR
444       rescue => e
445         logger.error "Unhandled master loop exception #{e.inspect}."
446         logger.error e.backtrace.join("\n")
447       end while true
448       stop # gracefully shutdown all workers on our way out
449       logger.info "master complete"
450       unlink_pid_safe(pid) if pid
451     end
453     # Terminates all workers, but does not exit master process
454     def stop(graceful = true)
455       self.listeners = []
456       limit = Time.now + timeout
457       until WORKERS.empty? || Time.now > limit
458         kill_each_worker(graceful ? :QUIT : :TERM)
459         sleep(0.1)
460         reap_all_workers
461       end
462       kill_each_worker(:KILL)
463     end
465     private
467     # list of signals we care about and trap in master.
468     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
469                    :TTIN, :TTOU ]
471     # defer a signal for later processing in #join (master process)
472     def trap_deferred(signal)
473       trap(signal) do |sig_nr|
474         if SIG_QUEUE.size < 5
475           SIG_QUEUE << signal
476           awaken_master
477         else
478           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
479         end
480       end
481     end
483     # wait for a signal hander to wake us up and then consume the pipe
484     # Wake up every second anyways to run murder_lazy_workers
485     def master_sleep(sec)
486       IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
487       SELF_PIPE[0].read_nonblock(Const::CHUNK_SIZE, HttpRequest::BUF)
488       rescue Errno::EAGAIN, Errno::EINTR
489     end
491     def awaken_master
492       SELF_PIPE[1].write_nonblock('.') # wakeup master process from select
493       rescue Errno::EAGAIN, Errno::EINTR
494     end
496     # reaps all unreaped workers
497     def reap_all_workers
498       begin
499         wpid, status = Process.waitpid2(-1, Process::WNOHANG)
500         wpid or return
501         if reexec_pid == wpid
502           logger.error "reaped #{status.inspect} exec()-ed"
503           self.reexec_pid = 0
504           self.pid = pid.chomp('.oldbin') if pid
505           proc_name 'master'
506         else
507           worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
508           m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
509           status.success? ? logger.info(m) : logger.error(m)
510         end
511       rescue Errno::ECHILD
512         break
513       end while true
514     end
516     # reexecutes the START_CTX with a new binary
517     def reexec
518       if reexec_pid > 0
519         begin
520           Process.kill(0, reexec_pid)
521           logger.error "reexec-ed child already running PID:#{reexec_pid}"
522           return
523         rescue Errno::ESRCH
524           self.reexec_pid = 0
525         end
526       end
528       if pid
529         old_pid = "#{pid}.oldbin"
530         prev_pid = pid.dup
531         begin
532           self.pid = old_pid  # clear the path for a new pid file
533         rescue ArgumentError
534           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
535                        "existing pid=#{old_pid}, refusing rexec"
536           return
537         rescue => e
538           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
539           return
540         end
541       end
543       self.reexec_pid = fork do
544         listener_fds = LISTENERS.map { |sock| sock.fileno }
545         ENV['UNICORN_FD'] = listener_fds.join(',')
546         Dir.chdir(START_CTX[:cwd])
547         cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
549         # avoid leaking FDs we don't know about, but let before_exec
550         # unset FD_CLOEXEC, if anything else in the app eventually
551         # relies on FD inheritence.
552         (3..1024).each do |io|
553           next if listener_fds.include?(io)
554           io = IO.for_fd(io) rescue next
555           IO_PURGATORY << io
556           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
557         end
558         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
559         before_exec.call(self)
560         exec(*cmd)
561       end
562       proc_name 'master (old)'
563     end
565     # forcibly terminate all workers that haven't checked in in timeout
566     # seconds.  The timeout is implemented using an unlinked File
567     # shared between the parent process and each worker.  The worker
568     # runs File#chmod to modify the ctime of the File.  If the ctime
569     # is stale for >timeout seconds, then we'll kill the corresponding
570     # worker.
571     def murder_lazy_workers
572       WORKERS.dup.each_pair do |wpid, worker|
573         stat = worker.tmp.stat
574         # skip workers that disable fchmod or have never fchmod-ed
575         stat.mode == 0100600 and next
576         (diff = (Time.now - stat.ctime)) <= timeout and next
577         logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
578                      "(#{diff}s > #{timeout}s), killing"
579         kill_worker(:KILL, wpid) # take no prisoners for timeout violations
580       end
581     end
583     def spawn_missing_workers
584       (0...worker_processes).each do |worker_nr|
585         WORKERS.values.include?(worker_nr) and next
586         worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
587         before_fork.call(self, worker)
588         WORKERS[fork {
589           ready_pipe.close if ready_pipe
590           self.ready_pipe = nil
591           worker_loop(worker)
592         }] = worker
593       end
594     end
596     def maintain_worker_count
597       (off = WORKERS.size - worker_processes) == 0 and return
598       off < 0 and return spawn_missing_workers
599       WORKERS.dup.each_pair { |wpid,w|
600         w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
601       }
602     end
604     # if we get any error, try to write something back to the client
605     # assuming we haven't closed the socket, but don't get hung up
606     # if the socket is already closed or broken.  We'll always ensure
607     # the socket is closed at the end of this function
608     def handle_error(client, e)
609       msg = case e
610       when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
611         Const::ERROR_500_RESPONSE
612       when HttpParserError # try to tell the client they're bad
613         Const::ERROR_400_RESPONSE
614       else
615         logger.error "Read error: #{e.inspect}"
616         logger.error e.backtrace.join("\n")
617         Const::ERROR_500_RESPONSE
618       end
619       client.write_nonblock(msg)
620       client.close
621       rescue
622         nil
623     end
625     # once a client is accepted, it is processed in its entirety here
626     # in 3 easy steps: read request, call app, write app response
627     def process_client(client)
628       client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
629       response = app.call(env = REQUEST.read(client))
631       if 100 == response[0].to_i
632         client.write(Const::EXPECT_100_RESPONSE)
633         env.delete(Const::HTTP_EXPECT)
634         response = app.call(env)
635       end
636       HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
637     rescue => e
638       handle_error(client, e)
639     end
641     # gets rid of stuff the worker has no business keeping track of
642     # to free some resources and drops all sig handlers.
643     # traps for USR1, USR2, and HUP may be set in the after_fork Proc
644     # by the user.
645     def init_worker_process(worker)
646       QUEUE_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       init_self_pipe!
652       WORKERS.values.each { |other| other.tmp.close rescue nil }
653       WORKERS.clear
654       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
655       worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
656       after_fork.call(self, worker) # can drop perms
657       worker.user(*user) if user.kind_of?(Array) && ! worker.switched
658       self.timeout /= 2.0 # halve it for select()
659       build_app! unless preload_app
660     end
662     def reopen_worker_logs(worker_nr)
663       logger.info "worker=#{worker_nr} reopening logs..."
664       Unicorn::Util.reopen_logs
665       logger.info "worker=#{worker_nr} done reopening logs"
666       init_self_pipe!
667     end
669     # runs inside each forked worker, this sits around and waits
670     # for connections and doesn't die until the parent dies (or is
671     # given a INT, QUIT, or TERM signal)
672     def worker_loop(worker)
673       ppid = master_pid
674       init_worker_process(worker)
675       nr = 0 # this becomes negative if we need to reopen logs
676       alive = worker.tmp # tmp is our lifeline to the master process
677       ready = LISTENERS
679       # closing anything we IO.select on will raise EBADF
680       trap(:USR1) { nr = -65536; SELF_PIPE[0].close rescue nil }
681       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
682       [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
683       logger.info "worker=#{worker.nr} ready"
684       m = 0
686       begin
687         nr < 0 and reopen_worker_logs(worker.nr)
688         nr = 0
690         # we're a goner in timeout seconds anyways if alive.chmod
691         # breaks, so don't trap the exception.  Using fchmod() since
692         # futimes() is not available in base Ruby and I very strongly
693         # prefer temporary files to be unlinked for security,
694         # performance and reliability reasons, so utime is out.  No-op
695         # changes with chmod doesn't update ctime on all filesystems; so
696         # we change our counter each and every time (after process_client
697         # and before IO.select).
698         alive.chmod(m = 0 == m ? 1 : 0)
700         ready.each do |sock|
701           begin
702             process_client(sock.accept_nonblock)
703             nr += 1
704             alive.chmod(m = 0 == m ? 1 : 0)
705           rescue Errno::EAGAIN, Errno::ECONNABORTED
706           end
707           break if nr < 0
708         end
710         # make the following bet: if we accepted clients this round,
711         # we're probably reasonably busy, so avoid calling select()
712         # and do a speculative accept_nonblock on ready listeners
713         # before we sleep again in select().
714         redo unless nr == 0 # (nr < 0) => reopen logs
716         ppid == Process.ppid or return
717         alive.chmod(m = 0 == m ? 1 : 0)
719         # timeout used so we can detect parent death:
720         ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) and ready = ret[0]
721       rescue Errno::EINTR
722         ready = LISTENERS
723       rescue Errno::EBADF
724         nr < 0 or return
725       rescue => e
726         if alive
727           logger.error "Unhandled listen loop exception #{e.inspect}."
728           logger.error e.backtrace.join("\n")
729         end
730       end while alive
731     end
733     # delivers a signal to a worker and fails gracefully if the worker
734     # is no longer running.
735     def kill_worker(signal, wpid)
736       Process.kill(signal, wpid)
737       rescue Errno::ESRCH
738         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
739     end
741     # delivers a signal to each worker
742     def kill_each_worker(signal)
743       WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
744     end
746     # unlinks a PID file at given +path+ if it contains the current PID
747     # still potentially racy without locking the directory (which is
748     # non-portable and may interact badly with other programs), but the
749     # window for hitting the race condition is small
750     def unlink_pid_safe(path)
751       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
752     end
754     # returns a PID if a given path contains a non-stale PID file,
755     # nil otherwise.
756     def valid_pid?(path)
757       wpid = File.read(path).to_i
758       wpid <= 0 and return
759       Process.kill(0, wpid)
760       wpid
761       rescue Errno::ESRCH, Errno::ENOENT
762         # don't unlink stale pid files, racy without non-portable locking...
763     end
765     def load_config!
766       loaded_app = app
767       logger.info "reloading config_file=#{config.config_file}"
768       config[:listeners].replace(init_listeners)
769       config.reload
770       config.commit!(self)
771       kill_each_worker(:QUIT)
772       Unicorn::Util.reopen_logs
773       self.app = orig_app
774       build_app! if preload_app
775       logger.info "done reloading config_file=#{config.config_file}"
776     rescue StandardError, LoadError, SyntaxError => e
777       logger.error "error reloading config_file=#{config.config_file}: " \
778                    "#{e.class} #{e.message} #{e.backtrace}"
779       self.app = loaded_app
780     end
782     # returns an array of string names for the given listener array
783     def listener_names(listeners = LISTENERS)
784       listeners.map { |io| sock_name(io) }
785     end
787     def build_app!
788       if app.respond_to?(:arity) && app.arity == 0
789         if defined?(Gem) && Gem.respond_to?(:refresh)
790           logger.info "Refreshing Gem list"
791           Gem.refresh
792         end
793         self.app = app.call
794       end
795     end
797     def proc_name(tag)
798       $0 = ([ File.basename(START_CTX[0]), tag
799             ]).concat(START_CTX[:argv]).join(' ')
800     end
802     def redirect_io(io, path)
803       File.open(path, 'ab') { |fp| io.reopen(fp) } if path
804       io.sync = true
805     end
807     def init_self_pipe!
808       SELF_PIPE.each { |io| io.close rescue nil }
809       SELF_PIPE.replace(IO.pipe)
810       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
811     end
813   end