1
# Licensed to the Apache Software Foundation (ASF) under one or more
2
# contributor license agreements. See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License. You may obtain a copy of the License at
8
# http://www.apache.org/licenses/LICENSE-2.0
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
16
package Apache2::Reload;
19
use warnings FATAL => 'all';
23
our $VERSION = '0.11';
25
use Apache2::Const -compile => qw(OK);
27
use Apache2::Connection;
28
use Apache2::ServerUtil;
29
use Apache2::RequestUtil;
33
use vars qw(%INCS %Stat $TouchTime);
35
%Stat = ($INC{"Apache2/Reload.pm"} => time);
41
my ($package, $file) = (caller)[0,1];
43
$class->register_module($package, $file);
46
sub package_to_module {
48
$package =~ s/::/\//g;
53
sub module_to_package {
56
$module =~ s/\.pm$//g;
61
my ($class, $package, $file) = @_;
62
my $module = package_to_module($package);
65
$INCS{$module} = $file;
68
$file = $INC{$module};
70
$INCS{$module} = $file;
74
sub unregister_module {
75
my ($class, $package) = @_;
76
my $module = package_to_module($package);
77
delete $INCS{$module};
80
# the first argument is:
81
# $c if invoked as 'PerlPreConnectionHandler'
82
# $r if invoked as 'PerlInitHandler'
85
$o = $o->base_server if ref($o) eq 'Apache2::Connection';
87
my $DEBUG = ref($o) && (lc($o->dir_config("ReloadDebug") || '') eq 'on');
89
my $ReloadByModuleName = ref($o) && (lc($o->dir_config("ReloadByModuleName") || '') eq 'on');
91
my $TouchFile = ref($o) && $o->dir_config("ReloadTouchFile");
93
my $ConstantRedefineWarnings = ref($o) &&
94
(lc($o->dir_config("ReloadConstantRedefineWarnings") || '') eq 'off')
100
warn "Checking mtime of $TouchFile\n" if $DEBUG;
101
my $touch_mtime = (stat $TouchFile)[9] || return Apache2::Const::OK;
102
return Apache2::Const::OK unless $touch_mtime > $TouchTime;
103
$TouchTime = $touch_mtime;
104
open my $fh, $TouchFile or die "Can't open '$TouchFile': $!";
105
$TouchModules = <$fh>;
106
chomp $TouchModules if $TouchModules;
109
if (ref($o) && (lc($o->dir_config("ReloadAll") || 'on') eq 'on')) {
110
*Apache2::Reload::INCS = \%INC;
113
*Apache2::Reload::INCS = \%INCS;
116
(ref($o) && $o->dir_config("ReloadModules")) ||
118
my @extra = split /\s+/, $ExtraList;
122
$prefix =~ s/::/\//g;
123
foreach my $match (keys %INC) {
124
if ($match =~ /^\Q$prefix\E/) {
125
$Apache2::Reload::INCS{$match} = $INC{$match};
130
Apache2::Reload->register_module($_);
135
my $ReloadDirs = ref($o) && $o->dir_config("ReloadDirectories");
136
my @watch_dirs = split(/\s+/, $ReloadDirs||'');
139
foreach my $key (sort { $a cmp $b } keys %Apache2::Reload::INCS) {
140
my $file = $Apache2::Reload::INCS{$key};
142
next unless defined $file;
144
next if @watch_dirs && !grep { $file =~ /^$_/ } @watch_dirs;
145
warn "Apache2::Reload: Checking mtime of $key\n" if $DEBUG;
147
my $mtime = (stat $file)[9];
149
unless (defined($mtime) && $mtime) {
151
$mtime = (stat "$_/$file")[9];
152
last if defined($mtime) && $mtime;
156
warn("Apache2::Reload: Can't locate $file\n"), next
157
unless defined $mtime and $mtime;
159
unless (defined $Stat{$file}) {
163
if ($mtime > $Stat{$file}) {
164
push @changed, [$key, $file];
166
$Stat{$file} = $mtime;
169
#First, let's unload all changed modules
170
foreach my $change (@changed) {
171
my ($module, $file) = @$change;
172
my $package = module_to_package($module);
173
ModPerl::Util::unload_package($package);
176
#Then, let's reload them all, so that module dependencies can satisfy
177
#themselves in the correct order.
178
foreach my $change (@changed) {
179
my ($module, $file) = @$change;
180
my $name = $ReloadByModuleName ? $module : $file;
183
my $package = module_to_package($module);
184
warn sprintf("Apache2::Reload: process %d reloading %s from %s\n",
185
$$, $package, $name);
189
return Apache2::Const::OK;
198
Apache2::Reload - Reload Perl Modules when Changed on Disk
202
# Monitor and reload all modules in %INC:
204
PerlModule Apache2::Reload
205
PerlInitHandler Apache2::Reload
207
# when working with protocols and connection filters
208
# PerlPreConnectionHandler Apache2::Reload
210
# Reload groups of modules:
212
PerlModule Apache2::Reload
213
PerlInitHandler Apache2::Reload
214
PerlSetVar ReloadAll Off
215
PerlSetVar ReloadModules "ModPerl::* Apache2::*"
216
#PerlSetVar ReloadDebug On
217
#PerlSetVar ReloadByModuleName On
219
# Reload a single module from within itself:
220
package My::Apache2::Module;
227
C<Apache2::Reload> reloads modules that change on the disk.
229
When Perl pulls a file via C<require>, it stores the filename in the
230
global hash C<%INC>. The next time Perl tries to C<require> the same
231
file, it sees the file in C<%INC> and does not reload from disk. This
232
module's handler can be configured to iterate over the modules in
233
C<%INC> and reload those that have changed on disk or only specific
234
modules that have registered themselves with C<Apache2::Reload>. It can
235
also do the check for modified modules, when a special touch-file has
238
Require-hooks, i.e., entries in %INC which are references, are ignored. The
239
hook should modify %INC itself, adding the path to the module file, for it to
242
C<Apache2::Reload> inspects and reloads the B<file> associated with a given
243
module. Changes to @INC are not recognized, as it is the file which is
244
being re-required, not the module name.
246
In version 0.10 and earlier the B<module name>, not the file, is re-required.
247
Meaning it operated on the the current context of @INC. If you still want this
248
behavior set this environment variable in I<httpd.conf>:
250
PerlSetVar ReloadByModuleName On
252
This means, when called as a C<Perl*Handler>, C<Apache2::Reload> will not see
253
C<@INC> paths added or removed by C<ModPerl::Registry> scripts, as the value of
254
C<@INC> is saved on server startup and restored to that value after each
255
request. In other words, if you want C<Apache2::Reload> to work with modules
256
that live in custom C<@INC> paths, you should modify C<@INC> when the server is
257
started. Besides, C<'use lib'> in the startup script, you can also set the
258
C<PERL5LIB> variable in the httpd's environment to include any non-standard
259
'lib' directories that you choose. For example, to accomplish that you can
262
PERL5LIB=/home/httpd/perl/extra; export PERL5LIB
264
in the script that starts Apache. Alternatively, you can set this
265
environment variable in I<httpd.conf>:
267
PerlSetEnv PERL5LIB /home/httpd/perl/extra
269
=head2 Monitor All Modules in C<%INC>
271
To monitor and reload all modules in C<%INC> at the beginning of
272
request's processing, simply add the following configuration to your
275
PerlModule Apache2::Reload
276
PerlInitHandler Apache2::Reload
278
When working with connection filters and protocol modules
279
C<Apache2::Reload> should be invoked in the pre_connection stage:
281
PerlPreConnectionHandler Apache2::Reload
283
See also the discussion on
284
C<L<PerlPreConnectionHandler|docs::2.0::user::handlers::protocols/PerlPreConnectionHandler>>.
286
=head2 Register Modules Implicitly
288
To only reload modules that have registered with C<Apache2::Reload>,
289
add the following to the I<httpd.conf>:
291
PerlModule Apache2::Reload
292
PerlInitHandler Apache2::Reload
293
PerlSetVar ReloadAll Off
294
# ReloadAll defaults to On
296
Then any modules with the line:
300
Will be reloaded when they change.
302
=head2 Register Modules Explicitly
304
You can also register modules explicitly in your I<httpd.conf> file
305
that you want to be reloaded on change:
307
PerlModule Apache2::Reload
308
PerlInitHandler Apache2::Reload
309
PerlSetVar ReloadAll Off
310
PerlSetVar ReloadModules "My::Foo My::Bar Foo::Bar::Test"
312
Note that these are split on whitespace, but the module list B<must>
313
be in quotes, otherwise Apache tries to parse the parameter list.
315
The C<*> wild character can be used to register groups of files under
316
the same namespace. For example the setting:
318
PerlSetVar ReloadModules "ModPerl::* Apache2::*"
320
will monitor all modules under the namespaces C<ModPerl::> and
323
=head2 Monitor Only Certain Sub Directories
325
To reload modules only in certain directories (and their
326
subdirectories) add the following to the I<httpd.conf>:
328
PerlModule Apache2::Reload
329
PerlInitHandler Apache2::Reload
330
PerlSetVar ReloadDirectories "/tmp/project1 /tmp/project2"
332
You can further narrow the list of modules to be reloaded from the
333
chosen directories with C<ReloadModules> as in:
335
PerlModule Apache2::Reload
336
PerlInitHandler Apache2::Reload
337
PerlSetVar ReloadDirectories "/tmp/project1 /tmp/project2"
338
PerlSetVar ReloadAll Off
339
PerlSetVar ReloadModules "MyApache2::*"
341
In this configuration example only modules from the namespace
342
C<MyApache2::> found in the directories I</tmp/project1/> and
343
I</tmp/project2/> (and their subdirectories) will be reloaded.
345
=head2 Special "Touch" File
347
You can also declare a file, which when gets C<touch(1)>ed, causes the
348
reloads to be performed. For example if you set:
350
PerlSetVar ReloadTouchFile /tmp/reload_modules
352
and don't C<touch(1)> the file I</tmp/reload_modules>, the reloads
353
won't happen until you go to the command line and type:
355
% touch /tmp/reload_modules
357
When you do that, the modules that have been changed, will be
358
magically reloaded on the next request. This option works with any
359
mode described before.
361
=head2 Unregistering a module
363
In some cases, it might be necessary to explicitely stop reloading
366
Apache2::Reload->unregister_module('Some::Module');
368
But be carefull, since unregistering a module in this way will only
369
do so for the current interpreter. This feature should be used with
372
=head1 Performance Issues
374
This module is perfectly suited for a development environment. Though
375
it's possible that you would like to use it in a production
376
environment, since with C<Apache2::Reload> you don't have to restart
377
the server in order to reload changed modules during software
378
updates. Though this convenience comes at a price:
384
If the "touch" file feature is used, C<Apache2::Reload> has to stat(2)
385
the touch file on each request, which adds a slight but most likely
386
insignificant overhead to response times. Otherwise C<Apache2::Reload>
387
will stat(2) each registered module or even worse--all modules in
388
C<%INC>, which will significantly slow everything down.
392
Once the child process reloads the modules, the memory used by these
393
modules is not shared with the parent process anymore. Therefore the
394
memory consumption may grow significantly.
398
Therefore doing a full server stop and restart is probably a better
403
If you aren't sure whether the modules that are supposed to be
404
reloaded, are actually getting reloaded, turn the debug mode on:
406
PerlSetVar ReloadDebug On
410
=head2 Problems With Reloading Modules Which Do Not Declare Their Package Name
412
If you modify modules, which don't declare their C<package>, and rely on
413
C<Apache2::Reload> to reload them, you may encounter problems: i.e.,
414
it'll appear as if the module wasn't reloaded when in fact it
415
was. This happens because when C<Apache2::Reload> C<require()>s such a
416
module all the global symbols end up in the C<Apache2::Reload>
417
namespace! So the module does get reloaded and you see the compile
418
time errors if there are any, but the symbols don't get imported to
419
the right namespace. Therefore the old version of the code is running.
422
=head2 Failing to Find a File to Reload
424
C<Apache2::Reload> uses C<%INC> to find the files on the filesystem. If
425
an entry for a certain filepath in C<%INC> is relative,
426
C<Apache2::Reload> will use C<@INC> to try to resolve that relative
427
path. Now remember that mod_perl freezes the value of C<@INC> at the
428
server startup, and you can modify it only for the duration of one
429
request when you need to load some module which is not in on of the
430
C<@INC> directories. So a module gets loaded, and registered in
431
C<%INC> with a relative path. Now when C<Apache2::Reload> tries to find
432
that module to check whether it has been modified, it can't find since
433
its directory is not in C<@INC>. So C<Apache2::Reload> will silently
436
You can enable the C<Debug|/Debug> mode to see what C<Apache2::Reload>
437
does behind the scenes.
441
=head2 Problems with Scripts Running with Registry Handlers that Cache the Code
443
The following problem is relevant only to registry handlers that cache
444
the compiled script. For example it concerns
445
C<L<ModPerl::Registry|docs::2.0::api::ModPerl::Registry>> but not
446
C<L<ModPerl::PerlRun|docs::2.0::api::ModPerl::PerlRun>>.
450
Let's say that there is a module C<My::Utils>:
455
BEGIN { warn __PACKAGE__ , " was reloaded\n" }
456
use base qw(Exporter);
457
@EXPORT = qw(colour);
458
sub colour { "white" }
461
And a registry script F<test.pl>:
466
print "Content-type: text/plain\n\n";
467
print "the color is " . colour();
469
Assuming that the server is running in a single mode, we request the
470
script for the first time and we get the response:
474
Now we change F<My/Utils.pm>:
476
- sub colour { "white" }
477
+ sub colour { "red" }
479
And issue the request again. C<Apache2::Reload> does its job and we can
480
see that C<My::Utils> was reloaded (look in the I<error_log>
481
file). However the script still returns:
485
=head3 The Explanation
487
Even though F<My/Utils.pm> was reloaded, C<ModPerl::Registry>'s cached
488
code won't run 'C<use My::Utils;>' again (since it happens only once,
489
i.e. during the compile time). Therefore the script doesn't know that
490
the subroutine reference has been changed.
492
This is easy to verify. Let's change the script to be:
497
print "Content-type: text/plain\n\n";
498
my $sub_int = \&colour;
499
my $sub_ext = \&My::Utils::colour;
500
print "int $sub_int\n";
501
print "ext $sub_ext\n";
503
Issue a request, you will see something similar to:
508
As you can see both point to the same CODE reference (meaning that
509
it's the same symbol). After modifying F<My/Utils.pm> again:
511
- sub colour { "red" }
512
+ sub colour { "blue" }
514
and calling the script on the secondnd time, we get:
519
You can see that the internal CODE reference is not the same as the
524
There are two solutions to this problem:
526
Solution 1: replace C<use()> with an explicit C<require()> +
530
+ require My::Utils; My::Utils->import();
532
now the changed functions will be reimported on every request.
534
Solution 2: remember to touch the script itself every time you change
535
the module that it requires.
537
=head1 Threaded MPM and Multiple Perl Interpreters
539
If you use C<Apache2::Reload> with a threaded MPM and multiple Perl
540
interpreters, the modules will be reloaded by each interpreter as they
541
are used, not every interpreters at once. Similar to mod_perl 1.0
542
where each child has its own Perl interpreter, the modules are
543
reloaded as each child is hit with a request.
545
If a module is loaded at startup, the syntax tree of each subroutine
546
is shared between interpreters (big win), but each subroutine has its
547
own padlist (where lexical my variables are stored). Once
548
C<Apache2::Reload> reloads a module, this sharing goes away and each
549
Perl interpreter will have its own copy of the syntax tree for the
550
reloaded subroutines.
555
The short summary of this is: Don't use pseudo-hashes. They are
556
deprecated since Perl 5.8 and are removed in 5.9.
558
Use an array with constant indexes. Its faster in the general case,
559
its more guaranteed, and generally, it works.
561
The long summary is that some work has been done to get this module
562
working with modules that use pseudo-hashes, but it's still broken in
563
the case of a single module that contains multiple packages that all
573
mod_perl 2.0 and its core modules are copyrighted under
574
The Apache Software License, Version 2.0.
579
Matt Sergeant, matt@sergeant.org
581
Stas Bekman (porting to mod_perl 2.0)
583
A few concepts borrowed from C<Stonehenge::Reload> by Randal Schwartz
584
and C<Apache::StatINC> (mod_perl 1.x) by Doug MacEachern and Ask
589
the mod_perl developers, dev@perl.apache.org