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