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