FastCGI For Neko On Share Hosting

In my previous post, I described you could setup neko web services on a shared host, using CGI. This method is not as efficient as it might be because a separate process is required for each request. However it is possible to extend this to “Fast CGI” (FGCI), which starts a single process, and keeps it alive. Apache talks to this over a socket, sending requests and receiving data and a very efficient manner.

If you got CGI working, and your server supports FCGI, then the transition on pretty simple.

The first thing to do is to download the new “fastcgi” haxelib. From a shell use:

haxelib install fastcgi

If haxelib asks you for a project directory, the following discussion assumes you specify your “haxeneko/lib” directory.
There is one bit of housekeeping you should do at this time – copy the “nekoapi.dso” object from “~/haxeneko/lib/fastcgi/0,1/ndll/Linux” into your “~/haxeneko” directory. This ensures that this dso will be found when neko is run by the web server.

Now it is time to change the cgi script. The code is very similar, except the extension should be “.fcgi”. Here is the script I used Site.fcgi:

#!/bin/sh
export HAXENEKO=~/haxeneko
export LD\_LIBRARY\_PATH=$HAXENEKO
export PATH=$PATH:$HAXENEKO
export NEKOPATH=$HAXENEKO
export HAXE\_LIBRARY\_PATH=$HAXENEKO/std
cd ../../site
exec neko SiteFCGI.n

Note the final “exec” call to ensure the pipes are all correctly plumbed.
And the obvious change to the .htaccess file (.fcgi extension):

RewriteEngine on
RewriteRule \\.(css|jpe?g|gif|png)$ - [L]
RewriteRule ^(.*)?$ cgi-bin/Site.fcgi [L]

Finally, compile the “Test.hx” file that came with the fastcgi lib. I have a slightly altered version here:

class Test
{
   static var processed = 0;
   static public function main()
   {
      // Called in single threaded mode...
      fastcgi.Request.init("");
      // This can be called multi-threaded...
      var req = new fastcgi.Request();
      while( req.nextRequest() )
      {
         req.write( "Content-type: text/html\r\n" +
            "\r\n" +
            "<title>Neko FastCGI<title/>" +
            "<h1>Fast CGI</h1> Requests processed here: " + (processed++) );
         req.write( "\n page = " + req.getParam("REQUEST\_URI") );
         req.close();
      }
   }
}

This version prints the request uri too. To compile, use:

haxe -main Test -neko SiteFCGI.n -lib fastcgi

And that should be that! When you visit your web page, you should see the “processed” counter increase, verifying that it is the same process that is running.

Currently the system does not support easily killing the FCGI process, which is something that you must do when you update the “.n” neko file. The only way at the moment is to use the shell to do “ps -x” to identify the process number, and then “kill -9 number”, where number is the process number of the neko executable.