rev+revactor: fix LARGE pipelined uploads
[rainbows.git] / lib / rainbows / revactor.rb
blob51f6c1f1952998e88490d1854e4982343211d614
1 # -*- encoding: binary -*-
2 require 'revactor'
3 require 'fcntl'
4 Revactor::VERSION >= '0.1.5' or abort 'revactor 0.1.5 is required'
6 # Enables use of the Actor model through
7 # {Revactor}[http://revactor.org] under Ruby 1.9.  It spawns one
8 # long-lived Actor for every listen socket in the process and spawns a
9 # new Actor for every client connection accept()-ed.
10 # +worker_connections+ will limit the number of client Actors we have
11 # running at any one time.
13 # Applications using this model are required to be reentrant, but do
14 # not have to worry about race conditions unless they use threads
15 # internally.  \Rainbows! does not spawn threads under this model.
16 # Multiple instances of the same app may run in the same address space
17 # sequentially (but at interleaved points).  Any network dependencies
18 # in the application using this model should be implemented using the
19 # \Revactor library as well, to take advantage of the networking
20 # concurrency features this model provides.
21 module Rainbows::Revactor
23   # :stopdoc:
24   RD_ARGS = {}
26   autoload :Proxy, 'rainbows/revactor/proxy'
28   include Rainbows::Base
29   LOCALHOST = Kgio::LOCALHOST
30   TCP = ::Revactor::TCP::Socket
32   # once a client is accepted, it is processed in its entirety here
33   # in 3 easy steps: read request, call app, write app response
34   def process_client(client) # :nodoc:
35     io = client.instance_variable_get(:@_io)
36     io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
37     rd_args = [ nil ]
38     remote_addr = if TCP === client
39       rd_args << RD_ARGS
40       client.remote_addr
41     else
42       LOCALHOST
43     end
44     hp = Unicorn::HttpParser.new
45     buf = hp.buf
46     alive = false
48     begin
49       ts = nil
50       until env = hp.parse
51         buf << client.read(*rd_args)
52       end
54       env[CLIENT_IO] = client
55       env[RACK_INPUT] = 0 == hp.content_length ?
56                NULL_IO : Unicorn::TeeInput.new(ts = TeeSocket.new(client), hp)
57       env[REMOTE_ADDR] = remote_addr
58       status, headers, body = app.call(env.update(RACK_DEFAULTS))
60       if 100 == status.to_i
61         client.write(EXPECT_100_RESPONSE)
62         env.delete(HTTP_EXPECT)
63         status, headers, body = app.call(env)
64       end
66       if hp.headers?
67         headers = HH.new(headers)
68         range = make_range!(env, status, headers) and status = range.shift
69         alive = hp.next? && G.alive && G.kato > 0
70         headers[CONNECTION] = alive ? KEEP_ALIVE : CLOSE
71         client.write(response_header(status, headers))
72         alive && ts and buf << ts.leftover
73       end
74       write_body(client, body, range)
75     end while alive
76   rescue ::Revactor::TCP::ReadError
77   rescue => e
78     Rainbows::Error.write(io, e)
79   ensure
80     client.close
81   end
83   # runs inside each forked worker, this sits around and waits
84   # for connections and doesn't die until the parent dies (or is
85   # given a INT, QUIT, or TERM signal)
86   def worker_loop(worker) #:nodoc:
87     init_worker_process(worker)
88     require 'rainbows/revactor/body'
89     self.class.__send__(:include, Rainbows::Revactor::Body)
90     RD_ARGS[:timeout] = G.kato if G.kato > 0
91     nr = 0
92     limit = worker_connections
93     actor_exit = Case[:exit, Actor, Object]
95     revactorize_listeners.each do |l, close, accept|
96       Actor.spawn(l, close, accept) do |l, close, accept|
97         Actor.current.trap_exit = true
98         l.controller = l.instance_variable_set(:@receiver, Actor.current)
99         begin
100           while nr >= limit
101             l.disable if l.enabled?
102             logger.info "busy: clients=#{nr} >= limit=#{limit}"
103             Actor.receive do |f|
104               f.when(close) {}
105               f.when(actor_exit) { nr -= 1 }
106               f.after(0.01) {} # another listener could've gotten an exit
107             end
108           end
110           l.enable unless l.enabled?
111           Actor.receive do |f|
112             f.when(close) {}
113             f.when(actor_exit) { nr -= 1 }
114             f.when(accept) do |_, _, s|
115               nr += 1
116               Actor.spawn_link(s) { |c| process_client(c) }
117             end
118           end
119         rescue => e
120           Rainbows::Error.listen_loop(e)
121         end while G.alive
122         Actor.receive do |f|
123           f.when(close) {}
124           f.when(actor_exit) { nr -= 1 }
125         end while nr > 0
126       end
127     end
129     Actor.sleep 1 while G.tick || nr > 0
130     rescue Errno::EMFILE
131       # ignore, let another worker process take it
132   end
134   def revactorize_listeners
135     LISTENERS.map do |s|
136       case s
137       when TCPServer
138         l = ::Revactor::TCP.listen(s, nil)
139         [ l, T[:tcp_closed, ::Revactor::TCP::Socket],
140           T[:tcp_connection, l, ::Revactor::TCP::Socket] ]
141       when UNIXServer
142         l = ::Revactor::UNIX.listen(s)
143         [ l, T[:unix_closed, ::Revactor::UNIX::Socket ],
144           T[:unix_connection, l, ::Revactor::UNIX::Socket] ]
145       end
146     end
147   end
149   # Revactor Sockets do not implement readpartial, so we emulate just
150   # enough to avoid mucking with TeeInput internals.  Fortunately
151   # this code is not heavily used so we can usually avoid the overhead
152   # of adding a userspace buffer.
153   class TeeSocket
154     def initialize(socket)
155       # IO::Buffer is used internally by Rev which Revactor is based on
156       # so we'll always have it available
157       @socket, @rbuf = socket, IO::Buffer.new
158     end
160     def leftover
161       @rbuf.read
162     end
164     # Revactor socket reads always return an unspecified amount,
165     # sometimes too much
166     def kgio_read(length, dst = "")
167       return dst.replace("") if length == 0
169       # always check and return from the userspace buffer first
170       @rbuf.size > 0 and return dst.replace(@rbuf.read(length))
172       # read off the socket since there was nothing in rbuf
173       tmp = @socket.read
175       # we didn't read too much, good, just return it straight back
176       # to avoid needlessly wasting memory bandwidth
177       tmp.size <= length and return dst.replace(tmp)
179       # ugh, read returned too much
180       @rbuf << tmp[length, tmp.size]
181       dst.replace(tmp[0, length])
182       rescue EOFError
183     end
185     # just proxy any remaining methods TeeInput may use
186     def close
187       @socket.close
188     end
189   end
191   # :startdoc: