Object
This is the main driver of Mongrel, while the Mongrel::HttpParser and Mongrel::URIClassifier make up the majority of how the server functions. It’s a very simple class that just has a thread accepting connections and a simple HttpServer.process_client function to do the heavy lifting with the IO and Ruby.
You use it by doing the following:
server = HttpServer.new("0.0.0.0", 3000) server.register("/stuff", MyNiftyHandler.new) server.run.join
The last line can be just server.run if you don’t want to join the thread used. If you don’t though Ruby will mysteriously just exit on you.
Ruby’s thread implementation is “interesting” to say the least. Experiments with many different types of IO processing simply cannot make a dent in it. Future releases of Mongrel will find other creative ways to make threads faster, but don’t hold your breath until Ruby 1.9 is actually finally useful.
Creates a working server on host:port (strange things happen if port isn’t a Number). Use HttpServer::run to start the server and HttpServer.acceptor.join to join the thread that’s processing incoming requests on the socket.
The num_processors optional argument is the maximum number of concurrent processors to accept, anything over this is closed immediately to maintain server processing performance. This may seem mean but it is the most efficient way to deal with overload. Other schemes involve still parsing the client’s request which defeats the point of an overload handling system.
The throttle parameter is a sleep timeout (in hundredths of a second) that is placed between socket.accept calls in order to give the server a cheap throttle time. It defaults to 0 and actually if it is 0 then the sleep is not done at all.
# File lib/mongrel.rb, line 96 96: def initialize(host, port, num_processors=950, throttle=0, timeout=60) 97: 98: tries = 0 99: @socket = TCPServer.new(host, port) 100: 101: @classifier = URIClassifier.new 102: @host = host 103: @port = port 104: @workers = ThreadGroup.new 105: @throttle = throttle / 100.0 106: @num_processors = num_processors 107: @timeout = timeout 108: end
# File lib/mongrel.rb, line 246 246: def configure_socket_options 247: case RUBY_PLATFORM 248: when /linux/ 249: # 9 is currently TCP_DEFER_ACCEPT 250: $tcp_defer_accept_opts = [Socket::SOL_TCP, 9, 1] 251: $tcp_cork_opts = [Socket::SOL_TCP, 3, 1] 252: when /freebsd(([1-4]\..{1,2})|5\.[0-4])/ 253: # Do nothing, just closing a bug when freebsd <= 5.4 254: when /freebsd/ 255: # Use the HTTP accept filter if available. 256: # The struct made by pack() is defined in /usr/include/sys/socket.h as accept_filter_arg 257: unless `/sbin/sysctl -nq net.inet.accf.http`.empty? 258: $tcp_defer_accept_opts = [Socket::SOL_SOCKET, Socket::SO_ACCEPTFILTER, ['httpready', nil].pack('a16a240')] 259: end 260: end 261: end
Performs a wait on all the currently running threads and kills any that take too long. It waits by @timeout seconds, which can be set in .initialize or via mongrel_rails. The @throttle setting does extend this waiting period by that much longer.
# File lib/mongrel.rb, line 239 239: def graceful_shutdown 240: while reap_dead_workers("shutdown") > 0 241: STDERR.puts "Waiting for #{@workers.list.length} requests to finish, could take #{@timeout + @throttle} seconds." 242: sleep @timeout / 10 243: end 244: end
Does the majority of the IO processing. It has been written in Ruby using about 7 different IO processing strategies and no matter how it’s done the performance just does not improve. It is currently carefully constructed to make sure that it gets the best possible performance, but anyone who thinks they can make it faster is more than welcome to take a crack at it.
# File lib/mongrel.rb, line 115 115: def process_client(client) 116: begin 117: parser = HttpParser.new 118: params = HttpParams.new 119: request = nil 120: data = client.readpartial(Const::CHUNK_SIZE) 121: nparsed = 0 122: 123: # Assumption: nparsed will always be less since data will get filled with more 124: # after each parsing. If it doesn't get more then there was a problem 125: # with the read operation on the client socket. Effect is to stop processing when the 126: # socket can't fill the buffer for further parsing. 127: while nparsed < data.length 128: nparsed = parser.execute(params, data, nparsed) 129: 130: if parser.finished? 131: if not params[Const::REQUEST_PATH] 132: # it might be a dumbass full host request header 133: uri = URI.parse(params[Const::REQUEST_URI]) 134: params[Const::REQUEST_PATH] = uri.path 135: end 136: 137: raise "No REQUEST PATH" if not params[Const::REQUEST_PATH] 138: 139: script_name, path_info, handlers = @classifier.resolve(params[Const::REQUEST_PATH]) 140: 141: if handlers 142: params[Const::PATH_INFO] = path_info 143: params[Const::SCRIPT_NAME] = script_name 144: 145: # From http://www.ietf.org/rfc/rfc3875 : 146: # "Script authors should be aware that the REMOTE_ADDR and REMOTE_HOST 147: # meta-variables (see sections 4.1.8 and 4.1.9) may not identify the 148: # ultimate source of the request. They identify the client for the 149: # immediate request to the server; that client may be a proxy, gateway, 150: # or other intermediary acting on behalf of the actual source client." 151: params[Const::REMOTE_ADDR] = client.peeraddr.last 152: 153: # select handlers that want more detailed request notification 154: notifiers = handlers.select { |h| h.request_notify } 155: request = HttpRequest.new(params, client, notifiers) 156: 157: # in the case of large file uploads the user could close the socket, so skip those requests 158: break if request.body == nil # nil signals from HttpRequest::initialize that the request was aborted 159: 160: # request is good so far, continue processing the response 161: response = HttpResponse.new(client) 162: 163: # Process each handler in registered order until we run out or one finalizes the response. 164: handlers.each do |handler| 165: handler.process(request, response) 166: break if response.done or client.closed? 167: end 168: 169: # And finally, if nobody closed the response off, we finalize it. 170: unless response.done or client.closed? 171: response.finished 172: end 173: else 174: # Didn't find it, return a stock 404 response. 175: client.write(Const::ERROR_404_RESPONSE) 176: end 177: 178: break #done 179: else 180: # Parser is not done, queue up more data to read and continue parsing 181: chunk = client.readpartial(Const::CHUNK_SIZE) 182: break if !chunk or chunk.length == 0 # read failed, stop processing 183: 184: data << chunk 185: if data.length >= Const::MAX_HEADER 186: raise HttpParserError.new("HEADER is longer than allowed, aborting client early.") 187: end 188: end 189: end 190: rescue EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL,Errno::EBADF 191: client.close rescue nil 192: rescue HttpParserError => e 193: STDERR.puts "#{Time.now}: HTTP parse error, malformed request (#{params[Const::HTTP_X_FORWARDED_FOR] || client.peeraddr.last}): #{e.inspect}" 194: STDERR.puts "#{Time.now}: REQUEST DATA: #{data.inspect}\n---\nPARAMS: #{params.inspect}\n---\n" 195: rescue Errno::EMFILE 196: reap_dead_workers('too many files') 197: rescue Object => e 198: STDERR.puts "#{Time.now}: Read error: #{e.inspect}" 199: STDERR.puts e.backtrace.join("\n") 200: ensure 201: begin 202: client.close 203: rescue IOError 204: # Already closed 205: rescue Object => e 206: STDERR.puts "#{Time.now}: Client error: #{e.inspect}" 207: STDERR.puts e.backtrace.join("\n") 208: end 209: request.body.close! if request and request.body.class == Tempfile 210: end 211: end
Used internally to kill off any worker threads that have taken too long to complete processing. Only called if there are too many processors currently servicing. It returns the count of workers still active after the reap is done. It only runs if there are workers to reap.
# File lib/mongrel.rb, line 217 217: def reap_dead_workers(reason='unknown') 218: if @workers.list.length > 0 219: STDERR.puts "#{Time.now}: Reaping #{@workers.list.length} threads for slow workers because of '#{reason}'" 220: error_msg = "Mongrel timed out this thread: #{reason}" 221: mark = Time.now 222: @workers.list.each do |worker| 223: worker[:started_on] = Time.now if not worker[:started_on] 224: 225: if mark - worker[:started_on] > @timeout + @throttle 226: STDERR.puts "Thread #{worker.inspect} is too old, killing." 227: worker.raise(TimeoutError.new(error_msg)) 228: end 229: end 230: end 231: 232: return @workers.list.length 233: end
Simply registers a handler with the internal URIClassifier. When the URI is found in the prefix of a request then your handler’s HttpHandler::process method is called. See Mongrel::URIClassifier#register for more information.
If you set in_front=true then the passed in handler will be put in the front of the list for that particular URI. Otherwise it’s placed at the end of the list.
# File lib/mongrel.rb, line 326 326: def register(uri, handler, in_front=false) 327: begin 328: @classifier.register(uri, [handler]) 329: rescue URIClassifier::RegistrationError => e 330: handlers = @classifier.resolve(uri)[2] 331: if handlers 332: # Already registered 333: method_name = in_front ? 'unshift' : 'push' 334: handlers.send(method_name, handler) 335: else 336: raise 337: end 338: end 339: handler.listener = self 340: end
Runs the thing. It returns the thread used so you can “join” it. You can also access the HttpServer::acceptor attribute to get the thread later.
# File lib/mongrel.rb, line 265 265: def run 266: BasicSocket.do_not_reverse_lookup=true 267: 268: configure_socket_options 269: 270: if defined?($tcp_defer_accept_opts) and $tcp_defer_accept_opts 271: @socket.setsockopt(*$tcp_defer_accept_opts) rescue nil 272: end 273: 274: @acceptor = Thread.new do 275: begin 276: while true 277: begin 278: client = @socket.accept 279: 280: if defined?($tcp_cork_opts) and $tcp_cork_opts 281: client.setsockopt(*$tcp_cork_opts) rescue nil 282: end 283: 284: worker_list = @workers.list 285: 286: if worker_list.length >= @num_processors 287: STDERR.puts "Server overloaded with #{worker_list.length} processors (#@num_processors max). Dropping connection." 288: client.close rescue nil 289: reap_dead_workers("max processors") 290: else 291: thread = Thread.new(client) {|c| process_client(c) } 292: thread[:started_on] = Time.now 293: @workers.add(thread) 294: 295: sleep @throttle if @throttle > 0 296: end 297: rescue StopServer 298: break 299: rescue Errno::EMFILE 300: reap_dead_workers("too many open files") 301: sleep 0.5 302: rescue Errno::ECONNABORTED 303: # client closed the socket even before accept 304: client.close rescue nil 305: rescue Object => e 306: STDERR.puts "#{Time.now}: Unhandled listen loop exception #{e.inspect}." 307: STDERR.puts e.backtrace.join("\n") 308: end 309: end 310: graceful_shutdown 311: ensure 312: @socket.close 313: # STDERR.puts "#{Time.now}: Closed socket." 314: end 315: end 316: 317: return @acceptor 318: end
Stops the acceptor thread and then causes the worker threads to finish off the request queue before finally exiting.
# File lib/mongrel.rb, line 351 351: def stop(synchronous=false) 352: @acceptor.raise(StopServer.new) 353: 354: if synchronous 355: sleep(0.5) while @acceptor.alive? 356: end 357: end
Removes any handlers registered at the given URI. See Mongrel::URIClassifier#unregister for more information. Remember this removes them all so the entire processing chain goes away.
# File lib/mongrel.rb, line 345 345: def unregister(uri) 346: @classifier.unregister(uri) 347: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.