Merge branch 'master' of https://github.com/jgoodman/Freeside
[freeside.git] / rt / lib / RT / Test / Apache.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 package RT::Test::Apache;
50 use strict;
51 use warnings;
52
53 my %MODULES = (
54     '2.2' => {
55         "mod_perl" => [qw(authz_host env alias perl)],
56         "fastcgi"  => [qw(authz_host env alias mime fastcgi)],
57     },
58 );
59
60 my $apache_module_prefix = $ENV{RT_TEST_APACHE_MODULES};
61 my $apxs =
62      $ENV{RT_TEST_APXS}
63   || RT::Test->find_executable('apxs')
64   || RT::Test->find_executable('apxs2');
65
66 if ($apxs and not $apache_module_prefix) {
67     $apache_module_prefix = `$apxs -q LIBEXECDIR`;
68     chomp $apache_module_prefix;
69 }
70
71 $apache_module_prefix ||= 'modules';
72
73 sub basic_auth {
74     my $self = shift;
75     my $passwd = File::Spec->rel2abs( File::Spec->catfile(
76         't', 'data', 'configs', 'passwords' ) );
77
78     return <<"EOT";
79     AuthType Basic
80     AuthName "restricted area"
81     AuthUserFile $passwd
82     Require user root
83 EOT
84 }
85
86 sub start_server {
87     my ($self, %config) = @_;
88     my %tmp = %{$config{tmp}};
89     my %info = $self->apache_server_info( %config );
90
91     RT::Test::diag(do {
92         open( my $fh, '<', $tmp{'config'}{'RT'} ) or die $!;
93         local $/;
94         <$fh>
95     });
96
97     my $tmpl = File::Spec->rel2abs( File::Spec->catfile(
98         't', 'data', 'configs',
99         'apache'. $info{'version'} .'+'. $config{variant} .'.conf'
100     ) );
101     my %opt = (
102         listen         => $config{port},
103         server_root    => $info{'HTTPD_ROOT'} || $ENV{'HTTPD_ROOT'}
104             || Test::More::BAIL_OUT("Couldn't figure out server root"),
105         document_root  => $RT::MasonComponentRoot,
106         tmp_dir        => "$tmp{'directory'}",
107         rt_bin_path    => $RT::BinPath,
108         rt_sbin_path   => $RT::SbinPath,
109         rt_site_config => $ENV{'RT_SITE_CONFIG'},
110         load_modules   => $info{load_modules},
111         basic_auth     => $config{basic_auth} ? $self->basic_auth : "",
112     );
113     foreach (qw(log pid lock)) {
114         $opt{$_ .'_file'} = File::Spec->catfile(
115             "$tmp{'directory'}", "apache.$_"
116         );
117     }
118
119     $tmp{'config'}{'apache'} = File::Spec->catfile(
120         "$tmp{'directory'}", "apache.conf"
121     );
122     $self->process_in_file(
123         in      => $tmpl, 
124         out     => $tmp{'config'}{'apache'},
125         options => \%opt,
126     );
127
128     $self->fork_exec($info{'executable'}, '-f', $tmp{'config'}{'apache'});
129     my $pid = do {
130         my $tries = 15;
131         while ( !-s $opt{'pid_file'} ) {
132             $tries--;
133             last unless $tries;
134             sleep 1;
135         }
136         my $pid_fh;
137         unless (-e $opt{'pid_file'} and open($pid_fh, '<', $opt{'pid_file'})) {
138             Test::More::BAIL_OUT("Couldn't start apache server, no pid file (unknown error)")
139                   unless -e $opt{log_file};
140
141             open my $log, "<", $opt{log_file};
142             my $error = do {local $/; <$log>};
143             close $log;
144             $RT::Logger->error($error) if $error;
145             Test::More::BAIL_OUT("Couldn't start apache server!");
146         }
147
148         my $pid = <$pid_fh>;
149         chomp $pid;
150         $pid;
151     };
152
153     Test::More::ok($pid, "Started apache server #$pid");
154     return $pid;
155 }
156
157 sub apache_server_info {
158     my $self = shift;
159     my %res = @_;
160
161     my $bin = $res{'executable'} = $ENV{'RT_TEST_APACHE'}
162         || $self->find_apache_server
163         || Test::More::BAIL_OUT("Couldn't find apache server, use RT_TEST_APACHE");
164
165     Test::More::BAIL_OUT(
166         "Couldn't find apache modules directory (set APXS= or RT_TEST_APACHE_MODULES=)"
167     ) unless -d $apache_module_prefix;
168
169
170     RT::Test::diag("Using '$bin' apache executable for testing");
171
172     my $info = `$bin -V`;
173     ($res{'version'}) = ($info =~ m{Server\s+version:\s+Apache/(\d+\.\d+)\.});
174     Test::More::BAIL_OUT(
175         "Couldn't figure out version of the server"
176     ) unless $res{'version'};
177
178     my %opts = ($info =~ m/^\s*-D\s+([A-Z_]+?)(?:="(.*)")$/mg);
179     %res = (%res, %opts);
180
181     $res{'modules'} = [
182         map {s/^\s+//; s/\s+$//; $_}
183         grep $_ !~ /Compiled in modules/i,
184         split /\r*\n/, `$bin -l`
185     ];
186
187     Test::More::BAIL_OUT(
188         "Unsupported apache version $res{version}"
189     ) unless exists $MODULES{$res{version}};
190
191     Test::More::BAIL_OUT(
192         "Unsupported apache variant $res{variant}"
193     ) unless exists $MODULES{$res{version}}{$res{variant}};
194
195     my @mlist = @{$MODULES{$res{version}}{$res{variant}}};
196     push @mlist, "authn_file", "auth_basic", "authz_user" if $res{basic_auth};
197
198     $res{'load_modules'} = '';
199     foreach my $mod ( @mlist ) {
200         next if grep $_ =~ /^(mod_|)$mod\.c$/, @{ $res{'modules'} };
201
202         my $so_file = $apache_module_prefix."/mod_".$mod.".so";
203         Test::More::BAIL_OUT( "Couldn't load $mod module (expected in $so_file)" )
204               unless -f $so_file;
205         $res{'load_modules'} .=
206             "LoadModule ${mod}_module $so_file\n";
207     }
208     return %res;
209 }
210
211 sub find_apache_server {
212     my $self = shift;
213     return $_ foreach grep defined,
214         map RT::Test->find_executable($_),
215         qw(httpd apache apache2 apache1);
216     return undef;
217 }
218
219 sub apache_mpm_type {
220     my $self = shift;
221     my $apache = $self->find_apache_server;
222     my $out = `$apache -l`;
223     if ( $out =~ /^\s*(worker|prefork|event|itk)\.c\s*$/m ) {
224         return $1;
225     }
226 }
227
228 sub fork_exec {
229     my $self = shift;
230
231     RT::Test::__disconnect_rt();
232     my $pid = fork;
233     unless ( defined $pid ) {
234         die "cannot fork: $!";
235     } elsif ( !$pid ) {
236         exec @_;
237         die "can't exec `". join(' ', @_) ."` program: $!";
238     } else {
239         RT::Test::__reconnect_rt();
240         return $pid;
241     }
242 }
243
244 sub process_in_file {
245     my $self = shift;
246     my %args = ( in => undef, options => undef, @_ );
247
248     my $text = RT::Test->file_content( $args{'in'} );
249     while ( my ($opt) = ($text =~ /\%\%(.+?)\%\%/) ) {
250         my $value = $args{'options'}{ lc $opt };
251         die "no value for $opt" unless defined $value;
252
253         $text =~ s/\%\%\Q$opt\E\%\%/$value/g;
254     }
255
256     my ($out_fh, $out_conf);
257     unless ( $args{'out'} ) {
258         ($out_fh, $out_conf) = tempfile();
259     } else {
260         $out_conf = $args{'out'};
261         open( $out_fh, '>', $out_conf )
262             or die "couldn't open '$out_conf': $!";
263     }
264     print $out_fh $text;
265     seek $out_fh, 0, 0;
266
267     return ($out_fh, $out_conf);
268 }
269
270 1;