=head1 NAME

Server Life Cycle Handlers

=head1 Description

This chapter discusses server life cycle and the mod_perl handlers
participating in it.









=head1 Server Life Cycle

The following diagram depicts the Apache 2.0 server life cycle and
highlights which handlers are available to mod_perl 2.0:

=for html
<img src="server_life_cycle.gif" width="561" height="537" 
 align="middle" alt="server life cycle"><br><br>

Apache 2.0 starts by parsing the configuration file.  After the
configuration file is parsed, the C<PerlOpenLogsHandler> handlers are
executed if any. After that it's a turn of C<PerlPostConfigHandler>
handlers to be run. When the I<post_config> phase is finished the
server immediately restarts, to make sure that it can survive graceful
restarts after starting to serve the clients.

When the restart is completed, Apache 2.0 spawns the workers that will
do the actual work. Depending on the used MPM, these can be threads,
processes and a mixture of both. For example the I<worker> MPM spawns
a number of processes, each running a number of threads. When each
child process is started C<PerlChildInit> handlers are
executed. Notice that they are run for each starting process, not a
thread.

From that moment on each working thread processes connections until
it's killed by the server or the server is shutdown.

=head2 Startup Phases Demonstration Module

Let's look at the following example that demonstrates all the startup
phases:

  file:MyApache/StartupLog.pm
  ---------------------------
  package MyApache::StartupLog;
  
  use strict;
  use warnings;
  
  use Apache::Log ();
  use Apache::ServerUtil ();
  
  use File::Spec::Functions;
  
  use Apache::Const -compile => 'OK';
  
  my $log_file = catfile "logs", "startup_log";
  my $log_fh;
  
  sub open_logs {
      my($conf_pool, $log_pool, $temp_pool, $s) = @_;
      my $log_path = Apache::server_root_relative($conf_pool, $log_file);
  
      $s->warn("opening the log file: $log_path");
      open $log_fh, ">>$log_path" or die "can't open $log_path: $!";
      my $oldfh = select($log_fh); $| = 1; select($oldfh);
  
      say("process $$ is born to reproduce");
      return Apache::OK;
  }
  
  sub post_config {
      my($conf_pool, $log_pool, $temp_pool, $s) = @_;
      say("configuration is completed");
      return Apache::OK;
  }
  
  sub child_init {
      my($child_pool, $s) = @_;
      say("process $$ is born to serve");
      return Apache::OK;
  }
  
  sub child_exit {
      my($child_pool, $s) = @_;
      say("process $$ now exits");
      return Apache::OK;
  }
  
  sub say {
      my($caller) = (caller(1))[3] =~ /([^:]+)$/;
      if (defined $log_fh) {
          printf $log_fh "[%s] - %-11s: %s\n", 
              scalar(localtime), $caller, $_[0];
      }
      else {
          # when the log file is not open
          warn __PACKAGE__ . " says: $_[0]\n";
      }
  }
  
  END {
      say("process $$ is shutdown\n");
  }
  
  1;


And the I<httpd.conf> configuration section:

  <IfModule prefork.c>
    StartServers         4
    MinSpareServers      4
    MaxSpareServers      4
    MaxClients           10
    MaxRequestsPerChild  0
  </IfModule>
  
  PerlModule            MyApache::StartupLog
  PerlOpenLogsHandler   MyApache::StartupLog::open_logs
  PerlPostConfigHandler MyApache::StartupLog::post_config
  PerlChildInitHandler  MyApache::StartupLog::child_init
  PerlChildExitHandler  MyApache::StartupLog::child_exit

When we perform a server startup followed by a shutdown, the
I<logs/startup_log> is created if it didn't exist already (it shares
the same directory with I<error_log> and other standard log files),
and each stage appends to it its log information. So when we perform:

  % bin/apachectl start && bin/apachectl stop

the following is getting logged to I<logs/startup_log>:

  [Thu May 29 13:11:08 2003] - open_logs  : process 21823 is born to reproduce
  [Thu May 29 13:11:08 2003] - post_config: configuration is completed
  [Thu May 29 13:11:09 2003] - END        : process 21823 is shutdown
  
  [Thu May 29 13:11:10 2003] - open_logs  : process 21825 is born to reproduce
  [Thu May 29 13:11:10 2003] - post_config: configuration is completed
  [Thu May 29 13:11:11 2003] - child_init : process 21830 is born to serve
  [Thu May 29 13:11:11 2003] - child_init : process 21831 is born to serve
  [Thu May 29 13:11:11 2003] - child_init : process 21832 is born to serve
  [Thu May 29 13:11:11 2003] - child_init : process 21833 is born to serve
  [Thu May 29 13:11:12 2003] - child_exit : process 21833 now exits
  [Thu May 29 13:11:12 2003] - child_exit : process 21832 now exits
  [Thu May 29 13:11:12 2003] - child_exit : process 21831 now exits
  [Thu May 29 13:11:12 2003] - child_exit : process 21830 now exits
  [Thu May 29 13:11:12 2003] - END        : process 21825 is shutdown

First of all, we can clearly see that Apache always restart itself
after the first I<post_config> phase is over. The logs show that the
I<post_config> phase is preceded by the I<open_logs> phase. Only
after Apache has restarted itself and has completed the I<open_logs>
and I<post_config> phase again the I<child_init> phase is run for each
child process. In our example we have had the setting
C<StartServers=4>, therefore you can see four child processes were
started.

Finally you can see that on server shutdown, the I<child_exit> phase
is run for each child process and the C<END {}> block is executed by
the parent process only.

Apache also specifies the I<pre_config> phase, which is executed
before the configuration files are parsed, but this is of no use to
mod_perl, because mod_perl is loaded only during the configuration
phase.

Now let's discuss each of the mentioned startup handlers and their
implementation in the C<MyApache::StartupLog> module in detail.

=head2 PerlOpenLogsHandler

The I<open_logs> phase happens just before the I<post_config> phase.

Handlers registered by C<PerlOpenLogsHandler> are usually used for
opening module-specific log files (e.g., httpd core and mod_ssl open
their log files during this phase).

At this stage the C<STDERR> stream is not yet redirected to
I<error_log>, and therefore any messages to that stream will be
printed to the console the server is starting from (if such exists).

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>.

As we have seen in the
C<L<MyApache::StartupLog::open_logs|/Startup_Phases_Demonstration_Module>>
handler, the I<open_logs> phase handlers accept four arguments: the
configuration pool, the logging stream pool, the temporary pool and
the server object:

  sub open_logs {
      my($conf_pool, $log_pool, $temp_pool, $s) = @_;
      my $log_path = Apache::server_root_relative($conf_pool, $log_file);
  
      $s->warn("opening the log file: $log_path");
      open $log_fh, ">>$log_path" or die "can't open $log_path: $!";
      my $oldfh = select($log_fh); $| = 1; select($oldfh);
  
      say("process $$ is born to reproduce");
      return Apache::OK;
  }

In our example the handler uses the function
C<Apache::server_root_relative()> to set the full path to the log
file, which is then opened for appending and set to unbuffered
mode. Finally it logs the fact that it's running in the parent
process.

As you've seen in the example this handler is configured by adding to
I<httpd.conf>:

  PerlOpenLogsHandler MyApache::StartupLog::open_logs



=head2 PerlPostConfigHandler

The I<post_config> phase happens right after Apache has processed the
configuration files, before any child processes were spawned (which
happens at the I<child_init> phase).

This phase can be used for initializing things to be shared between
all child processes. You can do the same in the startup file, but in
the I<post_config> phase you have an access to a complete
configuration tree (via
C<L<Apache::Directive|docs::2.0::api::Apache::Directive>>).

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>.

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>.

In our C<L<MyApache::StartupLog|/Startup_Phases_Demonstration_Module>>
example we used the I<post_config()> handler:

  sub post_config {
      my($conf_pool, $log_pool, $temp_pool, $s) = @_;
      say("configuration is completed");
      return Apache::OK;
  }

As you can see, its arguments are identical to the I<open_logs>
phase's handler. In this example handler we don't do much but logging
that the configuration was completed and returning right away.

As you've seen in the example this handler is configured by adding to
I<httpd.conf>:

  PerlPostConfigHandler MyApache::StartupLog::post_config


=head2 PerlChildInitHandler

The I<child_init> phase happens immediately after the child process is
spawned. Each child process (not a thread!) will run the hooks of this
phase only once in their life-time.

In the prefork MPM this phase is useful for initializing any data
structures which should be private to each process. For example
C<Apache::DBI> pre-opens database connections during this phase and
C<Apache::Resource> sets the process' resources limits.

This phase is of type
C<L<VOID|docs::2.0::user::handlers::intro/item_VOID>>.

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>.

In our C<L<MyApache::StartupLog|/Startup_Phases_Demonstration_Module>>
example we used the I<child_init()> handler:

  sub child_init {
      my($child_pool, $s) = @_;
      say("process $$ is born to serve");
      return Apache::OK;
  }

The I<child_init()> handler accepts two arguments: the child process
pool and the server object. The example handler logs the pid of the
child process it's run in and returns.

As you've seen in the example this handler is configured by adding to
I<httpd.conf>:

  PerlChildInitHandler  MyApache::StartupLog::child_init

=head2 PerlChildExitHandler

Opposite to the I<child_init> phase, the I<child_exit> phase is
executed before the child process exits. Notice that it happens only
when the process exits, not the thread (assuming that you are using a
threaded mpm).

This phase is of type
C<L<RUN_ALL|docs::2.0::user::handlers::intro/item_RUN_ALL>>. 

The handler's configuration scope is
C<L<SRV|docs::2.0::user::config::config/item_SRV>>.

In our C<L<MyApache::StartupLog|/Startup_Phases_Demonstration_Module>>
example we used the I<child_exit()> handler:

  sub child_exit {
      my($child_pool, $s) = @_;
      say("process $$ now exits");
      return Apache::OK;
  }

The I<child_exit()> handler accepts two arguments: the child process
pool and the server object. The example handler logs the pid of the
child process it's run in and returns.

As you've seen in the example this handler is configured by adding to
I<httpd.conf>:

  PerlChildExitHandler  MyApache::StartupLog::child_exit


=head1 Maintainers

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

=over

=item *

Stas Bekman E<lt>stas (at) stason.orgE<gt>

=back


=head1 Authors

=over

=item *

=back

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



=cut

