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