Improving the rails spawner script
Posted by Guy Naor Sun, 05 Mar 2006 06:51:00 GMT
The spawner script in rails is pretty cool in that it will keep looking out for the FastCGI processes and make sure they are all working.
What I don't like about it, is that it launches the dispatcher again and again, letting it fail when the socket is already open. This is doing the unnecessary and puts more load on the system. But most of all it's just ugly!
As we're in a ruby script anyway, why not use it to see if the socket is in use before we launch the dispatcher? The only thing that needs to be changed is the spawn method (and you need to add a require 'socket' at the top of the script). We try to open a listening socket on the port we're being passed. If it opens, it means no process is listening on it and we can launch the dispatcher. If it is in use, an exception will be raised, and we just catch it, print a YES, and we're done.
def spawn(port)
print "Checking if something is already running on port #{port}..."
begin
srv = TCPServer.new('0.0.0.0', port)
srv.close
srv = nil
print "NO\n "
print "Starting FCGI on port: #{port}\n "
system("#{OPTIONS[:spawner]} -f #{OPTIONS[:dispatcher]} -p #{port}")
rescue
print "YES\n"
end
end
Now it will not even get to the dispatcher if the socket is already in use.


















Probably this is no great revelation to anyone, but the above code is what I've got in my Rails 1.1 spawner.rb! I guess Guy got it accepted as a patch.
Yes, it was added a week or so before the Rails 1.1 release.