github
Advanced Search
  • Home
  • Pricing and Signup
  • Explore GitHub
  • Blog
  • Login

FooBarWidget / passenger

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
  • Pull Request
  • Download Source
    • 833
    • 69
  • Source
  • Commits
  • Network (69)
  • Wiki (4)
  • Graphs
  • Tree: 3579608

click here to add a description

click here to add a homepage

  • Branches (6)
    • experimental
    • master
    • multicorn
    • stable-1.0
    • stable-2.0
    • stable-2.1
  • Tags (28)
    • request_handler_with_pipes
    • release-2.2.9
    • release-2.2.8
    • release-2.2.7
    • release-2.2.6
    • release-2.2.5
    • release-2.2.4
    • release-2.2.3
    • release-2.2.2
    • release-2.2.1
    • release-2.2.0
    • release-2.1.3
    • release-2.1.2
    • release-2.1.1
    • release-2.0.6
    • release-2.0.5
    • release-2.0.4
    • release-2.0.3
    • release-2.0.2
    • release-2.0.1
    • release-1.9.1
    • release-1.9.0
    • release-1.0.5
    • release-1.0.4
    • release-1.0.3
    • release-1.0.2
    • release-1.0.1
    • release-1.0.0
Sending Request…
Click here to lend your support to: passenger and make a donation at www.pledgie.com ! Edit Pledgie Setup

Pledgie Donations

Once activated, we'll place the following badge in your repository's detail box:
Pledgie_example
This service is courtesy of Pledgie.

Phusion Passenger (mod_rails) — Read more

  cancel

http://www.modrails.com/

  cancel
  • Private
  • Read-Only
  • HTTP Read-Only

This URL has Read+Write access

Fix typo (APR -> APU) 
Hongli Lai (Phusion) (author)
Fri Jan 23 14:38:34 -0800 2009
commit  3579608738f3541340f1d5bc5b703bfaa3c5128c
tree    51e6e2b8e661a7ee90004596c12ab5cc52f0c474
parent  0c66e053c1755708024279fa7a40df9cc30f149c
passenger / lib / passenger / abstract_request_handler.rb lib/passenger/abstract_request_handler.rb
100644 450 lines (413 sloc) 14.621 kb
edit raw blame history
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# Phusion Passenger - http://www.modrails.com/
# Copyright (C) 2008 Phusion
#
# Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
require 'socket'
require 'fcntl'
require 'passenger/message_channel'
require 'passenger/utils'
module Passenger
 
# The request handler is the layer which connects Apache with the underlying application's
# request dispatcher (i.e. either Rails's Dispatcher class or Rack).
# The request handler's job is to process incoming HTTP requests using the
# currently loaded Ruby on Rails application. HTTP requests are forwarded
# to the request handler by the web server. HTTP responses generated by the
# RoR application are forwarded to the web server, which, in turn, sends the
# response back to the HTTP client.
#
# AbstractRequestHandler is an abstract base class for easing the implementation
# of request handlers for Rails and Rack.
#
# == Design decisions
#
# Some design decisions are made because we want to decrease system
# administrator maintenance overhead. These decisions are documented
# in this section.
#
# === Owner pipes
#
# Because only the web server communicates directly with a request handler,
# we want the request handler to exit if the web server has also exited.
# This is implemented by using a so-called _owner pipe_. The writable part
# of the pipe will be passed to the web server* via a Unix socket, and the web
# server will own that part of the pipe, while AbstractRequestHandler owns
# the readable part of the pipe. AbstractRequestHandler will continuously
# check whether the other side of the pipe has been closed. If so, then it
# knows that the web server has exited, and so the request handler will exit
# as well. This works even if the web server gets killed by SIGKILL.
#
# * It might also be passed to the ApplicationPoolServerExecutable, if the web
# server's using ApplicationPoolServer instead of StandardApplicationPool.
#
#
# == Request format
#
# Incoming "HTTP requests" are not true HTTP requests, i.e. their binary
# representation do not conform to RFC 2616. Instead, the request format
# is based on CGI, and is similar to that of SCGI.
#
# The format consists of 3 parts:
# - A 32-bit big-endian integer, containing the size of the transformed
# headers.
# - The transformed HTTP headers.
# - The verbatim (untransformed) HTTP request body.
#
# HTTP headers are transformed to a format that satisfies the following
# grammar:
#
# headers ::= header*
# header ::= name NUL value NUL
# name ::= notnull+
# value ::= notnull+
# notnull ::= "\x01" | "\x02" | "\x02" | ... | "\xFF"
# NUL = "\x00"
#
# The web server transforms the HTTP request to the aforementioned format,
# and sends it to the request handler.
class AbstractRequestHandler
# Signal which will cause the Rails application to exit immediately.
HARD_TERMINATION_SIGNAL = "SIGTERM"
# Signal which will cause the Rails application to exit as soon as it's done processing a request.
SOFT_TERMINATION_SIGNAL = "SIGUSR1"
BACKLOG_SIZE = 100
MAX_HEADER_SIZE = 128 * 1024
 
# String constants which exist to relieve Ruby's garbage collector.
IGNORE = 'IGNORE' # :nodoc:
DEFAULT = 'DEFAULT' # :nodoc:
NULL = "\0" # :nodoc:
CONTENT_LENGTH = 'CONTENT_LENGTH' # :nodoc:
HTTP_CONTENT_LENGTH = 'HTTP_CONTENT_LENGTH' # :nodoc:
X_POWERED_BY = 'X-Powered-By' # :nodoc:
REQUEST_METHOD = 'REQUEST_METHOD' # :nodoc:
PING = 'ping' # :nodoc:
 
# The name of the socket on which the request handler accepts
# new connections. At this moment, this value is always the filename
# of a Unix domain socket.
#
# See also #socket_type.
attr_reader :socket_name
 
# The type of socket that #socket_name refers to. At the moment, the
# value is always 'unix', which indicates a Unix domain socket.
attr_reader :socket_type
 
# Specifies the maximum allowed memory usage, in MB. If after having processed
# a request AbstractRequestHandler detects that memory usage has risen above
# this limit, then it will gracefully exit (that is, exit after having processed
# all pending requests).
#
# A value of 0 (the default) indicates that there's no limit.
attr_accessor :memory_limit
 
# The number of times the main loop has iterated so far. Mostly useful
# for unit test assertions.
attr_reader :iterations
 
# Number of requests processed so far. This includes requests that raised
# exceptions.
attr_reader :processed_requests
 
# Create a new RequestHandler with the given owner pipe.
# +owner_pipe+ must be the readable part of a pipe IO object.
#
# Additionally, the following options may be given:
# - memory_limit: Used to set the +memory_limit+ attribute.
def initialize(owner_pipe, options = {})
if should_use_unix_sockets?
create_unix_socket_on_filesystem
else
create_tcp_socket
end
@socket.close_on_exec!
@owner_pipe = owner_pipe
@previous_signal_handlers = {}
@main_loop_thread_lock = Mutex.new
@main_loop_thread_cond = ConditionVariable.new
@memory_limit = options["memory_limit"] || 0
@iterations = 0
@processed_requests = 0
end
 
# Clean up temporary stuff created by the request handler.
#
# If the main loop was started by #main_loop, then this method may only
# be called after the main loop has exited.
#
# If the main loop was started by #start_main_loop_thread, then this method
# may be called at any time, and it will stop the main loop thread.
def cleanup
if @main_loop_thread
@main_loop_thread.raise(Interrupt.new("Cleaning up"))
@main_loop_thread.join
end
@socket.close rescue nil
@owner_pipe.close rescue nil
File.unlink(@socket_name) rescue nil
end
 
# Check whether the main loop's currently running.
def main_loop_running?
return @main_loop_running
end
 
# Enter the request handler's main loop.
def main_loop
if defined?(::Passenger::AbstractRequestHandler)
# Some applications have a model named 'Passenger'.
# So we temporarily remove it from the global namespace
# and restore it later.
phusion_passenger_namespace = ::Passenger
Object.send(:remove_const, :Passenger)
end
reset_signal_handlers
begin
@graceful_termination_pipe = IO.pipe
@graceful_termination_pipe[0].close_on_exec!
@graceful_termination_pipe[1].close_on_exec!
 
@main_loop_thread_lock.synchronize do
@main_loop_running = true
@main_loop_thread_cond.broadcast
end
 
install_useful_signal_handlers
 
while true
@iterations += 1
client = accept_connection
if client.nil?
break
end
begin
headers, input = parse_request(client)
if headers
if headers[REQUEST_METHOD] == PING
process_ping(headers, input, client)
else
process_request(headers, input, client)
end
end
rescue IOError, SocketError, SystemCallError => e
print_exception("Passenger RequestHandler", e)
ensure
# 'input' is the same as 'client' so we don't
# need to close that.
client.close rescue nil
end
@processed_requests += 1
end
rescue EOFError
# Exit main loop.
rescue Interrupt
# Exit main loop.
rescue SignalException => signal
if signal.message != HARD_TERMINATION_SIGNAL &&
signal.message != SOFT_TERMINATION_SIGNAL
raise
end
ensure
@graceful_termination_pipe[0].close rescue nil
@graceful_termination_pipe[1].close rescue nil
revert_signal_handlers
if phusion_passenger_namespace
Object.send(:remove_const, :Passenger) rescue nil
Object.const_set(:Passenger, phusion_passenger_namespace)
end
@main_loop_thread_lock.synchronize do
@main_loop_running = false
@main_loop_thread_cond.broadcast
end
end
end
 
# Start the main loop in a new thread. This thread will be stopped by #cleanup.
def start_main_loop_thread
@main_loop_thread = Thread.new do
main_loop
end
@main_loop_thread_lock.synchronize do
while !@main_loop_running
@main_loop_thread_cond.wait(@main_loop_thread_lock)
end
end
end
 
private
include Utils
 
def should_use_unix_sockets?
# There seems to be a bug in MacOS X w.r.t. Unix sockets.
# When the Unix socket subsystem is under high stress, a
# recv()/read() on a Unix socket can return 0 even when EOF is
# not reached. We work around this by using TCP sockets on
# MacOS X.
return RUBY_PLATFORM !~ /darwin/
end
 
def create_unix_socket_on_filesystem
done = false
while !done
begin
if defined?(NativeSupport)
unix_path_max = NativeSupport::UNIX_PATH_MAX
else
unix_path_max = 100
end
@socket_name = "#{passenger_tmpdir}/passenger_backend.#{generate_random_id(:base64)}"
@socket_name = @socket_name.slice(0, unix_path_max - 1)
@socket = UNIXServer.new(@socket_name)
@socket.listen(BACKLOG_SIZE)
@socket_type = "unix"
File.chmod(0600, @socket_name)
done = true
rescue Errno::EADDRINUSE
# Do nothing, try again with another name.
end
end
end
 
def create_tcp_socket
# We use "127.0.0.1" as address in order to force
# TCPv4 instead of TCPv6.
@socket = TCPServer.new('127.0.0.1', 0)
@socket.listen(BACKLOG_SIZE)
@socket_name = "127.0.0.1:#{@socket.addr[1]}"
@socket_type = "tcp"
end
 
# Reset signal handlers to their default handler, and install some
# special handlers for a few signals. The previous signal handlers
# will be put back by calling revert_signal_handlers.
def reset_signal_handlers
Signal.list_trappable.each_key do |signal|
begin
prev_handler = trap(signal, DEFAULT)
if prev_handler != DEFAULT
@previous_signal_handlers[signal] = prev_handler
end
rescue ArgumentError
# Signal cannot be trapped; ignore it.
end
end
trap('HUP', IGNORE)
end
 
def install_useful_signal_handlers
trappable_signals = Signal.list_trappable
 
trap(SOFT_TERMINATION_SIGNAL) do
@graceful_termination_pipe[1].close rescue nil
end if trappable_signals.has_key?(SOFT_TERMINATION_SIGNAL.sub(/^SIG/, ''))
 
trap('ABRT') do
raise SignalException, "SIGABRT"
end if trappable_signals.has_key?('ABRT')
 
trap('QUIT') do
if Kernel.respond_to?(:caller_for_all_threads)
output = "========== Process #{Process.pid}: backtrace dump ==========\n"
caller_for_all_threads.each_pair do |thread, stack|
output << ("-" * 60) << "\n"
output << "# Thread: #{thread.inspect}, "
if thread == Thread.main
output << "[main thread], "
else
output << "[current thread], "
end
output << "alive = #{thread.alive?}\n"
output << ("-" * 60) << "\n"
output << " " << stack.join("\n ")
output << "\n\n"
end
else
output = "========== Process #{Process.pid}: backtrace dump ==========\n"
output << ("-" * 60) << "\n"
output << "# Current thread: #{Thread.current.inspect}\n"
output << ("-" * 60) << "\n"
output << " " << caller.join("\n ")
end
STDERR.puts(output)
STDERR.flush
end if trappable_signals.has_key?('QUIT')
end
 
def revert_signal_handlers
@previous_signal_handlers.each_pair do |signal, handler|
trap(signal, handler)
end
end
 
def accept_connection
ios = select([@socket, @owner_pipe, @graceful_termination_pipe[0]]).first
if ios.include?(@socket)
client = @socket.accept
client.close_on_exec!
 
# The real input stream is not seekable (calling _seek_
# or _rewind_ on it will raise an exception). But some
# frameworks (e.g. Merb) call _rewind_ if the object
# responds to it. So we simply undefine _seek_ and
# _rewind_.
client.instance_eval do
undef seek if respond_to?(:seek)
undef rewind if respond_to?(:rewind)
end
 
return client
else
# The other end of the owner pipe has been closed, or the
# graceful termination pipe has been closed. This is our
# call to gracefully terminate (after having processed all
# incoming requests).
return nil
end
end
 
# Read the next request from the given socket, and return
# a pair [headers, input_stream]. _headers_ is a Hash containing
# the request headers, while _input_stream_ is an IO object for
# reading HTTP POST data.
#
# Returns nil if end-of-stream was encountered.
def parse_request(socket)
channel = MessageChannel.new(socket)
headers_data = channel.read_scalar(MAX_HEADER_SIZE)
if headers_data.nil?
return
end
headers = Hash[*headers_data.split(NULL)]
headers[CONTENT_LENGTH] = headers[HTTP_CONTENT_LENGTH]
return [headers, socket]
rescue SecurityError => e
STDERR.puts("*** Passenger RequestHandler: HTTP header size exceeded maximum.")
STDERR.flush
print_exception("Passenger RequestHandler", e)
end
 
def process_ping(env, input, output)
output.write("pong")
end
 
# Generate a long, cryptographically secure random ID string, which
# is also a valid filename.
def generate_random_id(method)
case method
when :base64
require 'base64' unless defined?(Base64)
data = Base64.encode64(File.read("/dev/urandom", 64))
data.gsub!("\n", '')
data.gsub!("+", '')
data.gsub!("/", '')
data.gsub!(/==$/, '')
when :hex
data = File.read("/dev/urandom", 64).unpack('H*')[0]
end
return data
end
 
def self.determine_passenger_version
rakefile = "#{File.dirname(__FILE__)}/../../Rakefile"
if File.exist?(rakefile)
File.read(rakefile) =~ /^PACKAGE_VERSION = "(.*)"$/
return $1
else
return File.read("/etc/passenger_version.txt")
end
end
 
def self.determine_passenger_header
header = "Phusion Passenger (mod_rails/mod_rack) #{PASSENGER_VERSION}"
if File.exist?("#{File.dirname(__FILE__)}/../../enterprisey.txt") ||
File.exist?("/etc/passenger_enterprisey.txt")
header << ", Enterprise Edition"
end
return header
end
 
public
PASSENGER_VERSION = determine_passenger_version
PASSENGER_HEADER = determine_passenger_header
end
 
end # module Passenger
 
Blog | Support | Training | Contact | API | Status | Twitter | Help | Security
© 2010 GitHub Inc. All rights reserved. | Terms of Service | Privacy Policy
Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
Dedicated Server