reverting (most of) the whitespace changes
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / FastCGI.pm
1 package Catalyst::Engine::FastCGI;
2
3 use Moose;
4 extends 'Catalyst::Engine::CGI';
5
6 eval "use FCGI";
7 die "Unable to load the FCGI module, you may need to install it:\n$@\n" if $@;
8
9 =head1 NAME
10
11 Catalyst::Engine::FastCGI - FastCGI Engine
12
13 =head1 DESCRIPTION
14
15 This is the FastCGI engine.
16
17 =head1 OVERLOADED METHODS
18
19 This class overloads some methods from C<Catalyst::Engine::CGI>.
20
21 =head2 $self->run($c, $listen, { option => value, ... })
22  
23 Starts the FastCGI server.  If C<$listen> is set, then it specifies a
24 location to listen for FastCGI requests;
25
26 =over 4
27
28 =item /path
29
30 listen via Unix sockets on /path
31
32 =item :port
33
34 listen via TCP on port on all interfaces
35
36 =item hostname:port
37
38 listen via TCP on port bound to hostname
39
40 =back
41
42 Options may also be specified;
43
44 =over 4
45
46 =item leave_umask
47
48 Set to 1 to disable setting umask to 0 for socket open =item nointr
49
50 Do not allow the listener to be interrupted by Ctrl+C
51
52 =item nproc
53
54 Specify a number of processes for FCGI::ProcManager
55
56 =item pidfile
57
58 Specify a filename for the pid file
59
60 =item manager
61
62 Specify a FCGI::ProcManager sub-class
63
64 =item detach          
65
66 Detach from console
67
68 =item keep_stderr
69
70 Send STDERR to STDOUT instead of the webserver
71
72 =back
73
74 =cut
75
76 sub run {
77     my ( $self, $class, $listen, $options ) = @_;
78
79     my $sock = 0;
80     if ($listen) {
81         my $old_umask = umask;
82         unless ( $options->{leave_umask} ) {
83             umask(0);
84         }
85         $sock = FCGI::OpenSocket( $listen, 100 )
86           or die "failed to open FastCGI socket; $!";
87         unless ( $options->{leave_umask} ) {
88             umask($old_umask);
89         }
90     }
91     elsif ( $^O ne 'MSWin32' ) {
92         -S STDIN
93           or die "STDIN is not a socket; specify a listen location";
94     }
95
96     $options ||= {};
97
98     my %env;
99     my $error = \*STDERR; # send STDERR to the web server
100        $error = \*STDOUT  # send STDERR to stdout (a logfile)
101          if $options->{keep_stderr}; # (if asked to)
102     
103     my $request =
104       FCGI::Request( \*STDIN, \*STDOUT, $error, \%env, $sock,
105         ( $options->{nointr} ? 0 : &FCGI::FAIL_ACCEPT_ON_INTR ),
106       );
107
108     my $proc_manager;
109
110     if ($listen) {
111         $options->{manager} ||= "FCGI::ProcManager";
112         $options->{nproc}   ||= 1;
113
114         $self->daemon_fork() if $options->{detach};
115
116         if ( $options->{manager} ) {
117             eval "use $options->{manager}; 1" or die $@;
118
119             $proc_manager = $options->{manager}->new(
120                 {
121                     n_processes => $options->{nproc},
122                     pid_fname   => $options->{pidfile},
123                 }
124             );
125
126             # detach *before* the ProcManager inits
127             $self->daemon_detach() if $options->{detach};
128
129             $proc_manager->pm_manage();
130         }
131         elsif ( $options->{detach} ) {
132             $self->daemon_detach();
133         }
134     }
135
136     while ( $request->Accept >= 0 ) {
137         $proc_manager && $proc_manager->pm_pre_dispatch();
138         
139         # If we're running under Lighttpd, swap PATH_INFO and SCRIPT_NAME
140         # http://lists.rawmode.org/pipermail/catalyst/2006-June/008361.html
141         # Thanks to Mark Blythe for this fix
142         if ( $env{SERVER_SOFTWARE} && $env{SERVER_SOFTWARE} =~ /lighttpd/ ) {
143             $env{PATH_INFO} ||= delete $env{SCRIPT_NAME};
144         }
145         
146         $class->handle_request( env => \%env );
147         
148         $proc_manager && $proc_manager->pm_post_dispatch();
149     }
150 }
151
152 =head2 $self->write($c, $buffer)
153
154 =cut
155
156 sub write {
157     my ( $self, $c, $buffer ) = @_;
158
159     unless ( $self->{_prepared_write} ) {
160         $self->prepare_write($c);
161         $self->{_prepared_write} = 1;
162     }
163     
164     # XXX: We can't use Engine's write() method because syswrite
165     # appears to return bogus values instead of the number of bytes
166     # written: http://www.fastcgi.com/om_archive/mail-archive/0128.html
167     
168     # Prepend the headers if they have not yet been sent
169     if ( my $headers = delete $self->{_header_buf} ) {
170         $buffer = $headers . $buffer;
171     }
172
173     # FastCGI does not stream data properly if using 'print $handle',
174     # but a syswrite appears to work properly.
175     *STDOUT->syswrite($buffer);
176 }
177
178 =head2 $self->daemon_fork()
179
180 Performs the first part of daemon initialisation.  Specifically,
181 forking.  STDERR, etc are still connected to a terminal.
182
183 =cut
184
185 sub daemon_fork {
186     require POSIX;
187     fork && exit;
188 }
189
190 =head2 $self->daemon_detach( )
191
192 Performs the second part of daemon initialisation.  Specifically,
193 disassociates from the terminal.
194
195 However, this does B<not> change the current working directory to "/",
196 as normal daemons do.  It also does not close all open file
197 descriptors (except STDIN, STDOUT and STDERR, which are re-opened from
198 F</dev/null>).
199
200 =cut
201
202 sub daemon_detach {
203     my $self = shift;
204     print "FastCGI daemon started (pid $$)\n";
205     open STDIN,  "+</dev/null" or die $!;
206     open STDOUT, ">&STDIN"     or die $!;
207     open STDERR, ">&STDIN"     or die $!;
208     POSIX::setsid();
209 }
210
211 1;
212 __END__
213
214 =head1 WEB SERVER CONFIGURATIONS
215
216 =head2 Standalone FastCGI Server
217
218 In server mode the application runs as a standalone server and accepts 
219 connections from a web server.  The application can be on the same machine as
220 the web server, on a remote machine, or even on multiple remote machines.
221 Advantages of this method include running the Catalyst application as a
222 different user than the web server, and the ability to set up a scalable
223 server farm.
224
225 To start your application in server mode, install the FCGI::ProcManager
226 module and then use the included fastcgi.pl script.
227
228     $ script/myapp_fastcgi.pl -l /tmp/myapp.socket -n 5
229     
230 Command line options for fastcgi.pl include:
231
232     -d -daemon     Daemonize the server.
233     -p -pidfile    Write a pidfile with the pid of the process manager.
234     -l -listen     Listen on a socket path, hostname:port, or :port.
235     -n -nproc      The number of processes started to handle requests.
236     
237 See below for the specific web server configurations for using the external
238 server.
239
240 =head2 Apache 1.x, 2.x
241
242 Apache requires the mod_fastcgi module.  The same module supports both
243 Apache 1 and 2.
244
245 There are three ways to run your application under FastCGI on Apache: server, 
246 static, and dynamic.
247
248 =head3 Standalone server mode
249
250     FastCgiExternalServer /tmp/myapp.fcgi -socket /tmp/myapp.socket
251     Alias /myapp/ /tmp/myapp/myapp.fcgi/
252     
253     # Or, run at the root
254     Alias / /tmp/myapp.fcgi/
255     
256     # Optionally, rewrite the path when accessed without a trailing slash
257     RewriteRule ^/myapp$ myapp/ [R]
258     
259
260 The FastCgiExternalServer directive tells Apache that when serving
261 /tmp/myapp to use the FastCGI application listenting on the socket
262 /tmp/mapp.socket.  Note that /tmp/myapp.fcgi does not need to exist --
263 it's a virtual file name.  With some versions of C<mod_fastcgi> or
264 C<mod_fcgid>, you can use any name you like, but most require that the
265 virtual filename end in C<.fcgi>.
266
267 It's likely that Apache is not configured to serve files in /tmp, so the 
268 Alias directive maps the url path /myapp/ to the (virtual) file that runs the
269 FastCGI application. The trailing slashes are important as their use will
270 correctly set the PATH_INFO environment variable used by Catalyst to
271 determine the request path.  If you would like to be able to access your app
272 without a trailing slash (http://server/myapp), you can use the above
273 RewriteRule directive.
274
275 =head3 Static mode
276
277 The term 'static' is misleading, but in static mode Apache uses its own
278 FastCGI Process Manager to start the application processes.  This happens at
279 Apache startup time.  In this case you do not run your application's
280 fastcgi.pl script -- that is done by Apache. Apache then maps URIs to the
281 FastCGI script to run your application.
282
283     FastCgiServer /path/to/myapp/script/myapp_fastcgi.pl -processes 3
284     Alias /myapp/ /path/to/myapp/script/myapp_fastcgi.pl/
285     
286 FastCgiServer tells Apache to start three processes of your application at
287 startup.  The Alias command maps a path to the FastCGI application. Again,
288 the trailing slashes are important.
289     
290 =head3 Dynamic mode
291
292 In FastCGI dynamic mode, Apache will run your application on demand, 
293 typically by requesting a file with a specific extension (e.g. .fcgi).  ISPs
294 often use this type of setup to provide FastCGI support to many customers.
295
296 In this mode it is often enough to place or link your *_fastcgi.pl script in
297 your cgi-bin directory with the extension of .fcgi.  In dynamic mode Apache
298 must be able to run your application as a CGI script so ExecCGI must be
299 enabled for the directory.
300
301     AddHandler fastcgi-script .fcgi
302
303 The above tells Apache to run any .fcgi file as a FastCGI application.
304
305 Here is a complete example:
306
307     <VirtualHost *:80>
308         ServerName www.myapp.com
309         DocumentRoot /path/to/MyApp
310
311         # Allow CGI script to run
312         <Directory /path/to/MyApp>
313             Options +ExecCGI
314         </Directory>
315
316         # Tell Apache this is a FastCGI application
317         <Files myapp_fastcgi.pl>
318             SetHandler fastcgi-script
319         </Files>
320     </VirtualHost>
321
322 Then a request for /script/myapp_fastcgi.pl will run the
323 application.
324     
325 For more information on using FastCGI under Apache, visit
326 L<http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html>
327
328 =head3 Authorization header with mod_fastcgi or mod_cgi
329
330 By default, mod_fastcgi/mod_cgi do not pass along the Authorization header,
331 so modules like C<Catalyst::Plugin::Authentication::Credential::HTTP> will
332 not work.  To enable pass-through of this header, add the following
333 mod_rewrite directives:
334
335     RewriteCond %{HTTP:Authorization} ^(.+)
336     RewriteRule ^(.*)$ $1 [E=HTTP_AUTHORIZATION:%1,PT]
337
338 =head2 Lighttpd
339
340 These configurations were tested with Lighttpd 1.4.7.
341
342 =head3 Standalone server mode
343
344     server.document-root = "/var/www/MyApp/root"
345
346     fastcgi.server = (
347         "" => (
348             "MyApp" => (
349                 "socket"      => "/tmp/myapp.socket",
350                 "check-local" => "disable"
351             )
352         )
353     )
354
355 =head3 Static mode
356
357     server.document-root = "/var/www/MyApp/root"
358     
359     fastcgi.server = (
360         "" => (
361             "MyApp" => (
362                 "socket"       => "/tmp/myapp.socket",
363                 "check-local"  => "disable",
364                 "bin-path"     => "/var/www/MyApp/script/myapp_fastcgi.pl",
365                 "min-procs"    => 2,
366                 "max-procs"    => 5,
367                 "idle-timeout" => 20
368             )
369         )
370     )
371     
372 Note that in newer versions of lighttpd, the min-procs and idle-timeout
373 values are disabled.  The above example would start 5 processes.
374
375 =head3 Non-root configuration
376     
377 You can also run your application at any non-root location with either of the
378 above modes.
379
380     fastcgi.server = (
381         "/myapp" => (
382             "MyApp" => (
383                 # same as above
384             )
385         )
386     )
387
388 For more information on using FastCGI under Lighttpd, visit
389 L<http://www.lighttpd.net/documentation/fastcgi.html>
390
391 =head2 IIS
392
393 It is possible to run Catalyst under IIS with FastCGI, but we do not
394 yet have detailed instructions.
395
396 =head1 SEE ALSO
397
398 L<Catalyst>, L<FCGI>.
399
400 =head1 AUTHORS
401
402 Sebastian Riedel, <sri@cpan.org>
403
404 Christian Hansen, <ch@ngmedia.com>
405
406 Andy Grundman, <andy@hybridized.org>
407
408 =head1 THANKS
409
410 Bill Moseley, for documentation updates and testing.
411
412 =head1 COPYRIGHT
413
414 This program is free software, you can redistribute it and/or modify it under
415 the same terms as Perl itself.
416
417 =cut