Avoid temporary array creation
[unicorn.git] / lib / unicorn.rb
blob3e1d4188a40e85c47dc8cc15af38b1a54ebb2e58
1 require 'fcntl'
2 require 'tempfile'
3 require 'unicorn/socket_helper'
4 autoload :Rack, 'rack'
6 # Unicorn module containing all of the classes (include C extensions) for running
7 # a Unicorn web server.  It contains a minimalist HTTP server with just enough
8 # functionality to service web application requests fast as possible.
9 module Unicorn
10   autoload :Const, 'unicorn/const'
11   autoload :HttpRequest, 'unicorn/http_request'
12   autoload :HttpResponse, 'unicorn/http_response'
13   autoload :Configurator, 'unicorn/configurator'
14   autoload :TeeInput, 'unicorn/tee_input'
15   autoload :ChunkedReader, 'unicorn/chunked_reader'
16   autoload :TrailerParser, 'unicorn/trailer_parser'
17   autoload :Util, 'unicorn/util'
19   Z = '' # the stock empty string we use everywhere...
20   Z.force_encoding(Encoding::BINARY) if Z.respond_to?(:force_encoding)
21   Z.freeze
23   class << self
24     def run(app, options = {})
25       HttpServer.new(app, options).start.join
26     end
27   end
29   # This is the process manager of Unicorn. This manages worker
30   # processes which in turn handle the I/O and application process.
31   # Listener sockets are started in the master process and shared with
32   # forked worker children.
33   class HttpServer
34     attr_reader :logger
35     include ::Unicorn::SocketHelper
37     # prevents IO objects in here from being GC-ed
38     IO_PURGATORY = []
40     # all bound listener sockets
41     LISTENERS = []
43     # This hash maps PIDs to Workers
44     WORKERS = {}
46     # See: http://cr.yp.to/docs/selfpipe.html
47     SELF_PIPE = []
49     # signal queue used for self-piping
50     SIG_QUEUE = []
52     # constant lookups are faster and we're single-threaded/non-reentrant
53     REQUEST = HttpRequest.new
55     # We populate this at startup so we can figure out how to reexecute
56     # and upgrade the currently running instance of Unicorn
57     START_CTX = {
58       :argv => ARGV.map { |arg| arg.dup },
59       # don't rely on Dir.pwd here since it's not symlink-aware, and
60       # symlink dirs are the default with Capistrano...
61       :cwd => `/bin/sh -c pwd`.chomp("\n"),
62       :zero => $0.dup,
63     }
65     Worker = Struct.new(:nr, :tempfile) unless defined?(Worker)
66     class Worker
67       # worker objects may be compared to just plain numbers
68       def ==(other_nr)
69         self.nr == other_nr
70       end
71     end
73     # Creates a working server on host:port (strange things happen if
74     # port isn't a Number).  Use HttpServer::run to start the server and
75     # HttpServer.run.join to join the thread that's processing
76     # incoming requests on the socket.
77     def initialize(app, options = {})
78       @app = app
79       @pid = nil
80       @reexec_pid = 0
81       @init_listeners = options[:listeners] ? options[:listeners].dup : []
82       @config = Configurator.new(options.merge(:use_defaults => true))
83       @listener_opts = {}
84       @config.commit!(self, :skip => [:listeners, :pid])
85       @orig_app = app
86     end
88     # Runs the thing.  Returns self so you can run join on it
89     def start
90       BasicSocket.do_not_reverse_lookup = true
92       # inherit sockets from parents, they need to be plain Socket objects
93       # before they become UNIXServer or TCPServer
94       inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd|
95         io = Socket.for_fd(fd.to_i)
96         set_server_sockopt(io, @listener_opts[sock_name(io)])
97         IO_PURGATORY << io
98         logger.info "inherited addr=#{sock_name(io)} fd=#{fd}"
99         server_cast(io)
100       end
102       config_listeners = @config[:listeners].dup
103       LISTENERS.replace(inherited)
105       # we start out with generic Socket objects that get cast to either
106       # TCPServer or UNIXServer objects; but since the Socket objects
107       # share the same OS-level file descriptor as the higher-level *Server
108       # objects; we need to prevent Socket objects from being garbage-collected
109       config_listeners -= listener_names
110       if config_listeners.empty? && LISTENERS.empty?
111         config_listeners << Unicorn::Const::DEFAULT_LISTEN
112       end
113       config_listeners.each { |addr| listen(addr) }
114       raise ArgumentError, "no listeners" if LISTENERS.empty?
115       self.pid = @config[:pid]
116       build_app! if @preload_app
117       maintain_worker_count
118       self
119     end
121     # replaces current listener set with +listeners+.  This will
122     # close the socket if it will not exist in the new listener set
123     def listeners=(listeners)
124       cur_names, dead_names = [], []
125       listener_names.each do |name|
126         if "/" == name[0..0]
127           # mark unlinked sockets as dead so we can rebind them
128           (File.socket?(name) ? cur_names : dead_names) << name
129         else
130           cur_names << name
131         end
132       end
133       set_names = listener_names(listeners)
134       dead_names.concat(cur_names - set_names).uniq!
136       LISTENERS.delete_if do |io|
137         if dead_names.include?(sock_name(io))
138           IO_PURGATORY.delete_if do |pio|
139             pio.fileno == io.fileno && (pio.close rescue nil).nil? # true
140           end
141           (io.close rescue nil).nil? # true
142         else
143           set_server_sockopt(io, @listener_opts[sock_name(io)])
144           false
145         end
146       end
148       (set_names - cur_names).each { |addr| listen(addr) }
149     end
151     def stdout_path=(path); redirect_io($stdout, path); end
152     def stderr_path=(path); redirect_io($stderr, path); end
154     def logger=(obj)
155       REQUEST.logger = @logger = obj
156     end
158     # sets the path for the PID file of the master process
159     def pid=(path)
160       if path
161         if x = valid_pid?(path)
162           return path if @pid && path == @pid && x == $$
163           raise ArgumentError, "Already running on PID:#{x} " \
164                                "(or pid=#{path} is stale)"
165         end
166       end
167       unlink_pid_safe(@pid) if @pid
168       File.open(path, 'wb') { |fp| fp.syswrite("#$$\n") } if path
169       @pid = path
170     end
172     # add a given address to the +listeners+ set, idempotently
173     # Allows workers to add a private, per-process listener via the
174     # @after_fork hook.  Very useful for debugging and testing.
175     def listen(address, opt = {}.merge(@listener_opts[address] || {}))
176       return if String === address && listener_names.include?(address)
178       delay, tries = 0.5, 5
179       begin
180         io = bind_listen(address, opt)
181         unless TCPServer === io || UNIXServer === io
182           IO_PURGATORY << io
183           io = server_cast(io)
184         end
185         logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}"
186         LISTENERS << io
187         return io
188       rescue Errno::EADDRINUSE => err
189         logger.error "adding listener failed addr=#{address} (in use)"
190         raise err if tries == 0
191         tries -= 1
192         logger.error "retrying in #{delay} seconds (#{tries} tries left)"
193         sleep(delay)
194         retry
195       end
196     end
198     # monitors children and receives signals forever
199     # (or until a termination signal is sent).  This handles signals
200     # one-at-a-time time and we'll happily drop signals in case somebody
201     # is signalling us too often.
202     def join
203       # this pipe is used to wake us up from select(2) in #join when signals
204       # are trapped.  See trap_deferred
205       init_self_pipe!
206       respawn = true
208       QUEUE_SIGS.each { |sig| trap_deferred(sig) }
209       trap(:CHLD) { |sig_nr| awaken_master }
210       proc_name 'master'
211       logger.info "master process ready" # test_exec.rb relies on this message
212       begin
213         loop do
214           reap_all_workers
215           case SIG_QUEUE.shift
216           when nil
217             murder_lazy_workers
218             maintain_worker_count if respawn
219             master_sleep
220           when :QUIT # graceful shutdown
221             break
222           when :TERM, :INT # immediate shutdown
223             stop(false)
224             break
225           when :USR1 # rotate logs
226             logger.info "master reopening logs..."
227             Unicorn::Util.reopen_logs
228             logger.info "master done reopening logs"
229             kill_each_worker(:USR1)
230           when :USR2 # exec binary, stay alive in case something went wrong
231             reexec
232           when :WINCH
233             if Process.ppid == 1 || Process.getpgrp != $$
234               respawn = false
235               logger.info "gracefully stopping all workers"
236               kill_each_worker(:QUIT)
237             else
238               logger.info "SIGWINCH ignored because we're not daemonized"
239             end
240           when :TTIN
241             @worker_processes += 1
242           when :TTOU
243             @worker_processes -= 1 if @worker_processes > 0
244           when :HUP
245             respawn = true
246             if @config.config_file
247               load_config!
248               redo # immediate reaping since we may have QUIT workers
249             else # exec binary and exit if there's no config file
250               logger.info "config_file not present, reexecuting binary"
251               reexec
252               break
253             end
254           end
255         end
256       rescue Errno::EINTR
257         retry
258       rescue Object => e
259         logger.error "Unhandled master loop exception #{e.inspect}."
260         logger.error e.backtrace.join("\n")
261         retry
262       end
263       stop # gracefully shutdown all workers on our way out
264       logger.info "master complete"
265       unlink_pid_safe(@pid) if @pid
266     end
268     # Terminates all workers, but does not exit master process
269     def stop(graceful = true)
270       self.listeners = []
271       kill_each_worker(graceful ? :QUIT : :TERM)
272       timeleft = @timeout
273       step = 0.2
274       reap_all_workers
275       until WORKERS.empty?
276         sleep(step)
277         reap_all_workers
278         (timeleft -= step) > 0 and next
279         kill_each_worker(:KILL)
280       end
281     end
283     private
285     # list of signals we care about and trap in master.
286     QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP,
287                    :TTIN, :TTOU ].freeze
289     # defer a signal for later processing in #join (master process)
290     def trap_deferred(signal)
291       trap(signal) do |sig_nr|
292         if SIG_QUEUE.size < 5
293           SIG_QUEUE << signal
294           awaken_master
295         else
296           logger.error "ignoring SIG#{signal}, queue=#{SIG_QUEUE.inspect}"
297         end
298       end
299     end
301     # wait for a signal hander to wake us up and then consume the pipe
302     # Wake up every second anyways to run murder_lazy_workers
303     def master_sleep
304       begin
305         ready = IO.select([SELF_PIPE.first], nil, nil, 1) or return
306         ready.first && ready.first.first or return
307         loop { SELF_PIPE.first.read_nonblock(Const::CHUNK_SIZE) }
308       rescue Errno::EAGAIN, Errno::EINTR
309       end
310     end
312     def awaken_master
313       begin
314         SELF_PIPE.last.write_nonblock('.') # wakeup master process from select
315       rescue Errno::EAGAIN, Errno::EINTR
316         # pipe is full, master should wake up anyways
317         retry
318       end
319     end
321     # reaps all unreaped workers
322     def reap_all_workers
323       begin
324         loop do
325           pid, status = Process.waitpid2(-1, Process::WNOHANG)
326           pid or break
327           if @reexec_pid == pid
328             logger.error "reaped #{status.inspect} exec()-ed"
329             @reexec_pid = 0
330             self.pid = @pid.chomp('.oldbin') if @pid
331             proc_name 'master'
332           else
333             worker = WORKERS.delete(pid) and worker.tempfile.close rescue nil
334             logger.info "reaped #{status.inspect} " \
335                         "worker=#{worker.nr rescue 'unknown'}"
336           end
337         end
338       rescue Errno::ECHILD
339       end
340     end
342     # reexecutes the START_CTX with a new binary
343     def reexec
344       if @reexec_pid > 0
345         begin
346           Process.kill(0, @reexec_pid)
347           logger.error "reexec-ed child already running PID:#{@reexec_pid}"
348           return
349         rescue Errno::ESRCH
350           @reexec_pid = 0
351         end
352       end
354       if @pid
355         old_pid = "#{@pid}.oldbin"
356         prev_pid = @pid.dup
357         begin
358           self.pid = old_pid  # clear the path for a new pid file
359         rescue ArgumentError
360           logger.error "old PID:#{valid_pid?(old_pid)} running with " \
361                        "existing pid=#{old_pid}, refusing rexec"
362           return
363         rescue Object => e
364           logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}"
365           return
366         end
367       end
369       @reexec_pid = fork do
370         listener_fds = LISTENERS.map { |sock| sock.fileno }
371         ENV['UNICORN_FD'] = listener_fds.join(',')
372         Dir.chdir(START_CTX[:cwd])
373         cmd = [ START_CTX[:zero] ] + START_CTX[:argv]
375         # avoid leaking FDs we don't know about, but let before_exec
376         # unset FD_CLOEXEC, if anything else in the app eventually
377         # relies on FD inheritence.
378         (3..1024).each do |io|
379           next if listener_fds.include?(io)
380           io = IO.for_fd(io) rescue nil
381           io or next
382           IO_PURGATORY << io
383           io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
384         end
385         logger.info "executing #{cmd.inspect} (in #{Dir.pwd})"
386         @before_exec.call(self)
387         exec(*cmd)
388       end
389       proc_name 'master (old)'
390     end
392     # forcibly terminate all workers that haven't checked in in @timeout
393     # seconds.  The timeout is implemented using an unlinked tempfile
394     # shared between the parent process and each worker.  The worker
395     # runs File#chmod to modify the ctime of the tempfile.  If the ctime
396     # is stale for >@timeout seconds, then we'll kill the corresponding
397     # worker.
398     def murder_lazy_workers
399       diff = stat = nil
400       WORKERS.dup.each_pair do |pid, worker|
401         stat = begin
402           worker.tempfile.stat
403         rescue => e
404           logger.warn "worker=#{worker.nr} PID:#{pid} stat error: #{e.inspect}"
405           kill_worker(:QUIT, pid)
406           next
407         end
408         stat.mode == 0100000 and next
409         (diff = (Time.now - stat.ctime)) <= @timeout and next
410         logger.error "worker=#{worker.nr} PID:#{pid} timeout " \
411                      "(#{diff}s > #{@timeout}s), killing"
412         kill_worker(:KILL, pid) # take no prisoners for @timeout violations
413       end
414     end
416     def spawn_missing_workers
417       (0...@worker_processes).each do |worker_nr|
418         WORKERS.values.include?(worker_nr) and next
419         begin
420           Dir.chdir(START_CTX[:cwd])
421         rescue Errno::ENOENT => err
422           logger.fatal "#{err.inspect} (#{START_CTX[:cwd]})"
423           SIG_QUEUE << :QUIT # forcibly emulate SIGQUIT
424           return
425         end
426         tempfile = Tempfile.new(nil) # as short as possible to save dir space
427         tempfile.unlink # don't allow other processes to find or see it
428         worker = Worker.new(worker_nr, tempfile)
429         @before_fork.call(self, worker)
430         pid = fork { worker_loop(worker) }
431         WORKERS[pid] = 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 { |pid,w|
439         w.nr >= @worker_processes and kill_worker(:QUIT, pid) 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(app, client)
446       response = app.call(env = REQUEST.read(client))
448       if 100 == response.first.to_i
449         client.write(Const::EXPECT_100_RESPONSE)
450         env.delete(Const::HTTP_EXPECT)
451         response = app.call(env)
452       end
454       HttpResponse.write(client, response)
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, 'IGNORE') }
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.tempfile.close! rescue nil }
484       WORKERS.clear
485       LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
486       worker.tempfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
487       @after_fork.call(self, worker) # can drop perms
488       @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       master_pid = Process.ppid # slightly racy, but less memory usage
504       init_worker_process(worker)
505       nr = 0 # this becomes negative if we need to reopen logs
506       alive = worker.tempfile # tempfile 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"
515       app = @app
517       begin
518         nr < 0 and reopen_worker_logs(worker.nr)
519         nr = 0
521         # we're a goner in @timeout seconds anyways if alive.chmod
522         # breaks, so don't trap the exception.  Using fchmod() since
523         # futimes() is not available in base Ruby and I very strongly
524         # prefer temporary files to be unlinked for security,
525         # performance and reliability reasons, so utime is out.  No-op
526         # changes with chmod doesn't update ctime on all filesystems; so
527         # we change our counter each and every time (after process_client
528         # and before IO.select).
529         t == (ti = Time.now.to_i) or alive.chmod(t = ti)
531         ready.each do |sock|
532           begin
533             process_client(app, sock.accept_nonblock)
534             nr += 1
535             t == (ti = Time.now.to_i) or alive.chmod(t = ti)
536           rescue Errno::EAGAIN, Errno::ECONNABORTED
537           end
538           break if nr < 0
539         end
541         # make the following bet: if we accepted clients this round,
542         # we're probably reasonably busy, so avoid calling select()
543         # and do a speculative accept_nonblock on every listener
544         # before we sleep again in select().
545         redo unless nr == 0 # (nr < 0) => reopen logs
547         master_pid == Process.ppid or return
548         alive.chmod(t = 0)
549         begin
550           # timeout used so we can detect parent death:
551           ret = IO.select(LISTENERS, nil, SELF_PIPE, @timeout) or redo
552           ready = ret.first
553         rescue Errno::EINTR
554           ready = LISTENERS
555         rescue Errno::EBADF
556           nr < 0 or return
557         end
558       rescue Object => e
559         if alive
560           logger.error "Unhandled listen loop exception #{e.inspect}."
561           logger.error e.backtrace.join("\n")
562         end
563       end while alive
564     end
566     # delivers a signal to a worker and fails gracefully if the worker
567     # is no longer running.
568     def kill_worker(signal, pid)
569       begin
570         Process.kill(signal, pid)
571       rescue Errno::ESRCH
572         worker = WORKERS.delete(pid) and worker.tempfile.close rescue nil
573       end
574     end
576     # delivers a signal to each worker
577     def kill_each_worker(signal)
578       WORKERS.keys.each { |pid| kill_worker(signal, pid) }
579     end
581     # unlinks a PID file at given +path+ if it contains the current PID
582     # useful as an at_exit handler.
583     def unlink_pid_safe(path)
584       (File.read(path).to_i == $$ and File.unlink(path)) rescue nil
585     end
587     # returns a PID if a given path contains a non-stale PID file,
588     # nil otherwise.
589     def valid_pid?(path)
590       if File.exist?(path) && (pid = File.read(path).to_i) > 1
591         begin
592           Process.kill(0, pid)
593           return pid
594         rescue Errno::ESRCH
595         end
596       end
597       nil
598     end
600     def load_config!
601       begin
602         logger.info "reloading config_file=#{@config.config_file}"
603         @config[:listeners].replace(@init_listeners)
604         @config.reload
605         @config.commit!(self)
606         kill_each_worker(:QUIT)
607         Unicorn::Util.reopen_logs
608         @app = @orig_app
609         build_app! if @preload_app
610         logger.info "done reloading config_file=#{@config.config_file}"
611       rescue Object => e
612         logger.error "error reloading config_file=#{@config.config_file}: " \
613                      "#{e.class} #{e.message}"
614       end
615     end
617     # returns an array of string names for the given listener array
618     def listener_names(listeners = LISTENERS)
619       listeners.map { |io| sock_name(io) }
620     end
622     def build_app!
623       if @app.respond_to?(:arity) && @app.arity == 0
624         if defined?(Gem) && Gem.respond_to?(:refresh)
625           logger.info "Refreshing Gem list"
626           Gem.refresh
627         end
628         @app = @app.call
629       end
630     end
632     def proc_name(tag)
633       $0 = ([ File.basename(START_CTX[:zero]), tag ] +
634               START_CTX[:argv]).join(' ')
635     end
637     def redirect_io(io, path)
638       File.open(path, 'a') { |fp| io.reopen(fp) } if path
639       io.sync = true
640     end
642     def init_self_pipe!
643       SELF_PIPE.each { |io| io.close rescue nil }
644       SELF_PIPE.replace(IO.pipe)
645       SELF_PIPE.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
646     end
648   end