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