always load Rack up front at startup
[unicorn.git] / lib / unicorn.rb
blob70222f4b52c79a70ae9992c3efd8f0328272cbcc
1 # -*- encoding: binary -*-
3 require 'fcntl'
4 require 'etc'
5 require 'rack'
6 require 'unicorn/socket_helper'
7 require 'unicorn/const'
8 require 'unicorn/http_request'
9 require 'unicorn/configurator'
10 require 'unicorn/util'
11 require 'unicorn/tee_input'
12 require 'unicorn/http_response'
14 # Unicorn module containing all of the classes (include C extensions) for running
15 # a Unicorn web server.  It contains a minimalist HTTP server with just enough
16 # functionality to service web application requests fast as possible.
17 module Unicorn
19   # raised inside TeeInput when a client closes the socket inside the
20   # application dispatch.  This is always raised with an empty backtrace
21   # since there is nothing in the application stack that is responsible
22   # for client shutdowns/disconnects.
23   class ClientShutdown < EOFError
24   end
26   class << self
27     def run(app, options = {})
28       HttpServer.new(app, options).start.join
29     end
31     # This returns a lambda to pass in as the app, this does not "build" the
32     # app (which we defer based on the outcome of "preload_app" in the
33     # Unicorn config).  The returned lambda will be called when it is
34     # time to build the app.
35     def builder(ru, opts)
36       if ru =~ /\.ru\z/
37         # parse embedded command-line options in config.ru comments
38         /^#\\(.*)/ =~ File.read(ru) and opts.parse!($1.split(/\s+/))
39       end
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     # The following example may be used in your Unicorn config file to
141     # change your working directory during a config reload (HUP) without
142     # upgrading or restarting:
143     #
144     #   Dir.chdir(Unicorn::HttpServer::START_CTX[:cwd] = path)
145     #
146     # To change your unicorn executable to a different path without downtime,
147     # you can set the following in your Unicorn config file, HUP and then
148     # continue with the traditional USR2 + QUIT upgrade steps:
149     #
150     #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
151     START_CTX = {
152       :argv => ARGV.map { |arg| arg.dup },
153       :cwd => lambda {
154           # favor ENV['PWD'] since it is (usually) symlink aware for
155           # Capistrano and like systems
156           begin
157             a = File.stat(pwd = ENV['PWD'])
158             b = File.stat(Dir.pwd)
159             a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
160           rescue
161             Dir.pwd
162           end
163         }.call,
164       0 => $0.dup,
165     }
167     # This class and its members can be considered a stable interface
168     # and will not change in a backwards-incompatible fashion between
169     # releases of Unicorn.  You may need to access it in the
170     # before_fork/after_fork hooks.  See the Unicorn::Configurator RDoc
171     # for examples.
172     class Worker < Struct.new(:nr, :tmp, :switched)
174       # worker objects may be compared to just plain numbers
175       def ==(other_nr)
176         self.nr == other_nr
177       end
179       # Changes the worker process to the specified +user+ and +group+
180       # This is only intended to be called from within the worker
181       # process from the +after_fork+ hook.  This should be called in
182       # the +after_fork+ hook after any priviledged functions need to be
183       # run (e.g. to set per-worker CPU affinity, niceness, etc)
184       #
185       # Any and all errors raised within this method will be propagated
186       # directly back to the caller (usually the +after_fork+ hook.
187       # These errors commonly include ArgumentError for specifying an
188       # invalid user/group and Errno::EPERM for insufficient priviledges
189       def user(user, group = nil)
190         # we do not protect the caller, checking Process.euid == 0 is
191         # insufficient because modern systems have fine-grained
192         # capabilities.  Let the caller handle any and all errors.
193         uid = Etc.getpwnam(user).uid
194         gid = Etc.getgrnam(group).gid if group
195         Unicorn::Util.chown_logs(uid, gid)
196         tmp.chown(uid, gid)
197         if gid && Process.egid != gid
198           Process.initgroups(user, gid)
199           Process::GID.change_privilege(gid)
200         end
201         Process.euid != uid and Process::UID.change_privilege(uid)
202         self.switched = true
203       end
205     end
207     # Creates a working server on host:port (strange things happen if
208     # port isn't a Number).  Use HttpServer::run to start the server and
209     # HttpServer.run.join to join the thread that's processing
210     # incoming requests on the socket.
211     def initialize(app, options = {})
212       self.app = app
213       self.reexec_pid = 0
214       self.ready_pipe = options.delete(:ready_pipe)
215       self.init_listeners = options[:listeners] ? options[:listeners].dup : []
216       self.config = Configurator.new(options.merge(:use_defaults => true))
217       self.listener_opts = {}
219       # we try inheriting listeners first, so we bind them later.
220       # we don't write the pid file until we've bound listeners in case
221       # unicorn was started twice by mistake.  Even though our #pid= method
222       # checks for stale/existing pid files, race conditions are still
223       # possible (and difficult/non-portable to avoid) and can be likely
224       # to clobber the pid if the second start was in quick succession
225       # after the first, so we rely on the listener binding to fail in
226       # that case.  Some tests (in and outside of this source tree) and
227       # monitoring tools may also rely on pid files existing before we
228       # attempt to connect to the listener(s)
229       config.commit!(self, :skip => [:listeners, :pid])
230       self.orig_app = app
231     end
233     # Runs the thing.  Returns self so you can run join on it
234     def start
235       BasicSocket.do_not_reverse_lookup = true
237       # inherit sockets from parents, they need to be plain Socket objects
238       # before they become UNIXServer or TCPServer
239       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
240         io = Socket.for_fd(fd.to_i)
241         set_server_sockopt(io, listener_opts[sock_name(io)])
242         IO_PURGATORY << io
243         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
244         server_cast(io)
245       end
247       config_listeners = config[:listeners].dup
248       LISTENERS.replace(inherited)
250       # we start out with generic Socket objects that get cast to either
251       # TCPServer or UNIXServer objects; but since the Socket objects
252       # share the same OS-level file descriptor as the higher-level *Server
253       # objects; we need to prevent Socket objects from being garbage-collected
254       config_listeners -= listener_names
255       if config_listeners.empty? && LISTENERS.empty?
256         config_listeners << Unicorn::Const::DEFAULT_LISTEN
257         init_listeners << Unicorn::Const::DEFAULT_LISTEN
258         START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
259       end
260       config_listeners.each { |addr| listen(addr) }
261       raise ArgumentError, "no listeners" if LISTENERS.empty?
263       # this pipe is used to wake us up from select(2) in #join when signals
264       # are trapped.  See trap_deferred.
265       init_self_pipe!
267       # setup signal handlers before writing pid file in case people get
268       # trigger happy and send signals as soon as the pid file exists.
269       # Note that signals don't actually get handled until the #join method
270       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
271       trap(:CHLD) { |_| awaken_master }
272       self.pid = config[:pid]
274       self.master_pid = $$
275       build_app! if preload_app
276       maintain_worker_count
277       self
278     end
280     # replaces current listener set with +listeners+.  This will
281     # close the socket if it will not exist in the new listener set
282     def listeners=(listeners)
283       cur_names, dead_names = [], []
284       listener_names.each do |name|
285         if ?/ == name[0]
286           # mark unlinked sockets as dead so we can rebind them
287           (File.socket?(name) ? cur_names : dead_names) << name
288         else
289           cur_names << name
290         end
291       end
292       set_names = listener_names(listeners)
293       dead_names.concat(cur_names - set_names).uniq!
295       LISTENERS.delete_if do |io|
296         if dead_names.include?(sock_name(io))
297           IO_PURGATORY.delete_if do |pio|
298             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
299           end
300           (io.close rescue nil).nil? # true
301         else
302           set_server_sockopt(io, listener_opts[sock_name(io)])
303           false
304         end
305       end
307       (set_names - cur_names).each { |addr| listen(addr) }
308     end
310     def stdout_path=(path); redirect_io($stdout, path); end
311     def stderr_path=(path); redirect_io($stderr, path); end
313     def logger=(obj)
314       HttpRequest::DEFAULTS["rack.logger"] = super
315     end
317     # sets the path for the PID file of the master process
318     def pid=(path)
319       if path
320         if x = valid_pid?(path)
321           return path if pid && path == pid && x == $$
322           raise ArgumentError, "Already running on PID:#{x} " \
323                                "(or pid=#{path} is stale)"
324         end
325       end
326       unlink_pid_safe(pid) if pid
328       if path
329         fp = begin
330           tmp = "#{File.dirname(path)}/#{rand}.#$$"
331           File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
332         rescue Errno::EEXIST
333           retry
334         end
335         fp.syswrite("#$$\n")
336         File.rename(fp.path, path)
337         fp.close
338       end
339       super(path)
340     end
342     # add a given address to the +listeners+ set, idempotently
343     # Allows workers to add a private, per-process listener via the
344     # after_fork hook.  Very useful for debugging and testing.
345     # +:tries+ may be specified as an option for the number of times
346     # to retry, and +:delay+ may be specified as the time in seconds
347     # to delay between retries.
348     # A negative value for +:tries+ indicates the listen will be
349     # retried indefinitely, this is useful when workers belonging to
350     # different masters are spawned during a transparent upgrade.
351     def listen(address, opt = {}.merge(listener_opts[address] || {}))
352       address = config.expand_addr(address)
353       return if String === address && listener_names.include?(address)
355       delay = opt[:delay] || 0.5
356       tries = opt[:tries] || 5
357       begin
358         io = bind_listen(address, opt)
359         unless TCPServer === io || UNIXServer === io
360           IO_PURGATORY << io
361           io = server_cast(io)
362         end
363         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
364         LISTENERS << io
365         io
366       rescue Errno::EADDRINUSE => err
367         logger.error "adding listener failed addr=#{address} (in use)"
368         raise err if tries == 0
369         tries -= 1
370         logger.error "retrying in #{delay} seconds " \
371                      "(#{tries < 0 ? 'infinite' : tries} tries left)"
372         sleep(delay)
373         retry
374       rescue => err
375         logger.fatal "error adding listener addr=#{address}"
376         raise err
377       end
378     end
380     # monitors children and receives signals forever
381     # (or until a termination signal is sent).  This handles signals
382     # one-at-a-time time and we'll happily drop signals in case somebody
383     # is signalling us too often.
384     def join
385       respawn = true
386       last_check = Time.now
388       proc_name 'master'
389       logger.info "master process ready" # test_exec.rb relies on this message
390       if ready_pipe
391         ready_pipe.syswrite($$.to_s)
392         ready_pipe.close rescue nil
393         self.ready_pipe = nil
394       end
395       begin
396         loop do
397           reap_all_workers
398           case SIG_QUEUE.shift
399           when nil
400             # avoid murdering workers after our master process (or the
401             # machine) comes out of suspend/hibernation
402             if (last_check + timeout) >= (last_check = Time.now)
403               murder_lazy_workers
404             else
405               # wait for workers to wakeup on suspend
406               master_sleep(timeout/2.0 + 1)
407             end
408             maintain_worker_count if respawn
409             master_sleep(1)
410           when :QUIT # graceful shutdown
411             break
412           when :TERM, :INT # immediate shutdown
413             stop(false)
414             break
415           when :USR1 # rotate logs
416             logger.info "master reopening logs..."
417             Unicorn::Util.reopen_logs
418             logger.info "master done reopening logs"
419             kill_each_worker(:USR1)
420           when :USR2 # exec binary, stay alive in case something went wrong
421             reexec
422           when :WINCH
423             if Process.ppid == 1 || Process.getpgrp != $$
424               respawn = false
425               logger.info "gracefully stopping all workers"
426               kill_each_worker(:QUIT)
427             else
428               logger.info "SIGWINCH ignored because we're not daemonized"
429             end
430           when :TTIN
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               redo # immediate reaping since we may have QUIT workers
439             else # exec binary and exit if there's no config file
440               logger.info "config_file not present, reexecuting binary"
441               reexec
442               break
443             end
444           end
445         end
446       rescue Errno::EINTR
447         retry
448       rescue => e
449         logger.error "Unhandled master loop exception #{e.inspect}."
450         logger.error e.backtrace.join("\n")
451         retry
452       end
453       stop # gracefully shutdown all workers on our way out
454       logger.info "master complete"
455       unlink_pid_safe(pid) if pid
456     end
458     # Terminates all workers, but does not exit master process
459     def stop(graceful = true)
460       self.listeners = []
461       limit = Time.now + timeout
462       until WORKERS.empty? || Time.now > limit
463         kill_each_worker(graceful ? :QUIT : :TERM)
464         sleep(0.1)
465         reap_all_workers
466       end
467       kill_each_worker(:KILL)
468     end
470     private
472     # list of signals we care about and trap in master.
473     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
474                    :TTIN, :TTOU ]
476     # defer a signal for later processing in #join (master process)
477     def trap_deferred(signal)
478       trap(signal) do |sig_nr|
479         if SIG_QUEUE.size < 5
480           SIG_QUEUE << signal
481           awaken_master
482         else
483           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
484         end
485       end
486     end
488     # wait for a signal hander to wake us up and then consume the pipe
489     # Wake up every second anyways to run murder_lazy_workers
490     def master_sleep(sec)
491       begin
492         ready = IO.select([SELF_PIPE.first], nil, nil, sec) or return
493         ready.first && ready.first.first or return
494         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
495       rescue Errno::EAGAIN, Errno::EINTR
496       end
497     end
499     def awaken_master
500       begin
501         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
502       rescue Errno::EAGAIN, Errno::EINTR
503         # pipe is full, master should wake up anyways
504         retry
505       end
506     end
508     # reaps all unreaped workers
509     def reap_all_workers
510       begin
511         loop do
512           wpid, status = Process.waitpid2(-1, Process::WNOHANG)
513           wpid or break
514           if reexec_pid == wpid
515             logger.error "reaped #{status.inspect} exec()-ed"
516             self.reexec_pid = 0
517             self.pid = pid.chomp('.oldbin') if pid
518             proc_name 'master'
519           else
520             worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
521             logger.info "reaped #{status.inspect} " \
522                         "worker=#{worker.nr rescue 'unknown'}"
523           end
524         end
525       rescue Errno::ECHILD
526       end
527     end
529     # reexecutes the START_CTX with a new binary
530     def reexec
531       if reexec_pid > 0
532         begin
533           Process.kill(0, reexec_pid)
534           logger.error "reexec-ed child already running PID:#{reexec_pid}"
535           return
536         rescue Errno::ESRCH
537           self.reexec_pid = 0
538         end
539       end
541       if pid
542         old_pid = "#{pid}.oldbin"
543         prev_pid = pid.dup
544         begin
545           self.pid = old_pid  # clear the path for a new pid file
546         rescue ArgumentError
547           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
548                        "existing pid=#{old_pid}, refusing rexec"
549           return
550         rescue => e
551           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
552           return
553         end
554       end
556       self.reexec_pid = fork do
557         listener_fds = LISTENERS.map { |sock| sock.fileno }
558         ENV['UNICORN_FD'] = listener_fds.join(',')
559         Dir.chdir(START_CTX[:cwd])
560         cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
562         # avoid leaking FDs we don't know about, but let before_exec
563         # unset FD_CLOEXEC, if anything else in the app eventually
564         # relies on FD inheritence.
565         (3..1024).each do |io|
566           next if listener_fds.include?(io)
567           io = IO.for_fd(io) rescue nil
568           io or next
569           IO_PURGATORY << io
570           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
571         end
572         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
573         before_exec.call(self)
574         exec(*cmd)
575       end
576       proc_name 'master (old)'
577     end
579     # forcibly terminate all workers that haven't checked in in timeout
580     # seconds.  The timeout is implemented using an unlinked File
581     # shared between the parent process and each worker.  The worker
582     # runs File#chmod to modify the ctime of the File.  If the ctime
583     # is stale for >timeout seconds, then we'll kill the corresponding
584     # worker.
585     def murder_lazy_workers
586       WORKERS.dup.each_pair do |wpid, worker|
587         stat = worker.tmp.stat
588         # skip workers that disable fchmod or have never fchmod-ed
589         stat.mode == 0100600 and next
590         (diff = (Time.now - stat.ctime)) <= timeout and next
591         logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
592                      "(#{diff}s > #{timeout}s), killing"
593         kill_worker(:KILL, wpid) # take no prisoners for timeout violations
594       end
595     end
597     def spawn_missing_workers
598       (0...worker_processes).each do |worker_nr|
599         WORKERS.values.include?(worker_nr) and next
600         worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
601         before_fork.call(self, worker)
602         WORKERS[fork {
603           ready_pipe.close if ready_pipe
604           self.ready_pipe = nil
605           worker_loop(worker)
606         }] = worker
607       end
608     end
610     def maintain_worker_count
611       (off = WORKERS.size - worker_processes) == 0 and return
612       off < 0 and return spawn_missing_workers
613       WORKERS.dup.each_pair { |wpid,w|
614         w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
615       }
616     end
618     # if we get any error, try to write something back to the client
619     # assuming we haven't closed the socket, but don't get hung up
620     # if the socket is already closed or broken.  We'll always ensure
621     # the socket is closed at the end of this function
622     def handle_error(client, e)
623       msg = case e
624       when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
625         Const::ERROR_500_RESPONSE
626       when HttpParserError # try to tell the client they're bad
627         Const::ERROR_400_RESPONSE
628       else
629         logger.error "Read error: #{e.inspect}"
630         logger.error e.backtrace.join("\n")
631         Const::ERROR_500_RESPONSE
632       end
633       client.write_nonblock(msg)
634       client.close
635       rescue
636         nil
637     end
639     # once a client is accepted, it is processed in its entirety here
640     # in 3 easy steps: read request, call app, write app response
641     def process_client(client)
642       client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
643       response = app.call(env = REQUEST.read(client))
645       if 100 == response.first.to_i
646         client.write(Const::EXPECT_100_RESPONSE)
647         env.delete(Const::HTTP_EXPECT)
648         response = app.call(env)
649       end
650       HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
651     rescue => e
652       handle_error(client, e)
653     end
655     # gets rid of stuff the worker has no business keeping track of
656     # to free some resources and drops all sig handlers.
657     # traps for USR1, USR2, and HUP may be set in the after_fork Proc
658     # by the user.
659     def init_worker_process(worker)
660       QUEUE_SIGS.each { |sig| trap(sig, nil) }
661       trap(:CHLD, 'DEFAULT')
662       SIG_QUEUE.clear
663       proc_name "worker[#{worker.nr}]"
664       START_CTX.clear
665       init_self_pipe!
666       WORKERS.values.each { |other| other.tmp.close rescue nil }
667       WORKERS.clear
668       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
669       worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
670       after_fork.call(self, worker) # can drop perms
671       worker.user(*user) if user.kind_of?(Array) && ! worker.switched
672       self.timeout /= 2.0 # halve it for select()
673       build_app! unless preload_app
674     end
676     def reopen_worker_logs(worker_nr)
677       logger.info "worker=#{worker_nr} reopening logs..."
678       Unicorn::Util.reopen_logs
679       logger.info "worker=#{worker_nr} done reopening logs"
680       init_self_pipe!
681     end
683     # runs inside each forked worker, this sits around and waits
684     # for connections and doesn't die until the parent dies (or is
685     # given a INT, QUIT, or TERM signal)
686     def worker_loop(worker)
687       ppid = master_pid
688       init_worker_process(worker)
689       nr = 0 # this becomes negative if we need to reopen logs
690       alive = worker.tmp # tmp is our lifeline to the master process
691       ready = LISTENERS
693       # closing anything we IO.select on will raise EBADF
694       trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
695       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
696       [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
697       logger.info "worker=#{worker.nr} ready"
698       m = 0
700       begin
701         nr < 0 and reopen_worker_logs(worker.nr)
702         nr = 0
704         # we're a goner in timeout seconds anyways if alive.chmod
705         # breaks, so don't trap the exception.  Using fchmod() since
706         # futimes() is not available in base Ruby and I very strongly
707         # prefer temporary files to be unlinked for security,
708         # performance and reliability reasons, so utime is out.  No-op
709         # changes with chmod doesn't update ctime on all filesystems; so
710         # we change our counter each and every time (after process_client
711         # and before IO.select).
712         alive.chmod(m = 0 == m ? 1 : 0)
714         ready.each do |sock|
715           begin
716             process_client(sock.accept_nonblock)
717             nr += 1
718             alive.chmod(m = 0 == m ? 1 : 0)
719           rescue Errno::EAGAIN, Errno::ECONNABORTED
720           end
721           break if nr < 0
722         end
724         # make the following bet: if we accepted clients this round,
725         # we're probably reasonably busy, so avoid calling select()
726         # and do a speculative accept_nonblock on ready listeners
727         # before we sleep again in select().
728         redo unless nr == 0 # (nr < 0) => reopen logs
730         ppid == Process.ppid or return
731         alive.chmod(m = 0 == m ? 1 : 0)
732         begin
733           # timeout used so we can detect parent death:
734           ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
735           ready = ret.first
736         rescue Errno::EINTR
737           ready = LISTENERS
738         rescue Errno::EBADF
739           nr < 0 or return
740         end
741       rescue => e
742         if alive
743           logger.error "Unhandled listen loop exception #{e.inspect}."
744           logger.error e.backtrace.join("\n")
745         end
746       end while alive
747     end
749     # delivers a signal to a worker and fails gracefully if the worker
750     # is no longer running.
751     def kill_worker(signal, wpid)
752       begin
753         Process.kill(signal, wpid)
754       rescue Errno::ESRCH
755         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
756       end
757     end
759     # delivers a signal to each worker
760     def kill_each_worker(signal)
761       WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
762     end
764     # unlinks a PID file at given +path+ if it contains the current PID
765     # still potentially racy without locking the directory (which is
766     # non-portable and may interact badly with other programs), but the
767     # window for hitting the race condition is small
768     def unlink_pid_safe(path)
769       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
770     end
772     # returns a PID if a given path contains a non-stale PID file,
773     # nil otherwise.
774     def valid_pid?(path)
775       wpid = File.read(path).to_i
776       wpid <= 0 and return nil
777       begin
778         Process.kill(0, wpid)
779         wpid
780       rescue Errno::ESRCH
781         # don't unlink stale pid files, racy without non-portable locking...
782       end
783       rescue Errno::ENOENT
784     end
786     def load_config!
787       loaded_app = app
788       begin
789         logger.info "reloading config_file=#{config.config_file}"
790         config[:listeners].replace(init_listeners)
791         config.reload
792         config.commit!(self)
793         kill_each_worker(:QUIT)
794         Unicorn::Util.reopen_logs
795         self.app = orig_app
796         build_app! if preload_app
797         logger.info "done reloading config_file=#{config.config_file}"
798       rescue StandardError, LoadError, SyntaxError => e
799         logger.error "error reloading config_file=#{config.config_file}: " \
800                      "#{e.class} #{e.message}"
801         self.app = loaded_app
802       end
803     end
805     # returns an array of string names for the given listener array
806     def listener_names(listeners = LISTENERS)
807       listeners.map { |io| sock_name(io) }
808     end
810     def build_app!
811       if app.respond_to?(:arity) && app.arity == 0
812         if defined?(Gem) && Gem.respond_to?(:refresh)
813           logger.info "Refreshing Gem list"
814           Gem.refresh
815         end
816         self.app = app.call
817       end
818     end
820     def proc_name(tag)
821       $0 = ([ File.basename(START_CTX[0]), tag
822             ]).concat(START_CTX[:argv]).join(' ')
823     end
825     def redirect_io(io, path)
826       File.open(path, 'ab') { |fp| io.reopen(fp) } if path
827       io.sync = true
828     end
830     def init_self_pipe!
831       SELF_PIPE.each { |io| io.close rescue nil }
832       SELF_PIPE.replace(IO.pipe)
833       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
834     end
836   end