1 # Copyright (c) 2009 Eric Wong
2 # You can redistribute it and/or modify it under the same terms as Ruby.
4 # this class *must* be used with Rack::Chunked
7 class Inetd < Struct.new(:cmd)
9 class CatBody < Struct.new(:errors, :err_rd, :out_rd, :pid_map)
10 def initialize(env, cmd)
11 self.errors = env['rack.errors']
12 in_rd, in_wr = IO.pipe
13 self.err_rd, err_wr = IO.pipe
14 self.out_rd, out_wr = IO.pipe
17 inp, out, err = (0..2).map { |i| IO.new(i) }
21 [ in_rd, in_wr, err_rd, err_wr, out_rd, out_wr ].each { |i| i.close }
24 [ in_rd, err_wr, out_wr ].each { |io| io.close }
25 [ in_wr, err_rd, out_rd ].each { |io| io.binmode }
28 # Unfortunately, input here must be processed inside a seperate
29 # thread/process using blocking I/O since env['rack.input'] is not
30 # IO.select-able and attempting to make it so would trip Rack::Lint
32 input = env['rack.input']
33 [ err_rd, out_rd ].each { |io| io.close }
36 # this is dependent on input.read having readpartial semantics:
37 while input.read(16384, buf)
44 inp_pid => 'input streamer',
45 cmd_pid => cmd.inspect,
51 rd, = IO.select([err_rd, out_rd])
52 rd && rd.first or next
54 if rd.include?(err_rd)
56 errors.write(err_rd.read_nonblock(16384))
63 rd.include?(out_rd) or next
66 yield out_rd.read_nonblock(16384)
71 rescue EOFError,Errno::EPIPE,Errno::EBADF,Errno::EINVAL
79 pid_map.each { |pid, str|
81 pid, status = Process.waitpid2(pid)
83 errors.write("#{str}: #{status.inspect} (PID:#{pid})\n")
85 errors.write("Failed to reap #{str} (PID:#{pid})\n")
97 /\A100-continue\z/i =~ env[Unicorn::Const::HTTP_EXPECT] and
98 return [ 100, {} , [] ]
100 [ 200, { 'Content-Type' => 'application/octet-stream' },
101 CatBody.new(env, cmd) ]