=head1 NAME

Writing mod_perl Handlers and Scripts

=head1 Description

This chapter covers the mod_perl coding specifics, different from
normal Perl coding. Most other perl coding issues are covered in the
perl manpages and rich literature.

=head1 Prerequisites

=head1 Where the Methods Live

mod_perl 2.0 has all its methods spread across many modules. In order
to use these methods the modules containing them have to be loaded
first. If you don't do that mod_perl will complain that it can't find
the methods in question. The module
C<L<ModPerl::MethodLookup|docs::2.0::api::ModPerl::MethodLookup>> can
be used to find out which modules need to be used.

=head1 Goodies Toolkit

=head2 Environment Variables

mod_perl sets the following environment variables:

=over

=item * 

C<$ENV{MOD_PERL}> - is set to the mod_perl version the server is
running under. e.g.:

  mod_perl/1.99_03-dev

If C<$ENV{MOD_PERL}> doesn't exist, most likely you are not running
under mod_perl.

  die "I refuse to work without mod_perl!" unless exists $ENV{MOD_PERL};

However to check which version is used it's better to use the
following technique:

  use mod_perl;
  use constant MP2 => ($mod_perl::VERSION >= 1.99);
  # die "I want mod_perl 2.0!" unless MP2;

=item *

C<$ENV{GATEWAY_INTERFACE}> - is set to C<CGI-Perl/1.1> for
compatibility with mod_perl 1.0. This variable is deprecated in
mod_perl 2.0. Use C<$ENV{MOD_PERL}> instead.

=back

mod_perl passes (exports) the following shell environment variables
(if they are set) :

=over

=item * 

C<PATH> - Executables search path.

=item * 

C<TZ> - Time Zone.

=back

Any of these environment variables can be accessed via C<%ENV>.

=head2 Threaded MPM or not?

If the code needs to behave differently depending on whether it's
running under one of the threaded MPMs, or not, the class method
C<Apache::MPM-E<gt>is_threaded> can be used. For example:

  use Apache::MPM ();
  if (Apache::MPM->is_threaded) {
      require APR::OS;
      my $tid = APR::OS::thread_current();
      print "current thread id: $tid (pid: $$)";
  }
  else {
      print "current process id: $$";
  }

This code prints the current thread id if running under a threaded
MPM, otherwise it prints the process id.

=head2 Writing MPM-specific Code

If you write a CPAN module it's a bad idea to write code that won't
run under all MPMs, and developers should strive to write a code that
works with all mpms. However it's perfectly fine to perform different
things under different mpms.

If you don't develop CPAN modules, it's perfectly fine to develop your
project to be run under a specific MPM.

  use Apache::MPM ();
  my $mpm = lc Apache::MPM->show;
  if ($mpm eq 'prefork') {
      # prefork-specific code
  }
  elsif ($mpm eq 'worker') {
      # worker-specific code
  }
  elsif ($mpm eq 'winnt') {
      # winnt-specific code
  }
  else {
      # others...
  }


=head1 Code Developing Nuances

=head2 Auto-Reloading Modified Modules with Apache::Reload

META: need to port Apache::Reload notes from the guide here. but the
gist is:

  PerlModule Apache::Reload
  PerlInitHandler Apache::Reload
  #PerlPreConnectionHandler Apache::Reload
  PerlSetVar ReloadAll Off
  PerlSetVar ReloadModules "ModPerl::* Apache::*"

Use:

  PerlInitHandler Apache::Reload

if you need to debug HTTP protocol handlers. Use:

  PerlPreConnectionHandler Apache::Reload

for any handlers.

Though notice that we have started to practice the following style in
our modules:

  package Apache::Whatever;
  
  use strict;
  use warnings FATAL => 'all';

C<FATAL =E<gt> 'all'> escalates all warnings into fatal errors. So
when C<Apache::Whatever> is modified and reloaded by C<Apache::Reload>
the request is aborted. Therefore if you follow this very healthy
style and want to use C<Apache::Reload>, flex the strictness by
changing it to:

  use warnings FATAL => 'all';
  no warnings 'redefine';

but you probably still want to get the I<redefine> warnings, but
downgrade them to be non-fatal. The following will do the trick:

  use warnings FATAL => 'all';
  no warnings 'redefine';
  use warnings 'redefine';

Perl 5.8.0 allows to do all this in one line:

  use warnings FATAL => 'all', NONFATAL => 'redefine';

but if your code may be used with older perl versions, you probably
don't want to use this new functionality.

Refer to the I<perllexwarn> manpage for more information.

=head1 Integration with Apache Issues

In the following sections we discuss the specifics of Apache behavior
relevant to mod_perl developers.

=head2 Sending HTTP Response Headers

Apache 2.0 doesn't provide a method to force HTTP response headers
sending (what used to be done by C<send_http_header()> in Apache
1.3). HTTP response headers are sent as soon as the first bits of the
response body are seen by the special core output filter that
generates these headers. When the response handler send the first
chunks of body it may be cached by the mod_perl internal buffer or
even by some of the output filters. The response handler needs to
flush in order to tell all the components participating in the sending
of the response to pass the data out.

For example if the handler needs to perform a relatively long-running
operation (e.g. a slow db lookup) and the client may timeout if it
receives nothing right away, you may want to start the handler by
setting the I<Content-Type> header, following by an immediate flush:

  sub handler {
      my $r = shift;
      $r->content_type('text/html');
      $r->rflush; # send the headers out
  
      $r->print(long_operation());
      return Apache::OK;
  }

If this doesn't work, check whether you have configured any
third-party output filters for the resource in question. Improperly
written filter may ignore the orders to flush the data.

META: add a link to the notes on how to write well-behaved filters
at handlers/filters

=head2 Sending HTTP Response Body

In mod_perl 2.0 a response body can be sent only during the response
phase. Any attempts to do that in the earlier phases will fail with an
appropriate explanation logged into the I<error_log> file.

This happens due to the Apache 2.0 HTTP architecture specifics. One of
the issues is that the HTTP response filters are not setup before the
response phase.

=head1 Perl Specifics in the mod_perl Environment

In the following sections we discuss the specifics of Perl behavior
under mod_perl.

=head2 Request-localized Globals

mod_perl 2.0 provides two types of C<SetHandler> handlers:
C<L<modperl|docs::2.0::user::config::config/C_modperl_>> and
C<L<perl-script|docs::2.0::user::config::config/C_perl_script_>>.
Remember that the C<SetHandler> directive is only relevant for the
response phase handlers, it neither needed nor affects non-response
phases.

Under the handler:

  SetHandler perl-script

several special global Perl variables are saved before the handler is
called and restored afterwards. This includes: C<%ENV>, C<@INC>,
C<$/>, C<STDOUT>'s C<$|> and C<END> blocks array (C<PL_endav>).

Under:

  SetHandler modperl

nothing is restored, so you should be especially careful to remember
localize all special Perl variables so the local changes won't affect
other handlers.

=head2 exit()

In the normal Perl code exit() is used to stop the program flow and
exit the Perl interpreter. However under mod_perl we only want the
stop the program flow without killing the Perl interpreter.

You should take no action if your code includes exit() calls and it's
OK to continue using them. mod_perl worries to override the exit()
function with its own version which stops the program flow, and
performs all the necessary cleanups, but doesn't kill the server. This
is done by overriding:

  *CORE::GLOBAL::exit = \&ModPerl::Util::exit;

so if you mess up with C<*CORE::GLOBAL::exit> yourself you better know
what you are doing.

You can still call C<CORE::exit> to kill the interpreter, again if you
know what you are doing.


=head1 Threads Coding Issues Under mod_perl

The following sections discuss threading issues when running mod_perl
under a threaded MPM.

=head2 Thread-environment Issues

The "only" thing you have to worry about your code is that it's
thread-safe and that you don't use functions that affect all threads
in the same process.

Perl 5.8.0 itself is thread-safe. That means that operations like
C<push()>, C<map()>, C<chomp()>, C<=>, C</>, C<+=>, etc. are
thread-safe. Operations that involve system calls, may or may not be
thread-safe. It all depends on whether the underlying C libraries used
by the perl functions are thread-safe.

For example the function C<localtime()> is not thread-safe when the
implementation of C<asctime(3)> is not thread-safe. Other usually
problematic functions include C<readdir()>, C<srand()>, etc.

Another important issue that shouldn't be missed is what some people
refer to as I<thread-locality>. Certain functions executed in a single
thread affect the whole process and therefore all other threads
running inside that process. For example if you C<chdir()> in one
thread, all other thread now see the current working directory of that
thread that C<chdir()>'ed to that directory. Other functions with
similar effects include C<umask()>, C<chroot()>, etc. Currently there
is no cure for this problem. You have to find these functions in your
code and replace them with alternative solutions which don't incur
this problem.

For more information refer to the I<perlthrtut>
(I<http://perldoc.com/perl5.8.0/pod/perlthrtut.html>) manpage.


=head2 Deploying Threads

This is actually quite unrelated to mod_perl 2.0. You don't have to
know much about Perl threads, other than L<Thread-environment
Issues|/Thread_environment_Issues>, to have your code properly work 
under threaded MPM mod_perl.

If you want to spawn your own threads, first of all study how the new
ithreads Perl model works, by reading the I<perlthrtut>, I<threads>
(I<http://search.cpan.org/search?query=threads>) and
I<threads::shared>
(I<http://search.cpan.org/search?query=threads%3A%3Ashared>) manpages.

Artur Bergman wrote an article which explains how to port pure Perl
modules to work properly with Perl ithreads. Issues with C<chdir()>
and other functions that rely on shared process' datastructures are
discussed.  I<http://www.perl.com/lpt/a/2002/06/11/threads.html>.


=head2 Shared Variables

Global variables are only global to the interpreter in which they are
created. Other interpreters from other threads can't access that
variable. Though it's possible to make existing variables shared
between several threads running in the same process by using the
function C<threads::shared::share()>. New variables can be shared by
using the I<shared> attribute when creating them. This feature is
documented in the I<threads::shared>
(I<http://search.cpan.org/search?query=threads%3A%3Ashared>) manpage.

=head1 Maintainers

Maintainer is the person(s) you should contact with updates,
corrections and patches.

=over

=item *

=back


=head1 Authors

=over

=item *

=back

Only the major authors are listed above. For contributors see the
Changes file.



=cut
