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