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