test_signals: ensure we can parse pids in response
[unicorn.git] / lib / unicorn.rb
blob0e4626123d60819d81875003a5ccc13ca707f421
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   Z = '' # the stock empty string we use everywhere...
19   Z.force_encoding(Encoding::BINARY) if Z.respond_to?(:force_encoding)
20   Z.freeze
22   class << self
23     def run(app, options = {})
24       HttpServer.new(app, options).start.join
25     end
26   end
28   # This is the process manager of Unicorn. This manages worker
29   # processes which in turn handle the I/O and application process.
30   # Listener sockets are started in the master process and shared with
31   # forked worker children.
33   class HttpServer < Struct.new(:listener_opts, :timeout, :worker_processes,
34                                 :before_fork, :after_fork, :before_exec,
35                                 :logger, :pid, :app, :preload_app,
36                                 :reexec_pid, :orig_app, :init_listeners,
37                                 :master_pid, :config)
38     include ::Unicorn::SocketHelper
40     # prevents IO objects in here from being GC-ed
41     IO_PURGATORY = []
43     # all bound listener sockets
44     LISTENERS = []
46     # This hash maps PIDs to Workers
47     WORKERS = {}
49     # See: http://cr.yp.to/docs/selfpipe.html
50     SELF_PIPE = []
52     # signal queue used for self-piping
53     SIG_QUEUE = []
55     # constant lookups are faster and we're single-threaded/non-reentrant
56     REQUEST = HttpRequest.new
58     # We populate this at startup so we can figure out how to reexecute
59     # and upgrade the currently running instance of Unicorn
60     START_CTX = {
61       :argv => ARGV.map { |arg| arg.dup },
62       # don't rely on Dir.pwd here since it's not symlink-aware, and
63       # symlink dirs are the default with Capistrano...
64       :cwd => `/bin/sh -c pwd`.chomp("\n"),
65       0 => $0.dup,
66     }
68     class Worker < Struct.new(:nr, :tmp)
69       # worker objects may be compared to just plain numbers
70       def ==(other_nr)
71         self.nr == other_nr
72       end
73     end
75     # Creates a working server on host:port (strange things happen if
76     # port isn't a Number).  Use HttpServer::run to start the server and
77     # HttpServer.run.join to join the thread that's processing
78     # incoming requests on the socket.
79     def initialize(app, options = {})
80       self.app = app
81       self.reexec_pid = 0
82       self.init_listeners = options[:listeners] ? options[:listeners].dup : []
83       self.config = Configurator.new(options.merge(:use_defaults => true))
84       self.listener_opts = {}
85       config.commit!(self, :skip => [:listeners, :pid])
86       self.orig_app = app
87     end
89     # Runs the thing.  Returns self so you can run join on it
90     def start
91       BasicSocket.do_not_reverse_lookup = true
93       # inherit sockets from parents, they need to be plain Socket objects
94       # before they become UNIXServer or TCPServer
95       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
96         io = Socket.for_fd(fd.to_i)
97         set_server_sockopt(io, listener_opts[sock_name(io)])
98         IO_PURGATORY << io
99         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
100         server_cast(io)
101       end
103       config_listeners = config[:listeners].dup
104       LISTENERS.replace(inherited)
106       # we start out with generic Socket objects that get cast to either
107       # TCPServer or UNIXServer objects; but since the Socket objects
108       # share the same OS-level file descriptor as the higher-level *Server
109       # objects; we need to prevent Socket objects from being garbage-collected
110       config_listeners -= listener_names
111       if config_listeners.empty? && LISTENERS.empty?
112         config_listeners << Unicorn::Const::DEFAULT_LISTEN
113         init_listeners << Unicorn::Const::DEFAULT_LISTEN
114         START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}"
115       end
116       config_listeners.each { |addr| listen(addr) }
117       raise ArgumentError, "no listeners" if LISTENERS.empty?
118       self.pid = config[:pid]
119       self.master_pid = $$
120       build_app! if preload_app
121       maintain_worker_count
122       self
123     end
125     # replaces current listener set with +listeners+.  This will
126     # close the socket if it will not exist in the new listener set
127     def listeners=(listeners)
128       cur_names, dead_names = [], []
129       listener_names.each do |name|
130         if "/" == name[0..0]
131           # mark unlinked sockets as dead so we can rebind them
132           (File.socket?(name) ? cur_names : dead_names) << name
133         else
134           cur_names << name
135         end
136       end
137       set_names = listener_names(listeners)
138       dead_names.concat(cur_names - set_names).uniq!
140       LISTENERS.delete_if do |io|
141         if dead_names.include?(sock_name(io))
142           IO_PURGATORY.delete_if do |pio|
143             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
144           end
145           (io.close rescue nil).nil? # true
146         else
147           set_server_sockopt(io, listener_opts[sock_name(io)])
148           false
149         end
150       end
152       (set_names - cur_names).each { |addr| listen(addr) }
153     end
155     def stdout_path=(path); redirect_io($stdout, path); end
156     def stderr_path=(path); redirect_io($stderr, path); end
158     alias_method :set_pid, :pid=
159     undef_method :pid=
161     # sets the path for the PID file of the master process
162     def pid=(path)
163       if path
164         if x = valid_pid?(path)
165           return path if pid && path == pid && x == $$
166           raise ArgumentError, "Already running on PID:#{x} " \
167                                "(or pid=#{path} is stale)"
168         end
169       end
170       unlink_pid_safe(pid) if pid
171       File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
172       self.set_pid(path)
173     end
175     # add a given address to the +listeners+ set, idempotently
176     # Allows workers to add a private, per-process listener via the
177     # after_fork hook.  Very useful for debugging and testing.
178     def listen(address, opt = {}.merge(listener_opts[address] || {}))
179       return if String === address && listener_names.include?(address)
181       delay, tries = 0.5, 5
182       begin
183         io = bind_listen(address, opt)
184         unless TCPServer === io || UNIXServer === io
185           IO_PURGATORY << io
186           io = server_cast(io)
187         end
188         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
189         LISTENERS << io
190         return io
191       rescue Errno::EADDRINUSE => err
192         logger.error "adding listener failed addr=#{address} (in use)"
193         raise err if tries == 0
194         tries -= 1
195         logger.error "retrying in #{delay} seconds (#{tries} tries left)"
196         sleep(delay)
197         retry
198       end
199     end
201     # monitors children and receives signals forever
202     # (or until a termination signal is sent).  This handles signals
203     # one-at-a-time time and we'll happily drop signals in case somebody
204     # is signalling us too often.
205     def join
206       # this pipe is used to wake us up from select(2) in #join when signals
207       # are trapped.  See trap_deferred
208       init_self_pipe!
209       respawn = true
211       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
212       trap(:CHLD) { |sig_nr| awaken_master }
213       proc_name 'master'
214       logger.info "master process ready" # test_exec.rb relies on this message
215       begin
216         loop do
217           reap_all_workers
218           case SIG_QUEUE.shift
219           when nil
220             murder_lazy_workers
221             maintain_worker_count if respawn
222             master_sleep
223           when :QUIT # graceful shutdown
224             break
225           when :TERM, :INT # immediate shutdown
226             stop(false)
227             break
228           when :USR1 # rotate logs
229             logger.info "master reopening logs..."
230             Unicorn::Util.reopen_logs
231             logger.info "master done reopening logs"
232             kill_each_worker(:USR1)
233           when :USR2 # exec binary, stay alive in case something went wrong
234             reexec
235           when :WINCH
236             if Process.ppid == 1 || Process.getpgrp != $$
237               respawn = false
238               logger.info "gracefully stopping all workers"
239               kill_each_worker(:QUIT)
240             else
241               logger.info "SIGWINCH ignored because we're not daemonized"
242             end
243           when :TTIN
244             self.worker_processes += 1
245           when :TTOU
246             self.worker_processes -= 1 if self.worker_processes > 0
247           when :HUP
248             respawn = true
249             if config.config_file
250               load_config!
251               redo # immediate reaping since we may have QUIT workers
252             else # exec binary and exit if there's no config file
253               logger.info "config_file not present, reexecuting binary"
254               reexec
255               break
256             end
257           end
258         end
259       rescue Errno::EINTR
260         retry
261       rescue Object => e
262         logger.error "Unhandled master loop exception #{e.inspect}."
263         logger.error e.backtrace.join("\n")
264         retry
265       end
266       stop # gracefully shutdown all workers on our way out
267       logger.info "master complete"
268       unlink_pid_safe(pid) if pid
269     end
271     # Terminates all workers, but does not exit master process
272     def stop(graceful = true)
273       self.listeners = []
274       kill_each_worker(graceful ? :QUIT : :TERM)
275       timeleft = timeout
276       step = 0.2
277       reap_all_workers
278       until WORKERS.empty?
279         sleep(step)
280         reap_all_workers
281         (timeleft -= step) > 0 and next
282         kill_each_worker(:KILL)
283       end
284     end
286     private
288     # list of signals we care about and trap in master.
289     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
290                    :TTIN, :TTOU ]
292     # defer a signal for later processing in #join (master process)
293     def trap_deferred(signal)
294       trap(signal) do |sig_nr|
295         if SIG_QUEUE.size < 5
296           SIG_QUEUE << signal
297           awaken_master
298         else
299           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
300         end
301       end
302     end
304     # wait for a signal hander to wake us up and then consume the pipe
305     # Wake up every second anyways to run murder_lazy_workers
306     def master_sleep
307       begin
308         ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
309         ready.first && ready.first.first or return
310         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
311       rescue Errno::EAGAIN, Errno::EINTR
312       end
313     end
315     def awaken_master
316       begin
317         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
318       rescue Errno::EAGAIN, Errno::EINTR
319         # pipe is full, master should wake up anyways
320         retry
321       end
322     end
324     # reaps all unreaped workers
325     def reap_all_workers
326       begin
327         loop do
328           wpid, status = Process.waitpid2(-1, Process::WNOHANG)
329           wpid or break
330           if reexec_pid == wpid
331             logger.error "reaped #{status.inspect} exec()-ed"
332             self.reexec_pid = 0
333             self.pid = pid.chomp('.oldbin') if pid
334             proc_name 'master'
335           else
336             worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
337             logger.info "reaped #{status.inspect} " \
338                         "worker=#{worker.nr rescue 'unknown'}"
339           end
340         end
341       rescue Errno::ECHILD
342       end
343     end
345     # reexecutes the START_CTX with a new binary
346     def reexec
347       if reexec_pid > 0
348         begin
349           Process.kill(0, reexec_pid)
350           logger.error "reexec-ed child already running PID:#{reexec_pid}"
351           return
352         rescue Errno::ESRCH
353           reexec_pid = 0
354         end
355       end
357       if pid
358         old_pid = "#{pid}.oldbin"
359         prev_pid = pid.dup
360         begin
361           self.pid = old_pid  # clear the path for a new pid file
362         rescue ArgumentError
363           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
364                        "existing pid=#{old_pid}, refusing rexec"
365           return
366         rescue Object => e
367           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
368           return
369         end
370       end
372       self.reexec_pid = fork do
373         listener_fds = LISTENERS.map { |sock| sock.fileno }
374         ENV['UNICORN_FD'] = listener_fds.join(',')
375         Dir.chdir(START_CTX[:cwd])
376         cmd = [ START_CTX[0] ].concat(START_CTX[:argv])
378         # avoid leaking FDs we don't know about, but let before_exec
379         # unset FD_CLOEXEC, if anything else in the app eventually
380         # relies on FD inheritence.
381         (3..1024).each do |io|
382           next if listener_fds.include?(io)
383           io = IO.for_fd(io) rescue nil
384           io or next
385           IO_PURGATORY << io
386           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
387         end
388         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
389         before_exec.call(self)
390         exec(*cmd)
391       end
392       proc_name 'master (old)'
393     end
395     # forcibly terminate all workers that haven't checked in in timeout
396     # seconds.  The timeout is implemented using an unlinked File
397     # shared between the parent process and each worker.  The worker
398     # runs File#chmod to modify the ctime of the File.  If the ctime
399     # is stale for >timeout seconds, then we'll kill the corresponding
400     # worker.
401     def murder_lazy_workers
402       diff = stat = nil
403       WORKERS.dup.each_pair do |wpid, worker|
404         stat = begin
405           worker.tmp.stat
406         rescue => e
407           logger.warn "worker=#{worker.nr} PID:#{wpid} stat error: #{e.inspect}"
408           kill_worker(:QUIT, wpid)
409           next
410         end
411         stat.mode == 0100000 and next
412         (diff = (Time.now - stat.ctime)) <= timeout and next
413         logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \
414                      "(#{diff}s > #{timeout}s), killing"
415         kill_worker(:KILL, wpid) # take no prisoners for timeout violations
416       end
417     end
419     def spawn_missing_workers
420       (0...worker_processes).each do |worker_nr|
421         WORKERS.values.include?(worker_nr) and next
422         begin
423           Dir.chdir(START_CTX[:cwd])
424         rescue Errno::ENOENT => err
425           logger.fatal "#{err.inspect} (#{START_CTX[:cwd]})"
426           SIG_QUEUE << :QUIT # forcibly emulate SIGQUIT
427           return
428         end
429         worker = Worker.new(worker_nr, Unicorn::Util.tmpio)
430         before_fork.call(self, worker)
431         WORKERS[fork { worker_loop(worker) }] = worker
432       end
433     end
435     def maintain_worker_count
436       (off = WORKERS.size - worker_processes) == 0 and return
437       off < 0 and return spawn_missing_workers
438       WORKERS.dup.each_pair { |wpid,w|
439         w.nr >= worker_processes and kill_worker(:QUIT, wpid) rescue nil
440       }
441     end
443     # once a client is accepted, it is processed in its entirety here
444     # in 3 easy steps: read request, call app, write app response
445     def process_client(client)
446       client.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
447       response = app.call(env = REQUEST.read(client))
449       if 100 == response.first.to_i
450         client.write(Const::EXPECT_100_RESPONSE)
451         env.delete(Const::HTTP_EXPECT)
452         response = app.call(env)
453       end
454       HttpResponse.write(client, response, HttpRequest::PARSER.headers?)
455     # if we get any error, try to write something back to the client
456     # assuming we haven't closed the socket, but don't get hung up
457     # if the socket is already closed or broken.  We'll always ensure
458     # the socket is closed at the end of this function
459     rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF
460       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
461       client.close rescue nil
462     rescue HttpParserError # try to tell the client they're bad
463       client.write_nonblock(Const::ERROR_400_RESPONSE) rescue nil
464       client.close rescue nil
465     rescue Object => e
466       client.write_nonblock(Const::ERROR_500_RESPONSE) rescue nil
467       client.close rescue nil
468       logger.error "Read error: #{e.inspect}"
469       logger.error e.backtrace.join("\n")
470     end
472     # gets rid of stuff the worker has no business keeping track of
473     # to free some resources and drops all sig handlers.
474     # traps for USR1, USR2, and HUP may be set in the after_fork Proc
475     # by the user.
476     def init_worker_process(worker)
477       QUEUE_SIGS.each { |sig| trap(sig, nil) }
478       trap(:CHLD, 'DEFAULT')
479       SIG_QUEUE.clear
480       proc_name "worker[#{worker.nr}]"
481       START_CTX.clear
482       init_self_pipe!
483       WORKERS.values.each { |other| other.tmp.close rescue nil }
484       WORKERS.clear
485       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
486       worker.tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
487       after_fork.call(self, worker) # can drop perms
488       self.timeout /= 2.0 # halve it for select()
489       build_app! unless preload_app
490     end
492     def reopen_worker_logs(worker_nr)
493       logger.info "worker=#{worker_nr} reopening logs..."
494       Unicorn::Util.reopen_logs
495       logger.info "worker=#{worker_nr} done reopening logs"
496       init_self_pipe!
497     end
499     # runs inside each forked worker, this sits around and waits
500     # for connections and doesn't die until the parent dies (or is
501     # given a INT, QUIT, or TERM signal)
502     def worker_loop(worker)
503       ppid = master_pid
504       init_worker_process(worker)
505       nr = 0 # this becomes negative if we need to reopen logs
506       alive = worker.tmp # tmp is our lifeline to the master process
507       ready = LISTENERS
508       t = ti = 0
510       # closing anything we IO.select on will raise EBADF
511       trap(:USR1) { nr = -65536; SELF_PIPE.first.close rescue nil }
512       trap(:QUIT) { alive = nil; LISTENERS.each { |s| s.close rescue nil } }
513       [:TERM, :INT].each { |sig| trap(sig) { exit!(0) } } # instant shutdown
514       logger.info "worker=#{worker.nr} ready"
516       begin
517         nr < 0 and reopen_worker_logs(worker.nr)
518         nr = 0
520         # we're a goner in timeout seconds anyways if alive.chmod
521         # breaks, so don't trap the exception.  Using fchmod() since
522         # futimes() is not available in base Ruby and I very strongly
523         # prefer temporary files to be unlinked for security,
524         # performance and reliability reasons, so utime is out.  No-op
525         # changes with chmod doesn't update ctime on all filesystems; so
526         # we change our counter each and every time (after process_client
527         # and before IO.select).
528         t == (ti = Time.now.to_i) or alive.chmod(t = ti)
530         ready.each do |sock|
531           begin
532             process_client(sock.accept_nonblock)
533             nr += 1
534             t == (ti = Time.now.to_i) or alive.chmod(t = ti)
535           rescue Errno::EAGAIN, Errno::ECONNABORTED
536           end
537           break if nr < 0
538         end
540         # make the following bet: if we accepted clients this round,
541         # we're probably reasonably busy, so avoid calling select()
542         # and do a speculative accept_nonblock on ready listeners
543         # before we sleep again in select().
544         redo unless nr == 0 # (nr < 0) => reopen logs
546         ppid == Process.ppid or return
547         alive.chmod(t = 0)
548         begin
549           # timeout used so we can detect parent death:
550           ret = IO.select(LISTENERS, nil, SELF_PIPE, timeout) or redo
551           ready = ret.first
552         rescue Errno::EINTR
553           ready = LISTENERS
554         rescue Errno::EBADF
555           nr < 0 or return
556         end
557       rescue Object => e
558         if alive
559           logger.error "Unhandled listen loop exception #{e.inspect}."
560           logger.error e.backtrace.join("\n")
561         end
562       end while alive
563     end
565     # delivers a signal to a worker and fails gracefully if the worker
566     # is no longer running.
567     def kill_worker(signal, wpid)
568       begin
569         Process.kill(signal, wpid)
570       rescue Errno::ESRCH
571         worker = WORKERS.delete(wpid) and worker.tmp.close rescue nil
572       end
573     end
575     # delivers a signal to each worker
576     def kill_each_worker(signal)
577       WORKERS.keys.each { |wpid| kill_worker(signal, wpid) }
578     end
580     # unlinks a PID file at given +path+ if it contains the current PID
581     # useful as an at_exit handler.
582     def unlink_pid_safe(path)
583       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
584     end
586     # returns a PID if a given path contains a non-stale PID file,
587     # nil otherwise.
588     def valid_pid?(path)
589       if File.exist?(path) && (wpid = File.read(path).to_i) > 1
590         begin
591           Process.kill(0, wpid)
592           return wpid
593         rescue Errno::ESRCH
594         end
595       end
596       nil
597     end
599     def load_config!
600       begin
601         logger.info "reloading config_file=#{config.config_file}"
602         config[:listeners].replace(init_listeners)
603         config.reload
604         config.commit!(self)
605         kill_each_worker(:QUIT)
606         Unicorn::Util.reopen_logs
607         self.app = orig_app
608         build_app! if preload_app
609         logger.info "done reloading config_file=#{config.config_file}"
610       rescue Object => e
611         logger.error "error reloading config_file=#{config.config_file}: " \
612                      "#{e.class} #{e.message}"
613       end
614     end
616     # returns an array of string names for the given listener array
617     def listener_names(listeners = LISTENERS)
618       listeners.map { |io| sock_name(io) }
619     end
621     def build_app!
622       if app.respond_to?(:arity) && app.arity == 0
623         if defined?(Gem) && Gem.respond_to?(:refresh)
624           logger.info "Refreshing Gem list"
625           Gem.refresh
626         end
627         self.app = app.call
628       end
629     end
631     def proc_name(tag)
632       $0 = ([ File.basename(START_CTX[0]), tag
633             ]).concat(START_CTX[:argv]).join(' ')
634     end
636     def redirect_io(io, path)
637       File.open(path, 'ab') { |fp| io.reopen(fp) } if path
638       io.sync = true
639     end
641     def init_self_pipe!
642       SELF_PIPE.each { |io| io.close rescue nil }
643       SELF_PIPE.replace(IO.pipe)
644       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
645     end
647   end