SpeedyCGI - Speed up perl scripts by running them persistently.
#!/usr/bin/speedy
### Your Script Here. For example: print "Content-type: text/html\n\nHello World!\n";
## ## Optionally, use the CGI::SpeedyCGI module for various things ##
# Create a SpeedyCGI object use CGI::SpeedyCGI; my $sp = CGI::SpeedyCGI->new;
# See if we are running under SpeedyCGI or not. print "Running under speedy=", $sp->i_am_speedy ? 'yes' : 'no', "\n";
# Register a shutdown handler $sp->add_shutdown_handler(sub { do something here });
# Register a cleanup handler $sp->register_cleanup(sub { do something here });
# Set/get some SpeedyCGI options $sp->setopt('timeout', 30); print "maxruns=", $sp->getopt('maxruns'), "\n";
SpeedyCGI is a way to run perl scripts persistently, which can make them run much more quickly. A script can be made to to run persistently by changing the interpreter line at the top of the script from:
#!/usr/bin/perl
to
#!/usr/bin/speedy
After the script is initially run, instead of exiting, the perl interpreter is kept running. During subsequent runs, this interpreter is used to handle new executions instead of starting a new perl interpreter each time. A very fast frontend program, written in C, is executed for each request. This fast frontend then contacts the persistent Perl process, which is usually already running, to do the work and return the results.
By default each perl script runs in its own Unix process, so one perl script can't interfere with another. Command line options can also be used to deal with programs that have memory leaks or other problems that might keep them from otherwise running persistently.
SpeedyCGI can be used to speed up perl CGI scripts. It conforms to the CGI specification, and does not run perl code inside the web server. Since the perl interpreter runs outside the web server, it can't cause problems for the web server itself.
SpeedyCGI also provides an Apache module so that under the Apache web server, scripts can be run without the overhead of doing a fork/exec for each request. With this module a small amount of frontend code is run within the web server - the perl interpreters still run outside the server.
SpeedyCGI and PersistentPerl are currently both names for the same code. SpeedyCGI was the original name, but because people weren't sure what it did, the name PersistentPerl was picked as an alias. At some point SpeedyCGI will be replaced by PersistentPerl, or become a sub-class of PersistentPerl to avoid always having two distributions.
SpeedyCGI options can be set in several ways:
For example the line:
#!/usr/bin/speedy -w -- -t300
at the top of your script will set the perl option
``-w
'' and will pass the ``-t
'' option to SpeedyCGI, setting the
Timeout value to 300 seconds.
Note that these variables are global. There is currently no way to run different scripts with different SpeedyCGI options when they are run from the Apache module. Any <Directory> or <Location> contexts have no effect on the scope of the SpeedyCGI options. When the same SpeedyCGI option is set several times, the last one overrides the others.
Not all options below are available in all contexts. The context for which each option is valid is listed on the ``Context'' line in the section below. There are three contexts:
Command Line : -p<string> Default Value : "/usr/bin/speedy_backend" Context : mod_speedycgi, speedy
Description:
Path to the speedy backend program.
Command Line : -B<number> Default Value : 131072 Context : speedy
Description:
Use <number> bytes as the maximum size for the buffer that receives data from the perl backend.
Command Line : -b<number> Default Value : 131072 Context : speedy
Description:
Use <number> bytes as the maximum size for the buffer that sends data to the perl backend.
Command Line : -g<string> Default Value : "none" Context : mod_speedycgi, speedy
Description:
Allow a single perl interpreter to run multiple scripts. All scripts that are run with the same group name and by the same user will be run by the same group of perl interpreters. If the group name is "none" then grouping is disabled and each interpreter will run one script. Different group names allow scripts to be separated into different groups. Name is case-sensitive, and only the first 12-characters are significant. Specifying an empty group name is the same as specifying the group name "default" - this allows just specifying "-g" on the command line to turn on grouping.
Command Line : -M<number> Default Value : 0 (no max) Context : mod_speedycgi, speedy
Description:
If non-zero, limits the number of speedy backends running for this perl script to <number>.
Command Line : -r<number> Default Value : 500 Context : mod_speedycgi, module, speedy
Description:
Once the perl interpreter has run <number> times, re-exec the backend process. Zero indicates no maximum. This option is useful for processes that tend to consume resources over time.
Command Line : N/A Default Value : "" Context : mod_speedycgi
Description:
Command-line options to pass to the perl interpreter.
Command Line : -t<number> Default Value : 3600 (one hour) Context : mod_speedycgi, module, speedy
Description:
If no new requests have been received after <number> seconds, exit the persistent perl interpreter. Zero indicates no timeout.
Command Line : -T<string> Default Value : "/tmp/speedy" Context : mod_speedycgi, speedy
Description:
Use the given prefix for creating temporary files. This must be a filename prefix, not a directory name.
Command Line : -v Context : speedy
Description:
Print the SpeedyCGI version and exit.
The following methods are available in the CGI::SpeedyCGI module.
my $sp = CGI::SpeedyCGI->new;
register_cleanup($function_ref)
$sp->register_cleanup(\&cleanup_func);
add_shutdown_handler($function_ref)
$sp->add_shutdown_handler(sub {$dbh->logout});
set_shutdown_handler($function_ref)
add_shutdown_handler
, but only allows for a single
function to be registered.
$sp->set_shutdown_handler(sub {$dbh->logout});
$sp->i_am_speedy;
To make your script as portable as possible, you can use the following test to make sure both the SpeedyCGI module is available and you are running under SpeedyCGI:
if (eval {require CGI::SpeedyCGI} && CGI::SpeedyCGI->i_am_speedy) { Do something SpeedyCGI specific here...
To increase the speed of this check you can also test whether the following variable is defined instead of going through the object interface:
$CGI::SpeedyCGI::i_am_speedy
$sp->setopt('TIMEOUT', 300);
getopt($optname)
$sp->getopt('TIMEOUT');
$sp->shutdown_now
$sp->shutdown_next_time
To install SpeedyCGI you will need to either download a binary package for your OS, or compile SpeedyCGI from source code. See DOWNLOADING for information on where to obtain the source code and binaries.
Once you have downloaded the binary package for your OS, you'll need to install it using the normal package tools for your OS. The commands to do that are:
rpm -i <filename>
gunzip <filename>.gz pkgadd -d <filename>
pkg_add <filename>
If you are also installing the apache module you will have to configure Apache as documented in Apache Configuration.
To compile SpeedyCGI you will need perl 5.005_03 or later, and a C compiler, preferably the same one that your perl distribution was compiled with. SpeedyCGI is known to work under Solaris, Redhat Linux, FreeBSD and OpenBSD. There may be problems with other OSes or earlier versions of Perl. SpeedyCGI may not work with threaded perl -- as of release 2.10, Linux and Solaris seem to work OK with threaded perl, but FreeBSD does not.
To do a standard install from source code, execute the following:
perl Makefile.PL make make test make install
This will install the speedy and speedy_backend binaries in the same directory where perl was installed, and the SpeedyCGI.pm module in the standard perl lib directory. It will also attempt to install the mod_speedycgi module if you have the command apxs in your path.
If you don't have permission to install into the standard perl directory, or if you want to install elsewhere, the easiest way is to compile and install your own copy of perl in another location, then use your new version of perl when you run ``perl Makefile.PL''. The SpeedyCGI binaries and module will then be installed in the same location as the new version of perl.
If you can't install your own perl, you can take the following steps:
SpeedyCGI has limited support for running setuid - installing this way may compromise the security of your system. To install setuid do the following:
This has been know to work in Linux and FreeBSD. Solaris will work as long as the Group option is set to ``none''.
To compile the optional apache mod_speedycgi module you must have the apxs command in your path. Redhat includes this command with the ``apache-devel'' RPM, though it may not work properly for installation.
If the apache installation fails:
LoadModule speedycgi_module modules/mod_speedycgi.so
If you are using Apache-1, also add:
AddModule mod_speedycgi.c
Once mod_speedycgi is installed, it has to be configured to be used for your perl scripts. There are two methods.
Warning! The instructions below may compromise the security of your web site. The security risks associated with SpeedyCGI are similar to those of regular CGI. If you don't understand the security implications of the changes below then don't make them.
Alias /speedy/ /home/httpd/cgi-bin/ <Location /speedy> SetHandler speedycgi-script Options ExecCGI allow from all </Location>
AddHandler speedycgi-script .speedy <Location /> Options ExecCGI </Location>
Starting in version 1.8.3 an option was added to limit the number of perl backends running. See MaxBackends in Options Available above.
%ENV
and @ARGV
are the only globals changed between requests.
Globals retain their values between runs, which can be good for keeping persistent database handles for example, or bad if your code assumes they're undefined.
Also, if you create global variables with ``my'', you shouldn't try to reference those variables from within a subroutine - you should pass them into the subroutine instead. Or better yet just declare global variables with ``use vars'' instead of ``my'' to avoid the problem altogether.
Here's a good explanation of the problem - it's for mod_perl, but the same thing applies to speedycgi:
http://perl.apache.org/docs/general/perl_reference/perl_reference.html#my___Scoped_Variable_in_Nested_Subroutines
If all else fails you can disable persistence by setting MaxRuns to 1. The only benefit of this over normal perl is that speedy will pre-compile your script.
For example, if your code has an ``open_db_connection'' subroutine that returns a database connection handle, you can use the code below to keep a persistent connection:
use vars qw($dbh); unless (defined($dbh)) { $dbh = &open_db_connection; }
This code will store a persistent database connection handle in the global variable ``$dbh'' and only initialize it the first time the code is run. During subsequent runs, the existing connection is re-used.
You may also want to check the connection each time before using it, in case it is not working for some reason. So, assuming you have a subroutine named ``db_connection_ok'' that returns true if the db connection is working, you can use code like this:
use vars qw($dbh); unless (defined($dbh) && &db_connection_ok($dbh)) { $dbh = &open_db_connection; }
use Fcntl; fcntl(STDOUT, F_SETFD, FD_CLOEXEC);
This will set the close-on-exec flag on standard out so it is closed when oracle is exec'ed.
The group feature in SpeedyCGI can be used to help reduce the amount of memory used by the perl interpreters. By default groups are not used (group name is ``none''), and each perl script is given its own set of perl interpreters. Each perl interpreter is also a separate system process.
When grouping is used, perl interpreters and perl scripts are put in a group. All perl interpreters in a group can run perl scripts in the same group. What this means is that by putting all your scripts into one group, there could be one perl interpreter running all the perl scripts on your system. This can greatly reduce your memory needs when running lots of different perl scripts.
SpeedyCGI group names are entities unto themselves. They are not associated with Unix groups, or with the Group directive in Apache. Expect for the two special group names ``none'' and ``default'', all group names are created by the user of SpeedyCGI using the Group option described in OPTIONS
If you want the maximum amount of grouping possible then you should run all scripts with the group option set to ``default''. This the group name used if you just specify ``-g'' on the command line without an explicit group name. When you do this, you will get the fewest number of perl interpreters possible - any perl interpreter will be able to run any of your perl scripts.
Although using group ``default'' for all scripts results in the most efficient use of resources, it's not always possible or desirable to do this. You may want to use other group names for the following reasons:
In other cases, scripts may make changes to included packages, etc, that may break other scripts running in the same interpreter. In this case such scripts can be given their own group name (like ``pariah'') to keep them away from scripts they are incompatible with. The rest of your scripts can then run out of group ``default''. This will ensure that the ``pariah'' scripts won't run within the same interpreter as the other scripts.
For example, you may have an email application that contains ten perl scripts, and since the common perl code used in this application has a bad memory leak, you want to use a MaxRuns setting of 5 for all of these scripts. You want to run all your other scripts with a normal MaxRuns setting. To accomplish this you can edit the ten email application scripts, and at the top use the line:
#!/usr/bin/speedy -- -gmail -r5
In the rest of your perl scripts you can use:
#!/usr/bin/speedy -- -g
What this will do is put the ten email scripts into a group of their own (named ``mail'') and give them all the default MaxRuns value of 5. All other scripts will be put into the group named ``default'', and this group will have a normal MaxRuns setting.
Binaries for many OSes can be found at:
http://daemoninc.com/SpeedyCGI/download.html
The standard source code distribution can be retrieved from any CPAN mirror or from:
http://daemoninc.com/SpeedyCGI/download.html http://www.cpan.org/modules/by-authors/id/H/HO/HORROCKS/
The latest development code can be obtained from the SourceForge CVS repository using the following commands:
cvs -d:pserver:anonymous@cvs.SpeedyCGI.sourceforge.net:/cvsroot/speedycgi login cvs -z3 -d:pserver:anonymous@cvs.SpeedyCGI.sourceforge.net:/cvsroot/speedycgi co 2.x
Press Enter when prompted for a password.
Sam Horrocks http://daemoninc.com sam@daemoninc.com
A lot of people have helped out with code, patches, ideas, resources, etc. I'm sure I'm missing someone here - if so, please drop me an email.
perl(1), httpd(8), apxs(8).
http://daemoninc.com/SpeedyCGI/
Please report any bugs or requests for changes to the mailing list.
The current bugs / todo list can be found at http://www.sourceforge.net/projects/speedycgi/. Go to the Bug Tracking menu and select the group ``bug'' for bugs, or the group ``rfe'' for the todo list.
http://member.nifty.ne.jp/hippo2000/perltips/CGI/SpeedyCGI.htm
http://daemoninc.com/SpeedyCGI/benchmarks/
http://daemoninc.com/SpeedyCGI/success_stories/
http://daemoninc.com/SpeedyCGI/CGI-SpeedyCGI/Changes
I gave an Introduction to SpeedyCGI talk at YAPC 2001. It can be found at http://daemoninc.com/SpeedyCGI/yapc_2001/
Copyright (C) 2003 Sam Horrocks
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; either version 2 of the License, or (at your option) any later version.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
This product includes software developed by the Apache Software Foundation (http://www.apache.org/).