remove SSL support
[unicorn.git] / lib / unicorn / http_server.rb
bloba523fce13fe128c5e47f666abe9f80af5bec43f7
1 # -*- encoding: binary -*-
3 # This is the process manager of Unicorn. This manages worker
4 # processes which in turn handle the I/O and application process.
5 # Listener sockets are started in the master process and shared with
6 # forked worker children.
8 # Users do not need to know the internals of this class, but reading the
9 # {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb]
10 # is education for programmers wishing to learn how \Unicorn works.
11 # See Unicorn::Configurator for information on how to configure \Unicorn.
12 class Unicorn::HttpServer
13   # :stopdoc:
14   attr_accessor :app, :request, :timeout, :worker_processes,
15                 :before_fork, :after_fork, :before_exec,
16                 :listener_opts, :preload_app,
17                 :reexec_pid, :orig_app, :init_listeners,
18                 :master_pid, :config, :ready_pipe, :user
20   attr_reader :pid, :logger
21   include Unicorn::SocketHelper
22   include Unicorn::HttpResponse
24   # backwards compatibility with 1.x
25   Worker = Unicorn::Worker
27   # all bound listener sockets
28   LISTENERS = []
30   # listeners we have yet to bind
31   NEW_LISTENERS = []
33   # This hash maps PIDs to Workers
34   WORKERS = {}
36   # We use SELF_PIPE differently in the master and worker processes:
37   #
38   # * The master process never closes or reinitializes this once
39   # initialized.  Signal handlers in the master process will write to
40   # it to wake up the master from IO.select in exactly the same manner
41   # djb describes in http://cr.yp.to/docs/selfpipe.html
42   #
43   # * The workers immediately close the pipe they inherit.  See the
44   # Unicorn::Worker class for the pipe workers use.
45   SELF_PIPE = []
47   # signal queue used for self-piping
48   SIG_QUEUE = []
50   # list of signals we care about and trap in master.
51   QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ]
53   # :startdoc:
54   # We populate this at startup so we can figure out how to reexecute
55   # and upgrade the currently running instance of Unicorn
56   # This Hash is considered a stable interface and changing its contents
57   # will allow you to switch between different installations of Unicorn
58   # or even different installations of the same applications without
59   # downtime.  Keys of this constant Hash are described as follows:
60   #
61   # * 0 - the path to the unicorn/unicorn_rails executable
62   # * :argv - a deep copy of the ARGV array the executable originally saw
63   # * :cwd - the working directory of the application, this is where
64   # you originally started Unicorn.
65   #
66   # To change your unicorn executable to a different path without downtime,
67   # you can set the following in your Unicorn config file, HUP and then
68   # continue with the traditional USR2 + QUIT upgrade steps:
69   #
70   #   Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn"
71   START_CTX = {
72     :argv => ARGV.map { |arg| arg.dup },
73     0 => $0.dup,
74   }
75   # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano
76   # and like systems
77   START_CTX[:cwd] = begin
78     a = File.stat(pwd = ENV['PWD'])
79     b = File.stat(Dir.pwd)
80     a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd
81   rescue
82     Dir.pwd
83   end
84   # :stopdoc:
86   # Creates a working server on host:port (strange things happen if
87   # port isn't a Number).  Use HttpServer::run to start the server and
88   # HttpServer.run.join to join the thread that's processing
89   # incoming requests on the socket.
90   def initialize(app, options = {})
91     @app = app
92     @request = Unicorn::HttpRequest.new
93     self.reexec_pid = 0
94     options = options.dup
95     @ready_pipe = options.delete(:ready_pipe)
96     @init_listeners = options[:listeners] ? options[:listeners].dup : []
97     options[:use_defaults] = true
98     self.config = Unicorn::Configurator.new(options)
99     self.listener_opts = {}
101     # we try inheriting listeners first, so we bind them later.
102     # we don't write the pid file until we've bound listeners in case
103     # unicorn was started twice by mistake.  Even though our #pid= method
104     # checks for stale/existing pid files, race conditions are still
105     # possible (and difficult/non-portable to avoid) and can be likely
106     # to clobber the pid if the second start was in quick succession
107     # after the first, so we rely on the listener binding to fail in
108     # that case.  Some tests (in and outside of this source tree) and
109     # monitoring tools may also rely on pid files existing before we
110     # attempt to connect to the listener(s)
111     config.commit!(self, :skip => [:listeners, :pid])
112     self.orig_app = app
113   end
115   # Runs the thing.  Returns self so you can run join on it
116   def start
117     inherit_listeners!
118     # this pipe is used to wake us up from select(2) in #join when signals
119     # are trapped.  See trap_deferred.
120     SELF_PIPE.replace(Unicorn.pipe)
121     @master_pid = $$
123     # setup signal handlers before writing pid file in case people get
124     # trigger happy and send signals as soon as the pid file exists.
125     # Note that signals don't actually get handled until the #join method
126     QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } }
127     trap(:CHLD) { awaken_master }
129     # write pid early for Mongrel compatibility if we're not inheriting sockets
130     # This is needed for compatibility some Monit setups at least.
131     # This unfortunately has the side effect of clobbering valid PID if
132     # we upgrade and the upgrade breaks during preload_app==true && build_app!
133     self.pid = config[:pid]
135     build_app! if preload_app
136     bind_new_listeners!
138     spawn_missing_workers
139     self
140   end
142   # replaces current listener set with +listeners+.  This will
143   # close the socket if it will not exist in the new listener set
144   def listeners=(listeners)
145     cur_names, dead_names = [], []
146     listener_names.each do |name|
147       if ?/ == name[0]
148         # mark unlinked sockets as dead so we can rebind them
149         (File.socket?(name) ? cur_names : dead_names) << name
150       else
151         cur_names << name
152       end
153     end
154     set_names = listener_names(listeners)
155     dead_names.concat(cur_names - set_names).uniq!
157     LISTENERS.delete_if do |io|
158       if dead_names.include?(sock_name(io))
159         IO_PURGATORY.delete_if do |pio|
160           pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
161         end
162         (io.close rescue nil).nil? # true
163       else
164         set_server_sockopt(io, listener_opts[sock_name(io)])
165         false
166       end
167     end
169     (set_names - cur_names).each { |addr| listen(addr) }
170   end
172   def stdout_path=(path); redirect_io($stdout, path); end
173   def stderr_path=(path); redirect_io($stderr, path); end
175   def logger=(obj)
176     Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj
177   end
179   def clobber_pid(path)
180     unlink_pid_safe(@pid) if @pid
181     if path
182       fp = begin
183         tmp = "#{File.dirname(path)}/#{rand}.#$$"
184         File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644)
185       rescue Errno::EEXIST
186         retry
187       end
188       fp.syswrite("#$$\n")
189       File.rename(fp.path, path)
190       fp.close
191     end
192   end
194   # sets the path for the PID file of the master process
195   def pid=(path)
196     if path
197       if x = valid_pid?(path)
198         return path if pid && path == pid && x == $$
199         if x == reexec_pid && pid =~ /\.oldbin\z/
200           logger.warn("will not set pid=#{path} while reexec-ed "\
201                       "child is running PID:#{x}")
202           return
203         end
204         raise ArgumentError, "Already running on PID:#{x} " \
205                              "(or pid=#{path} is stale)"
206       end
207     end
209     # rename the old pid if possible
210     if @pid && path
211       begin
212         File.rename(@pid, path)
213       rescue Errno::ENOENT, Errno::EXDEV
214         # a user may have accidentally removed the original,
215         # obviously cross-FS renames don't work, either.
216         clobber_pid(path)
217       end
218     else
219       clobber_pid(path)
220     end
221     @pid = path
222   end
224   # add a given address to the +listeners+ set, idempotently
225   # Allows workers to add a private, per-process listener via the
226   # after_fork hook.  Very useful for debugging and testing.
227   # +:tries+ may be specified as an option for the number of times
228   # to retry, and +:delay+ may be specified as the time in seconds
229   # to delay between retries.
230   # A negative value for +:tries+ indicates the listen will be
231   # retried indefinitely, this is useful when workers belonging to
232   # different masters are spawned during a transparent upgrade.
233   def listen(address, opt = {}.merge(listener_opts[address] || {}))
234     address = config.expand_addr(address)
235     return if String === address && listener_names.include?(address)
237     delay = opt[:delay] || 0.5
238     tries = opt[:tries] || 5
239     begin
240       io = bind_listen(address, opt)
241       unless Kgio::TCPServer === io || Kgio::UNIXServer === io
242         prevent_autoclose(io)
243         io = server_cast(io)
244       end
245       logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
246       LISTENERS << io
247       io
248     rescue Errno::EADDRINUSE => err
249       logger.error "adding listener failed addr=#{address} (in use)"
250       raise err if tries == 0
251       tries -= 1
252       logger.error "retrying in #{delay} seconds " \
253                    "(#{tries < 0 ? 'infinite' : tries} tries left)"
254       sleep(delay)
255       retry
256     rescue => err
257       logger.fatal "error adding listener addr=#{address}"
258       raise err
259     end
260   end
262   # monitors children and receives signals forever
263   # (or until a termination signal is sent).  This handles signals
264   # one-at-a-time time and we'll happily drop signals in case somebody
265   # is signalling us too often.
266   def join
267     respawn = true
268     last_check = Time.now
270     proc_name 'master'
271     logger.info "master process ready" # test_exec.rb relies on this message
272     if @ready_pipe
273       begin
274         @ready_pipe.syswrite($$.to_s)
275       rescue => e
276         logger.warn("grandparent died too soon?: #{e.message} (#{e.class})")
277       end
278       @ready_pipe = @ready_pipe.close rescue nil
279     end
280     begin
281       reap_all_workers
282       case SIG_QUEUE.shift
283       when nil
284         # avoid murdering workers after our master process (or the
285         # machine) comes out of suspend/hibernation
286         if (last_check + @timeout) >= (last_check = Time.now)
287           sleep_time = murder_lazy_workers
288         else
289           sleep_time = @timeout/2.0 + 1
290           @logger.debug("waiting #{sleep_time}s after suspend/hibernation")
291         end
292         maintain_worker_count if respawn
293         master_sleep(sleep_time)
294       when :QUIT # graceful shutdown
295         break
296       when :TERM, :INT # immediate shutdown
297         stop(false)
298         break
299       when :USR1 # rotate logs
300         logger.info "master reopening logs..."
301         Unicorn::Util.reopen_logs
302         logger.info "master done reopening logs"
303         soft_kill_each_worker(:USR1)
304       when :USR2 # exec binary, stay alive in case something went wrong
305         reexec
306       when :WINCH
307         if Unicorn::Configurator::RACKUP[:daemonized]
308           respawn = false
309           logger.info "gracefully stopping all workers"
310           soft_kill_each_worker(:QUIT)
311           self.worker_processes = 0
312         else
313           logger.info "SIGWINCH ignored because we're not daemonized"
314         end
315       when :TTIN
316         respawn = true
317         self.worker_processes += 1
318       when :TTOU
319         self.worker_processes -= 1 if self.worker_processes > 0
320       when :HUP
321         respawn = true
322         if config.config_file
323           load_config!
324         else # exec binary and exit if there's no config file
325           logger.info "config_file not present, reexecuting binary"
326           reexec
327         end
328       end
329     rescue => e
330       Unicorn.log_error(@logger, "master loop error", e)
331     end while true
332     stop # gracefully shutdown all workers on our way out
333     logger.info "master complete"
334     unlink_pid_safe(pid) if pid
335   end
337   # Terminates all workers, but does not exit master process
338   def stop(graceful = true)
339     self.listeners = []
340     limit = Time.now + timeout
341     until WORKERS.empty? || Time.now > limit
342       if graceful
343         soft_kill_each_worker(:QUIT)
344       else
345         kill_each_worker(:TERM)
346       end
347       sleep(0.1)
348       reap_all_workers
349     end
350     kill_each_worker(:KILL)
351   end
353   def rewindable_input
354     Unicorn::HttpRequest.input_class.method_defined?(:rewind)
355   end
357   def rewindable_input=(bool)
358     Unicorn::HttpRequest.input_class = bool ?
359                                 Unicorn::TeeInput : Unicorn::StreamInput
360   end
362   def client_body_buffer_size
363     Unicorn::TeeInput.client_body_buffer_size
364   end
366   def client_body_buffer_size=(bytes)
367     Unicorn::TeeInput.client_body_buffer_size = bytes
368   end
370   def check_client_connection
371     Unicorn::HttpRequest.check_client_connection
372   end
374   def check_client_connection=(bool)
375     Unicorn::HttpRequest.check_client_connection = bool
376   end
378   private
380   # wait for a signal hander to wake us up and then consume the pipe
381   def master_sleep(sec)
382     IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return
383     SELF_PIPE[0].kgio_tryread(11)
384   end
386   def awaken_master
387     return if $$ != @master_pid
388     SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select
389   end
391   # reaps all unreaped workers
392   def reap_all_workers
393     begin
394       wpid, status = Process.waitpid2(-1, Process::WNOHANG)
395       wpid or return
396       if reexec_pid == wpid
397         logger.error "reaped #{status.inspect} exec()-ed"
398         self.reexec_pid = 0
399         self.pid = pid.chomp('.oldbin') if pid
400         proc_name 'master'
401       else
402         worker = WORKERS.delete(wpid) and worker.close rescue nil
403         m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}"
404         status.success? ? logger.info(m) : logger.error(m)
405       end
406     rescue Errno::ECHILD
407       break
408     end while true
409   end
411   # reexecutes the START_CTX with a new binary
412   def reexec
413     if reexec_pid > 0
414       begin
415         Process.kill(0, reexec_pid)
416         logger.error "reexec-ed child already running PID:#{reexec_pid}"
417         return
418       rescue Errno::ESRCH
419         self.reexec_pid = 0
420       end
421     end
423     if pid
424       old_pid = "#{pid}.oldbin"
425       begin
426         self.pid = old_pid  # clear the path for a new pid file
427       rescue ArgumentError
428         logger.error "old PID:#{valid_pid?(old_pid)} running with " \
429                      "existing pid=#{old_pid}, refusing rexec"
430         return
431       rescue => e
432         logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
433         return
434       end
435     end
437     self.reexec_pid = fork do
438       listener_fds = {}
439       LISTENERS.each do |sock|
440         # IO#close_on_exec= will be available on any future version of
441         # Ruby that sets FD_CLOEXEC by default on new file descriptors
442         # ref: http://redmine.ruby-lang.org/issues/5041
443         sock.close_on_exec = false if sock.respond_to?(:close_on_exec=)
444         listener_fds[sock.fileno] = sock
445       end
446       ENV['UNICORN_FD'] = listener_fds.keys.join(',')
447       Dir.chdir(START_CTX[:cwd])
448       cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
450       # avoid leaking FDs we don't know about, but let before_exec
451       # unset FD_CLOEXEC, if anything else in the app eventually
452       # relies on FD inheritence.
453       (3..1024).each do |io|
454         next if listener_fds.include?(io)
455         io = IO.for_fd(io) rescue next
456         prevent_autoclose(io)
457         io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
458       end
460       # exec(command, hash) works in at least 1.9.1+, but will only be
461       # required in 1.9.4/2.0.0 at earliest.
462       cmd << listener_fds if RUBY_VERSION >= "1.9.1"
463       logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
464       before_exec.call(self)
465       exec(*cmd)
466     end
467     proc_name 'master (old)'
468   end
470   # forcibly terminate all workers that haven't checked in in timeout seconds.  The timeout is implemented using an unlinked File
471   def murder_lazy_workers
472     next_sleep = @timeout - 1
473     now = Time.now.to_i
474     WORKERS.dup.each_pair do |wpid, worker|
475       tick = worker.tick
476       0 == tick and next # skip workers that haven't processed any clients
477       diff = now - tick
478       tmp = @timeout - diff
479       if tmp >= 0
480         next_sleep > tmp and next_sleep = tmp
481         next
482       end
483       next_sleep = 0
484       logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
485                    "(#{diff}s > #{@timeout}s), killing"
486       kill_worker(:KILL, wpid) # take no prisoners for timeout violations
487     end
488     next_sleep <= 0 ? 1 : next_sleep
489   end
491   def after_fork_internal
492     SELF_PIPE.each { |io| io.close }.clear # this is master-only, now
493     @ready_pipe.close if @ready_pipe
494     Unicorn::Configurator::RACKUP.clear
495     @ready_pipe = @init_listeners = @before_exec = @before_fork = nil
497     srand # http://redmine.ruby-lang.org/issues/4338
499     # The OpenSSL PRNG is seeded with only the pid, and apps with frequently
500     # dying workers can recycle pids
501     OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random)
502   end
504   def spawn_missing_workers
505     worker_nr = -1
506     until (worker_nr += 1) == @worker_processes
507       WORKERS.value?(worker_nr) and next
508       worker = Worker.new(worker_nr)
509       before_fork.call(self, worker)
510       if pid = fork
511         WORKERS[pid] = worker
512         worker.atfork_parent
513       else
514         after_fork_internal
515         worker_loop(worker)
516         exit
517       end
518     end
519     rescue => e
520       @logger.error(e) rescue nil
521       exit!
522   end
524   def maintain_worker_count
525     (off = WORKERS.size - worker_processes) == 0 and return
526     off < 0 and return spawn_missing_workers
527     WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) }
528   end
530   # if we get any error, try to write something back to the client
531   # assuming we haven't closed the socket, but don't get hung up
532   # if the socket is already closed or broken.  We'll always ensure
533   # the socket is closed at the end of this function
534   def handle_error(client, e)
535     code = case e
536     when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN
537       # client disconnected on us and there's nothing we can do
538     when Unicorn::RequestURITooLongError
539       414
540     when Unicorn::RequestEntityTooLargeError
541       413
542     when Unicorn::HttpParserError # try to tell the client they're bad
543       400
544     else
545       Unicorn.log_error(@logger, "app error", e)
546       500
547     end
548     if code
549       client.kgio_trywrite(err_response(code, @request.response_start_sent))
550     end
551     client.close
552     rescue
553   end
555   def expect_100_response
556     if @request.response_start_sent
557       Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED
558     else
559       Unicorn::Const::EXPECT_100_RESPONSE
560     end
561   end
563   # once a client is accepted, it is processed in its entirety here
564   # in 3 easy steps: read request, call app, write app response
565   def process_client(client)
566     status, headers, body = @app.call(env = @request.read(client))
567     return if @request.hijacked?
569     if 100 == status.to_i
570       client.write(expect_100_response)
571       env.delete(Unicorn::Const::HTTP_EXPECT)
572       status, headers, body = @app.call(env)
573       return if @request.hijacked?
574     end
575     @request.headers? or headers = nil
576     http_response_write(client, status, headers, body,
577                         @request.response_start_sent)
578     unless client.closed? # rack.hijack may've close this for us
579       client.shutdown # in case of fork() in Rack app
580       client.close # flush and uncork socket immediately, no keepalive
581     end
582   rescue => e
583     handle_error(client, e)
584   end
586   EXIT_SIGS = [ :QUIT, :TERM, :INT ]
587   WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS
589   def nuke_listeners!(readers)
590     # only called from the worker, ordering is important here
591     tmp = readers.dup
592     readers.replace([false]) # ensure worker does not continue ASAP
593     tmp.each { |io| io.close rescue nil } # break out of IO.select
594   end
596   # gets rid of stuff the worker has no business keeping track of
597   # to free some resources and drops all sig handlers.
598   # traps for USR1, USR2, and HUP may be set in the after_fork Proc
599   # by the user.
600   def init_worker_process(worker)
601     worker.atfork_child
602     # we'll re-trap :QUIT later for graceful shutdown iff we accept clients
603     EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } }
604     exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0]
605     WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) }
606     trap(:CHLD, 'DEFAULT')
607     SIG_QUEUE.clear
608     proc_name "worker[#{worker.nr}]"
609     START_CTX.clear
610     WORKERS.clear
612     after_fork.call(self, worker) # can drop perms and create listeners
613     LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
615     worker.user(*user) if user.kind_of?(Array) && ! worker.switched
616     self.timeout /= 2.0 # halve it for select()
617     @config = nil
618     build_app! unless preload_app
619     @after_fork = @listener_opts = @orig_app = nil
620     readers = LISTENERS.dup
621     readers << worker
622     trap(:QUIT) { nuke_listeners!(readers) }
623     readers
624   end
626   def reopen_worker_logs(worker_nr)
627     logger.info "worker=#{worker_nr} reopening logs..."
628     Unicorn::Util.reopen_logs
629     logger.info "worker=#{worker_nr} done reopening logs"
630     rescue => e
631       logger.error(e) rescue nil
632       exit!(77) # EX_NOPERM in sysexits.h
633   end
635   # runs inside each forked worker, this sits around and waits
636   # for connections and doesn't die until the parent dies (or is
637   # given a INT, QUIT, or TERM signal)
638   def worker_loop(worker)
639     ppid = master_pid
640     readers = init_worker_process(worker)
641     nr = 0 # this becomes negative if we need to reopen logs
643     # this only works immediately if the master sent us the signal
644     # (which is the normal case)
645     trap(:USR1) { nr = -65536 }
647     ready = readers.dup
648     @logger.info "worker=#{worker.nr} ready"
650     begin
651       nr < 0 and reopen_worker_logs(worker.nr)
652       nr = 0
653       worker.tick = Time.now.to_i
654       tmp = ready.dup
655       while sock = tmp.shift
656         # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all,
657         # but that will return false
658         if client = sock.kgio_tryaccept
659           process_client(client)
660           nr += 1
661           worker.tick = Time.now.to_i
662         end
663         break if nr < 0
664       end
666       # make the following bet: if we accepted clients this round,
667       # we're probably reasonably busy, so avoid calling select()
668       # and do a speculative non-blocking accept() on ready listeners
669       # before we sleep again in select().
670       unless nr == 0
671         tmp = ready.dup
672         redo
673       end
675       ppid == Process.ppid or return
677       # timeout used so we can detect parent death:
678       worker.tick = Time.now.to_i
679       ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0]
680     rescue => e
681       redo if nr < 0 && readers[0]
682       Unicorn.log_error(@logger, "listen loop error", e) if readers[0]
683     end while readers[0]
684   end
686   # delivers a signal to a worker and fails gracefully if the worker
687   # is no longer running.
688   def kill_worker(signal, wpid)
689     Process.kill(signal, wpid)
690     rescue Errno::ESRCH
691       worker = WORKERS.delete(wpid) and worker.close rescue nil
692   end
694   # delivers a signal to each worker
695   def kill_each_worker(signal)
696     WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
697   end
699   def soft_kill_each_worker(signal)
700     WORKERS.each_value { |worker| worker.soft_kill(signal) }
701   end
703   # unlinks a PID file at given +path+ if it contains the current PID
704   # still potentially racy without locking the directory (which is
705   # non-portable and may interact badly with other programs), but the
706   # window for hitting the race condition is small
707   def unlink_pid_safe(path)
708     (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
709   end
711   # returns a PID if a given path contains a non-stale PID file,
712   # nil otherwise.
713   def valid_pid?(path)
714     wpid = File.read(path).to_i
715     wpid <= 0 and return
716     Process.kill(0, wpid)
717     wpid
718     rescue Errno::EPERM
719       logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}"
720       nil
721     rescue Errno::ESRCH, Errno::ENOENT
722       # don't unlink stale pid files, racy without non-portable locking...
723   end
725   def load_config!
726     loaded_app = app
727     logger.info "reloading config_file=#{config.config_file}"
728     config[:listeners].replace(@init_listeners)
729     config.reload
730     config.commit!(self)
731     soft_kill_each_worker(:QUIT)
732     Unicorn::Util.reopen_logs
733     self.app = orig_app
734     build_app! if preload_app
735     logger.info "done reloading config_file=#{config.config_file}"
736   rescue StandardError, LoadError, SyntaxError => e
737     Unicorn.log_error(@logger,
738         "error reloading config_file=#{config.config_file}", e)
739     self.app = loaded_app
740   end
742   # returns an array of string names for the given listener array
743   def listener_names(listeners = LISTENERS)
744     listeners.map { |io| sock_name(io) }
745   end
747   def build_app!
748     if app.respond_to?(:arity) && app.arity == 0
749       if defined?(Gem) && Gem.respond_to?(:refresh)
750         logger.info "Refreshing Gem list"
751         Gem.refresh
752       end
753       self.app = app.call
754     end
755   end
757   def proc_name(tag)
758     $0 = ([ File.basename(START_CTX[0]), tag
759           ]).concat(START_CTX[:argv]).join(' ')
760   end
762   def redirect_io(io, path)
763     File.open(path, 'ab') { |fp| io.reopen(fp) } if path
764     io.sync = true
765   end
767   def inherit_listeners!
768     # inherit sockets from parents, they need to be plain Socket objects
769     # before they become Kgio::UNIXServer or Kgio::TCPServer
770     inherited = ENV['UNICORN_FD'].to_s.split(',').map do |fd|
771       io = Socket.for_fd(fd.to_i)
772       set_server_sockopt(io, listener_opts[sock_name(io)])
773       prevent_autoclose(io)
774       logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
775       server_cast(io)
776     end
778     config_listeners = config[:listeners].dup
779     LISTENERS.replace(inherited)
781     # we start out with generic Socket objects that get cast to either
782     # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket
783     # objects share the same OS-level file descriptor as the higher-level
784     # *Server objects; we need to prevent Socket objects from being
785     # garbage-collected
786     config_listeners -= listener_names
787     if config_listeners.empty? && LISTENERS.empty?
788       config_listeners << Unicorn::Const::DEFAULT_LISTEN
789       @init_listeners << Unicorn::Const::DEFAULT_LISTEN
790       START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
791     end
792     NEW_LISTENERS.replace(config_listeners)
793   end
795   # call only after calling inherit_listeners!
796   # This binds any listeners we did NOT inherit from the parent
797   def bind_new_listeners!
798     NEW_LISTENERS.each { |addr| listen(addr) }
799     raise ArgumentError, "no listeners" if LISTENERS.empty?
800     NEW_LISTENERS.clear
801   end