Archive for the ‘IIS’ Category

Thursday, April 12th, 2007

A nice write-up of getting Rails up and running using Brent’s installer.

Monday, February 19th, 2007

Sorry folks - I’ve not been working with IIS recently.

But luckily, others have not been standing still. As well as Microsoft themselves looking at adding FastCGI support to IIS, the number of deployment options you have seem to be growing.

UPDATE: plus this one from Druid (in the comments but reprinted for clarity).

Wednesday, January 3rd, 2007

Brent Heinz contacted me last year asking me to point to his new installer. It’s taken me a while to get round to it but here it is … automating all the rubbish that I wrote about all those months ago.

Tuesday, January 24th, 2006

Update: Brent Heinz has written an installer to automate this.

Last time I wrote about setting up Rails on IIS I was in a bit of a rush. However, this time, hot on the heels of an installation on a live customer site, on Windows Server 2003, I have decided to rewrite the original article.

The process I’ve followed here has worked on IIS on Windows 2000 Server, Windows XP and now Windows Server 2003. I don’t know which versions of IIS were involved but the same basic process has been used across all three. I’ve not quite managed to get web services working over IIS but I reckon I’m not far away - so follow the instructions below and I’ll update you when we get there.

So where do we begin? First of all, collect all your bits and bobs together. In particular you will need

Ruby is for obvious reasons.

Rails is useful as I found that 2003 is so locked down that gem did not have access to download the framework from rubyforge.

The DBI-ADO interface is needed for a single file, ADO.rb, that allows the SQL Server adapter to connect to MS-SQL.

Ruby for IIS does some patching to Rails and Ruby to allow IIS to route its requests to FastCGI and eventually to Rails. In the interests of full disclosure I should say that I have not looked at the source of this and so do not know exactly how it works. I will get round to it, promise.

FastCGI keeps a number of Ruby/Rails processes running within IIS. This means that when a request comes in from a client you do not need to start a new Ruby process (and hence incur the not insignificant cost of loading all the libraries) every time. Instead FastCGI starts N processes and if all are busy will start more, upto a maximum of M processes and routes requests to whichever process is free.

The Ionic Rewriter takes a Rails-friendly url (controller/action/id) and rewrites it into a form that IIS understands. IIS then dispatches this new URL to FastCGI which in turn passes it to Ruby.

So, you’ve installed Rails (into C:\Ruby) and copied your application files over (into D:\MyApp). You’ve added the Rails framework into your application’s vendor folder (D:\MyApp\vendor) - this is because we will be altering some of the framework files so we want to keep our changes (in D:\MyApp\vendor) separate from the main Rails installation (in C:\ruby\lib\ruby\gems\1.8\gems). You then need to extract ADO.rb from the DBI file and place it in C:\ruby\lib\ruby\site_ruby\1.8\DBD - you will need to create an ADO folder and place the file into there.

Next up, edit your application’s configuration file (either one of the environment specific ones, or your general one - you decide) and add the line:

ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:tmpdir] = 'D:\\Temp\\'

. You will need to create a Temp folder on D: or your application will silently fail to work. The point of this is to force Ruby to place its session files into a known folder - if you read back through this blog you will find that at one point I was having strange behaviour with sessions. It turns out that as you run under different configurations (CGI, FastCGI and WEBrick) Ruby sometimes places its files in different locations and you get unpredictable behaviour. Plus it also helps when you need to clean up your sessions (which you will need to do later).

Now run your application under WEBrick. This is vital. If it doesn’t work here it definitely won’t work under IIS. Don’t say I didn’t warn you. What? It didn’t work under WEBrick. I bet you forgot to edit your database.yml file. Go and do it now and test it again. Still doesn’t work? Seems to fail silently with no entries in your log file. I told you - create a D:\Temp folder and you should be OK.

Copy your ISAPI files to a safe place - I tend to put them in C:\InetPub - they are associated with IIS but not available to the public. This means copying your FastCGI.DLL and IsapiRewrite4.DLL and IsapiRewrite4.INI files to wherever. Watch out, the Ionic Rewriter DLL and INI file must live in the same folder.

Fire up the trusty pain-in-the-arse Internet Information Services configuration manager. The instructions here are for setting up one site on the “Default Web Site” - I don’t think it will be too hard to set up multiple Rails sites on one IIS site and even easier to set up multiple IIS sites, each containing a single Rails site. But I’ve not done it so I won’t go on about it here.

Right-click on your “Default Web Site” and select “Properties”. Select ISAPI Filters. Click Add and enter a filter name of “Rewriter” and select the IsapiRewrite4 DLL.

Next, switch to the “Home Directory” tab. Make sure “a directory stored on this computer” is selected and set D:\MyApp\Public as the local path. Put your application name into “Application Name” (if this is greyed out then click “Create” to set up the site as an application) and make sure “Scripts and Executables” is selected for “execute permissions”. Next up, click “Configuration”. Under “Mappings” click “Add” and select FastCGI.DLL as the executable, .fcgi as the extension (if you are going to have multiple Rails applications on a single server you need to vary this extension on a Rails-application-specific basis - for example .myapp1, .myapp2 etc), with “All Verbs”, “Script Engine” and “Check that file exists” all selected.

If you’re on Server 2003 there is an extra step. You have to allow IIS access to the executables you are going to be using. Create a new Web Server Extension in the IIS Configuration Manager, calling it “MyApp”. Add FastCGI.DLL, IsapiRewriter4.DLL and RubyW.exe to this extension and make sure that it is enabled.

Phew - what have we done so far?

  • We’ve installed Rails and our application and made sure it works OK under WEBrick
  • We’ve told IIS that the default web site for this server is our application’s public folder
  • We’ve told IIS that any request to the default web site should be fed through the Ionic Rewriter
  • We’ve told IIS that any request for a .fcgi file should be fed through FastCGI

What we’ve not done is tell Ionic or FastCGI how to behave.

Ionic first. Edit IsapiRewrite4.INI - get rid of the contents of the file and replace it with

# Ruby on RailsIterationLimit 0RewriteRule ^(/[^.]+)$ /dispatch.fcgi?$1

This takes the URL that IIS recieves and matches it against the given regular expression. I’m no grexpert but I’m reliably informed that it matches any string starting with a ‘/’ that does not contain ‘.’s. If you are setting up a web-service then this has an implication - by default Rails makes the WSDL available via a URL ending in service.wsdl. You will need to edit D:\MyApp\config\routes.rb to change this to something like service_wsdl - otherwise the URL rewriter will spot the ‘.’ and will not feed the request to Rails at all. (Of course, I haven’t got web services working with these instructions yet but I will. Oh yes, I will). Anyway, so it matches any URL starting with a ‘/’ and not containing a ‘.’ - and rewrites it to /dispatch.fcgi?$1. So /controller/action/id will be matched to /dispatch.fcgi?/controller/action/id.

Hang on - our URL is being rewritten with a .fcgi in it - ring any bells? That’s right, next up we configure FastCGI. Open RegEdit and open the Local Machine/Software key. Create a key (folder) called “FastCGI”. Under here create another key (folder) called “.fcgi” - when FastCGI is invoked with a file extension of .fcgi it will use the settings in this key. This is why, when we have multiple applications on a single server, we need to vary the file extensions (.myapp1, .myapp2 as detailed above - likewise we need to rename dispatch.fcgi to dispatch.myapp1/dispatch.myapp2 for each respective application). The basic FastCGI setttings we need (we’ll add some more later) are:

  • AppPath - set this to C:\ruby\bin\rubyw.exe
  • Args - set this to D:\MyApp\public\dispatch.fcgi
  • BindPath - set this to MyAppRailsCGI

. AppPath tells FastCGI that we want Ruby (the “windows” version that does not produce a command line output) to execute our scripts, passing it the Args (our dispatch.fcgi script) as the entry point to the application, using the Named Pipe “MyAppRailsCGI” to communicate.

Now, use the IIS Configuration thingy to restart IIS - right-click on the Server, select All Tasks and restart. This seems to take forever on Server 2003. Now open your favourite browser and point it at your application (http://myserver/controller/action/id or whatever). Now I’m betting that you get a “recognition failed for dispatch.fcgi”.

Let’s take a walk on the dark side. I’m not 100% sure what is going on here. It involves regular expressions and environment variables that I can’t access in debug mode and it all seems to happen before Rails’ logging is invoked. So this is guesswork that seems to be effective (apart from web-services, which, as I have said before, I will return to some other day). Go to D:\MyApp\vendor\actionpack-version\lib\action_controller\request.rb - this is the Ruby file that ActionPack uses to route URL requests. Under Apache and WEBrick, it returns the REQUEST_URI environment variable, and if it can’t get at it, it manipulates PATH_INFO and SCRIPT_NAME to get the same result. Under IIS it doesn’t work - what the method is expecting is a “SCRIPT_NAME” of “/dispatch.fcgi” (which is what we have) but a “PATH_INFO” of “/dispatch.fcgi/controller/action”. In other words, instead of extracting the original URL and making it into a query string, it expects the original URL to be tacked onto the end of the dispatcher script. The problem with this is that if the URL looks like that, then the URL no longer ends with .fcgi so IIS does not know to ask FastCGI to process the request. Our PATH_INFO looks more like “/dispatch.fcgi?/controller/action” - note the all important question mark in the URL. However, if we modify the request_uri method in request.rb to look like:

# Returns the request URI correctly, taking into account the idiosyncracies # of the various servers. def request_uri   if uri = env[’REQUEST_URI’]     (%r{^\w+\://[^/]+(/.*|$)$} =~ uri) ? $1 : uri # Remove domain, which webrick puts into the request_uri.   else  # REQUEST_URI is blank under IIS - get this from PATH_INFO and SCRIPT_NAME     script_filename = env[’SCRIPT_NAME’].to_s#.match(%r{[^/]+$})     uri = env[’PATH_INFO’]     uri = uri.sub(”#{script_filename}”, “”) unless script_filename.nil?     uri <<>

I’m 99% sure that this edit is what is making the web-services fall over. However, it does mean that traditional sites (that don’t use query strings) are routed correctly.

Restart IIS (again .. yawn) and try connecting once more. After a long pause (as FastCGI invokes Ruby for the first time) you should see your application. Congratulations. Have a cup of tea.

Now to reconfigure FastCGI again … reopen RegEdit and move to your .fcgi key. Add entries for StartServers (DWORD), IncrementServers (DWORD) and MaxServers (DWORD). This tells FastCGI how many copies of Ruby to start initially (I tend to use 5), how many to start at times of high load (I tend to use 3) and the maximum number of Ruby processes to have running at one time (15 if your server can handle it). I also tend to set the Timeout (DWORD) to 600 - if FastCGI needs to start extra Ruby processes it will keep them alive for ten minutes before shutting them down again. And your last one - add a BINARY key called Environment - and type in RAILS_ENV=PRODUCTION for the value. In Regedit you can directly enter the value for binaries by typing in the right hand side of the edit box - you don’t need to convert each character into Hex, like I did the first time I was confronted with this editor!

And there you have it. Your Rails application (sans web-services) should be up and running on your IIS server. It should have 5 concurrent Ruby processes dealing with incoming requests, increasing to 15 processes under load.

Hope that helps … enjoy.

Oops - almost forgot. Create a batch file (D:\MyApp\Scripts\cleanup.cmd) that contains the line del D:\Temp\Ruby_Sess*.*. Then add a scheduled task to run that batch file every night at some god-forsaken hour. This cleans up Ruby’s session files and prevents too many from being created. Of course, ideally, you would examine the last-changed-time and only delete those that hadn’t been touched in twenty minutes, or whatever, but, for my application at least, getting rid of all of yesterday’s sessions is good enough. Your mileage may vary.

Wednesday, December 7th, 2005

I actually bothered to read the Readme for FastCGI today (it is included in the source package, not in the binaries). I’ve not taken a proper look at this so I don’t know what effect it may have.

Some of the Path Info rewriting may be down to IIS impersonation:


For authentication to work properly in all instances, you MUST check the ‘Check that file exists’ checkbox, this has the unfortunate side effect of breaking path_info values.

Likewise, under your .fcgi key there are some more options to supply:


StartServers REG_DWORD 5
IncrementServers REG_DWORD 2
MaxServers REG_DWORD 25
Environment REG_BINARY
(newline deliminated, null terminated, for adding additional
environment variables ie. PHP_FCGI_MAX_REQUESTS=25)
Filter REG_DWORD 0
If set to 1, this fastcgi server will be treated as a FastCGI FILTER.
A Filter server receives the file to be filtered from the web server.
for more information, see documentation at fastcgi.com
Timeout REG_DWORD 600
How long extra servers (number above StartServers) are kept alive
before being terminated

It’s the first three that are the important ones. This allows FastCGI to start multiple RubyW processes to handle each incoming request (as each process handles a single request at a time). The Environment option is to allow arguments to be passed to the ruby processor but I’m passing them through the Args key. Which of course doesn’t work for the -e production option.

So get rid of your -e production and instead, create the Environment key (as a REG_BINARY) and put RAILS_ENV=PRODUCTION. A quick tip, using the XP version of RegEdit - editing a binary key gives you a text area with three columns - the decimal, hex and text. You cannot type in the decimal, but you can put in your hex values into the hex column. What is blatantly not obvious is that you can also type in the text section. So I wasted five minutes of my life looking up those values when I didn’t need to.

However, I’ve set the Environment key to “RAILS_ENV=production” (52 41 49 4C 53 5F 45 4E 56 3D 70 72 6F 64 75 63 74 69 6F 6E 0D 0A 00) and it makes no difference - still running in Development mode. I could just edit environment.rb I suppose.

Incidentally, the Bind-Path is the named pipe that FastCGI uses to communicate, as I suspected.

If you want more than one rails application on a single server then you add new keys (instead of .fcgi, use .myapp or something like that). You need to rename your dispatch.fcgi to match the newly chosen key, create the FastCGI mapping in IIS and set up the application and args for your new file extension.

*STOP PRESS* I take it all back. The Environment key is working fine and I was being a tit.