Writing mod_ perl Scripts

mod_ perl Scripts"-->
only for RuBoard - do not distribute or recompile

Writing mod_ perl Scripts

In general, writing CGI scripts to run under mod_perl doesn t differ much from writing them for execution under a standalone Perl process. Therefore, if you create a standalone script in the cgi-bin directory, you often can expect that moving it to the cgi-perl directory won t cause problems, the script will just run faster. The perl-test.pl script we used earlier to test the mod_perl configuration was an example of this: It functioned properly whether run from cgi-bin or from cgi-perl. You can try this with other scripts as well. For example, you can move the scripts developed in Chapter 2 from cgi-bin to cgi-perl to see whether they work properly.

That s not to say that there are never any problems using CGI scripts under mod_perl. This section describes things to guard against so your scripts don t cause problems for themselves, other scripts, or your Web server. It discusses the issues you should be aware of for the applications in this book. You might trip over others in your own scripts, however; so for additional information, check the mod_perl_to_cgi and mod_perl _traps documents listed in Appendix B.

Script-Writing Shortcuts

When you write scripts for mod_perl, you can use certain shortcuts as compared to writing them for standalone execution:

  • A mod_perl script must be executable, just like its standalone counterpart, but you don t need to include the initial #! line that specifies the pathname to the Perl interpreter.

  • For any directory added to the Perl search path with a use lib statement in the startup file, you don t need to add it in any of your scripts.

Of course, if you take advantage of these shortcuts, you ll need to add the #! and use lib lines back in if you decide later to use your scripts as standalone CGI programs (for example, to use them on a host that supports only that execution mode). In this book, scripts written for mod_perl will begin with the #! line and will include any necessary use lib line, even though they don t strictly need them. That way you ll more easily be able to use them even if you don t install mod_perl, by moving them to the cgi-bin directory instead.

Diagnostic Output Generation

It s often useful to tell Perl to generate error messages that help you determine that your scripts have problems and what to do about it. You may find the following techniques useful for getting diagnostic information and debugging your scripts:

  • Use the -w option on the #! line at the beginning of your scripts to tell Perl to emit warnings for questionable constructs:

     #! /usr/bin/perl -w 

    mod_perl doesn t use the pathname, but it will notice the -w option and turn on warning mode.

  • Include a use diagnostics line to tell Perl to print suggestions about the causes of problems:

     use diagnostics; 
  • Install the Apache::DBdebugger module and preload it in the mod_perl startup file. This module isn t included with Apache or mod_perl by default, but you can get it from http://cpan.perl.org/.

Output resulting from these techniques will go to the Apache error log, so you ll need to look there for diagnostic messages. Naturally, you should try to write your scripts to eliminate warnings if possible. If you use the -w option on the #! line, the error log can become useless if you have so many warnings being produced that it becomes difficult to tell what s important and what isn t. Try to modify your scripts to make the warnings go away.

Script Environment Contamination

With a standalone script, the environment provided by the external Perl process that executes the script goes away when the script terminates. The processes are independent and don t affect each other. With mod_perl, this is not true, because a given httpd process can run several scripts over the course of its lifetime, and there is state information in the Perl interpreter that persists from request to request. This is essential behavior for implementing some kinds of services such as persistent database connections, but it can lead to problems as well. If you re sloppy in your programming, one script can pollute the environment for subsequent scripts. Here s a simple example:

 #! /usr/bin/perl -w  print "Content-Type: text/html\n\n";  print $x++, "\n"; 

Put this script in your cgi-bin directory as increment.pl, and then request it several times in quick succession. You ll see the value 0 in your browser window each time. Then move it to cgi-perl and request it from there several more times. Now you ll see a series of numbers that is sort of random but generally increasing. (The order depends on the order in which the httpd children are selected to process your requests.) The reason this occurs is that $x is a global variable but is never initialized. The first time any given child executes increment.pl, the value of $x is 0. The next time, the script inherits the previous value and increments that.

Don t use variables as global variables without declaring them as such or without initializing them first. The increment.pl script doesn t follow this principle, so it needs some modification to be a better citizen. Fortunately, that s easy to do. Just declare $x to be global explicitly with use vars, and then initialize it:

 #! /usr/bin/perl -w  use strict;  use vars qw($x);  $x = 0;  print "Content-Type: text/html\n\n";  print $x++, "\n"; 

The usestrict line isn t actually required to make the script yield consistent results (0 each time it s invoked); it s just good programming practice to use it.

When you initialize a variable, make sure it s initialized every time your script executes. The following bit of code sets $x to 1, but only if some_test() succeeds:

 use vars qw($x);  $x = 1 if some_test (); 

The problem is that $x remains set to 1 even if some_test() fails on every subsequent invocation of the script. Suppose what some_test() does is check a user-supplied password and return true if the password is okay. After $x gets set, it remains set, even if the next person to come along provides an incorrect password! The following code handles the situation properly:

 use vars qw($x);  $x = 0;  $x = 1 if some_test (); 

So does this:

 use vars qw($x);  $x = some_test () ? 1 : 0; 

The basic principle here is that you don t want to start making decisions based on variable values until you know they ve been initialized properly.

When you re trying to determine the cause of problems due to shared script environments, you may find it useful to stop Apache and restart it using httpd -X. The -X option tells Apache to run as a single process rather than in the usual parent-children configuration. That makes shared-environment problems show up more quickly. (You should do this only on a development server, not a production server.)

Variable Scope Effects

mod_perl runs scripts by wrapping them inside a function (one reason for this is that it can assign each script its own unique namespace). This can cause problems due to variable scope. Here is a simple program that illustrates the effect:

 #! /usr/bin/perl -w  print "Content-Type: text/html\n\n";  my $x = 0;  f ();  exit (0);  sub f  {      print $x++, "\n";  } 

If you request this script several times from your browser, the script doesn t print 0 each time as you would expect. Instead, the values increase. This occurs even though the variable $x is explicitly initialized to 0. A clue that something is wrong here will be found in the Apache error log:

 Variable "$x" will not stay shared at line 5. 

(The line number is off due to the script being executed inside the wrapper function.) The difficulty here is that when the script is run inside a wrapper by mod_perl, your entire script becomes a single function, and any functions in the script become inner subroutines. That means f() is an inner subroutine that references a lexically scoped my() variable belonging to its parent subroutine and that isn t passed to it as an argument. As a result, the inner subroutine sees $x with the correct value the first time the script runs. After that, the variable becomes unshared and the inner subroutine continues to use its own unshared value of $x on subsequent invocations. This issue is discussed in more detail in the mod_perl Guide, along with various solutions to the problem. One way to avoid the difficulty is to change the declaration of $x to be global:

 #! /usr/bin/perl -w  print "Content-Type: text/html\n\n";  use vars qw($x);  $x = 0;  f ();  exit (0);  sub f  {      print $x++, "\n";  } 

You can declare a variable using my if you want to, as long as you pass it as an argument to any subroutine that needs it, instead of accessing it directly from the subroutine as a global variable. (That s actually the way I prefer to write scripts, which is why you won t see many instances of use vars in this book.) If you want to modify the variable inside the subroutine, pass it by reference:

 #! /usr/bin/perl -w  print "Content-type: text/html\n\n";  my $x = 0;  f (\$x);  exit (0);  sub f  { my $x_ref = shift;       print ++${$x_ref}, "\n";  } 

Code Caching Effects

Recall that mod_perl caches compiled scripts. This helps it run scripts faster, but what happens if you change a script? Does mod_perl continue to execute the cached version? Nope. Apache::Registry keeps track of the scripts that it has run and checks the modification date of the original file when a script is requested again. If the date has changed, it recompiles the script and the new version is used instead. You can verify this for yourself. Request a script, and then change it and click the Reload button in your browser. You should see the changed output. Then change the script back and click Reload again.You should see the original output. That s what you expect and want to happen.[2]

[2] If you re watching the Apache error log while you make changes to a script, you ll probably notice messages that say subroutine xxx redefined, where xxxis some function in the script. You can make these go away by restarting Apache.

However, this behavior doesn t apply to modules pulled into your script via use or require. If you change those files, the changes won t be noticed until you restart the server. Another workaround for this problem is to use the Apache::StatINC module, which forces Apache to check the last modification time even for modules referenced from use or require statements. This is a technique best used on a development server, because it slows down Apache. Run perldoc Apache::StatINC from the command line for more information.

Script caching also is responsible for another mysterious problem. If you use or require a library file, that file s code is pulled in to your script, compiled, and cached, as usual. If the file doesn t contain a package declaration to specify a namespace, however, the code goes into your script s own namespace. This is main when you run scripts in standalone mode, but scripts run in their own unique namespace under mod_perl. If your script is called script.pl, for example, the namespace might be &Apache::ROOT::cgi_2dperl::script_2epl. Normally, having unique namespaces per script is a good thing, because it helps keep scripts that are run under a given httpd child from colliding with each other in the main namespace. But it causes a problem for unpackaged library code. Here s why: Suppose you run your script script.pl that uses a library file MyLib.pm containing a function lib_func(). script.pl will execute properly. Now suppose you have a second script, script2.pl, that wants to use MyLib.pm, too. When the second script executes, mod_perl sees the use or require line for the library file, notices that the file has already been processed and cached, and doesn t bother to recompile it. Then when script2.pl calls lib_func() from the library file, an error occurs:

 [error] Undefined subroutine  &Apache::ROOT::cgi_2dperl::script2_2epl::lib_func called 

This happens because functions in the library file have been compiled, but they re in the namespace for script.pl, not script2.pl. To fix this problem, make sure the library file includes a package declaration, and then invoke its functions using the package identifier. MyLib.pm can be written like this:

 package MyLib;  sub lib_func  {     ...  }  ... 

After making that change, your scripts should invoke MyLib::lib_func() rather than lib_func().

Persistent Database Connections

Normally, scripts that use MySQL open a connection to the MySQL server, access the database, and close the connection. Such connections are non-persistent. You can use persistent database connections instead if you want to share connections among database scripts and minimize connection setup overhead. However, you don t actually make any changes to your scripts to do this. Instead, preload the Apache::DBImodule from your mod_perl startup file:

 use Apache::DBI (); 

Alternatively, use a PerlModule directive in httpd.conf :

 PerlModule Apache::DBI 

(In either case, if you preload both Apache::DBI and DBI, you should load Apache::DBI first.) After you restart Apache to make the change take effect, each child httpd process will manage a pool of open connections to the MySQL server. This happens transparently to your scripts. DBI s disconnect() method is overridden to become a no-op, and the connect() method is overridden with one that checks whether the database you re connecting to is already open. If so, the connection is reused. For more information, run perldoc Apache::DBI from the command line.

Running Scripts with Special Privileges

You can invoke a standalone Perl script under Apache s suEXEC mechanism to run them under a particular user ID if the script needs higher security or greater privileges. This isn t possible with mod_perl scripts because they run within Apache, and Apache can t change its own user ID (unless you run it as root, which is a huge security risk). A workaround for this in some cases is to run a helper application using suEXEC for that part of your script s task that requires special privileges. Or, if your script doesn t actually require mod_perl, put it in the cgi-bin directory and launch it with suEXEC as a standalone script.

You should now be able to install mod_perl if you want to. And by bearing in mind the discussion just presented concerning mod_perl -related issues to watch out for, you should be able to write scripts that run properly whether or not they run under mod_perl. Of course, none of the programs shown in this chapter really do much of anything; they are intended only to illustrate various aspects of mod_perl s behavior. In the next chapter we ll discuss the design of form-based scripts, an extremely common type of Web application that enables you to accomplish real work.

only for RuBoard - do not distribute or recompile


MySQL and Perl for the Web
MySQL and Perl for the Web
ISBN: 0735710546
EAN: 2147483647
Year: 2005
Pages: 77
Authors: Paul DuBois

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net