Write out the pid file after double fork.
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Script / Server.pm
1 package Catalyst::Script::Server;
2 use Moose;
3 use MooseX::Types::Common::Numeric qw/PositiveInt/;
4 use MooseX::Types::Moose qw/ArrayRef Str Bool Int RegexpRef/;
5 use Catalyst::Utils;
6 use namespace::autoclean;
7
8 with 'Catalyst::ScriptRole';
9
10 has debug => (
11     traits        => [qw(Getopt)],
12     cmd_aliases   => 'd',
13     isa           => Bool,
14     is            => 'ro',
15     documentation => q{Force debug mode},
16 );
17
18 has host => (
19     traits        => [qw(Getopt)],
20     cmd_aliases   => 'h',
21     isa           => Str,
22     is            => 'ro',
23     # N.B. undef (the default) means we bind on all interfaces on the host.
24     documentation => 'Specify a hostname or IP on this host for the server to bind to',
25 );
26
27 has fork => (
28     traits        => [qw(Getopt)],
29     cmd_aliases   => 'f',
30     isa           => Bool,
31     is            => 'ro',
32     default       => 0,
33     documentation => 'Fork the server to be able to serve multiple requests at once',
34 );
35
36 has port => (
37     traits        => [qw(Getopt)],
38     cmd_aliases   => 'p',
39     isa           => PositiveInt,
40     is            => 'ro',
41     default       => sub {
42         Catalyst::Utils::env_value(shift->application_name, 'port') || 3000
43     },
44     documentation => 'Specify a different listening port (to the default port 3000)',
45 );
46
47 use Moose::Util::TypeConstraints;
48 class_type 'MooseX::Daemonize::Pid::File';
49 subtype 'MyStr', as Str, where { 1 }; # FIXME - Fuck ugly!
50 coerce 'MooseX::Daemonize::Pid::File', from 'MyStr', via {
51     Class::MOP::load_class("MooseX::Daemonize::Pid::File");
52     MooseX::Daemonize::Pid::File->new( file => $_ );
53 };
54 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
55     'MooseX::Daemonize::Pid::File' => '=s',
56 );
57 has pidfile => (
58     traits        => [qw(Getopt)],
59     cmd_aliases   => 'pid',
60     isa           => 'MooseX::Daemonize::Pid::File',
61     is            => 'ro',
62     documentation => 'Specify a pidfile',
63     coerce        => 1,
64     predicate     => '_has_pidfile',
65 );
66
67 sub BUILD {
68     my $self = shift;
69
70     if ($self->background) {
71         # FIXME - This is evil. Should we just add MX::Daemonize to the deps?
72         Class::MOP::load_class('MooseX::Daemonize::Core');
73         MooseX::Daemonize::Core->meta->apply($self);
74     }
75 }
76
77 has keepalive => (
78     traits        => [qw(Getopt)],
79     cmd_aliases   => 'k',
80     isa           => Bool,
81     is            => 'ro',
82     default       => 0,
83     documentation => 'Support keepalive',
84 );
85
86 has background => (
87     traits        => [qw(Getopt)],
88     cmd_aliases   => 'bg',
89     isa           => Bool,
90     is            => 'ro',
91     default       => 0,
92     documentation => 'Run in the background',
93 );
94
95 has restart => (
96     traits        => [qw(Getopt)],
97     cmd_aliases   => 'r',
98     isa           => Bool,
99     is            => 'ro',
100     default       => sub {
101         Catalyst::Utils::env_value(shift->application_name, 'reload') || 0;
102     },
103     documentation => 'use Catalyst::Restarter to detect code changes and restart the application',
104 );
105
106 has restart_directory => (
107     traits        => [qw(Getopt)],
108     cmd_aliases   => [ 'rdir', 'restartdirectory' ],
109     isa           => ArrayRef[Str],
110     is            => 'ro',
111     documentation => 'Restarter directory to watch',
112     predicate     => '_has_restart_directory',
113 );
114
115 has restart_delay => (
116     traits        => [qw(Getopt)],
117     cmd_aliases   => 'rd',
118     isa           => Int,
119     is            => 'ro',
120     documentation => 'Set a restart delay',
121     predicate     => '_has_restart_delay',
122 );
123
124 {
125     use Moose::Util::TypeConstraints;
126
127     my $tc = subtype as RegexpRef;
128     coerce $tc, from Str, via { qr/$_/ };
129
130     MooseX::Getopt::OptionTypeMap->add_option_type_to_map($tc => '=s');
131
132     has restart_regex => (
133         traits        => [qw(Getopt)],
134         cmd_aliases   => 'rr',
135         isa           => $tc,
136         coerce        => 1,
137         is            => 'ro',
138         documentation => 'Restart regex',
139         predicate     => '_has_restart_regex',
140     );
141 }
142
143 has follow_symlinks => (
144     traits        => [qw(Getopt)],
145     cmd_aliases   => 'sym',
146     isa           => Bool,
147     is            => 'ro',
148     default       => 0,
149     documentation => 'Follow symbolic links',
150     predicate     => '_has_follow_symlinks',
151 );
152
153 sub _plack_engine_name {
154     my $self = shift;
155     return $self->fork ? 'Starman' : $self->keepalive ? 'Starman' : 'Standalone';
156 }
157
158 sub _restarter_args {
159     my $self = shift;
160
161     return (
162         argv => $self->ARGV,
163         start_sub => sub { $self->_run_application },
164         ($self->_has_follow_symlinks   ? (follow_symlinks => $self->follow_symlinks)   : ()),
165         ($self->_has_restart_delay     ? (sleep_interval  => $self->restart_delay)     : ()),
166         ($self->_has_restart_directory ? (directories     => $self->restart_directory) : ()),
167         ($self->_has_restart_regex     ? (filter          => $self->restart_regex)     : ()),
168     ),
169     (
170         map { $_ => $self->$_ } qw(application_name host port debug pidfile fork background keepalive)
171     );
172 }
173
174 has restarter_class => (
175     is => 'ro',
176     isa => Str,
177     lazy => 1,
178     default => sub {
179         my $self = shift;
180         Catalyst::Utils::env_value($self->application_name, 'RESTARTER') || 'Catalyst::Restarter';
181     }
182 );
183
184 sub run {
185     my $self = shift;
186
187     local $ENV{CATALYST_DEBUG} = 1
188         if $self->debug;
189
190     if ( $self->restart ) {
191         die "Cannot run in the background and also watch for changed files.\n"
192             if $self->background;
193         die "Cannot write out a pid file and fork for the restarter.\n"
194             if $self->_has_pidfile;
195
196         # If we load this here, then in the case of a restarter, it does not
197         # need to be reloaded for each restart.
198         require Catalyst;
199
200         # If this isn't done, then the Catalyst::Devel tests for the restarter
201         # fail.
202         $| = 1 if $ENV{HARNESS_ACTIVE};
203
204         Catalyst::Utils::ensure_class_loaded($self->restarter_class);
205
206         my $subclass = $self->restarter_class->pick_subclass;
207
208         my $restarter = $subclass->new(
209             $self->_restarter_args()
210         );
211
212         $restarter->run_and_watch;
213     }
214     else {
215         if ($self->background) {
216             $self->daemon_fork;
217
218             return 1 unless $self->is_daemon;
219
220             Class::MOP::load_class($self->application_name);
221
222             $self->daemon_detach;
223         }
224
225         $self->pidfile->write
226             if $self->_has_pidfile;
227
228         $self->_run_application;
229     }
230
231
232 }
233
234 sub _plack_loader_args {
235     my ($self) = shift;
236     return (
237         port => $self->port,
238         host => $self->host,
239         keepalive => $self->keepalive ? 100 : 1,
240         server_ready => sub {
241             my ($args) = @_;
242
243             my $name  = $args->{server_software} || ref($args); # $args is $server
244             my $host  = $args->{host} || 0;
245             my $proto = $args->{proto} || 'http';
246
247             print STDERR "$name: Accepting connections at $proto://$host:$args->{port}/\n";
248         },
249     );
250 }
251
252 sub _application_args {
253     my ($self) = shift;
254     return (
255         $self->port,
256         $self->host,
257         {
258            argv => $self->ARGV,
259            map { $_ => $self->$_ } qw/
260                 fork
261                 keepalive
262                 background
263                 pidfile
264                 keepalive
265                 follow_symlinks
266             /,
267         },
268     );
269 }
270
271 __PACKAGE__->meta->make_immutable;
272
273 1;
274
275 =head1 NAME
276
277 Catalyst::Script::Server - Catalyst test server
278
279 =head1 SYNOPSIS
280
281  myapp_server.pl [options]
282
283  Options:
284    -d     --debug          force debug mode
285    -f     --fork           handle each request in a new process
286                       (defaults to false)
287           --help           display this help and exits
288    -h     --host           host (defaults to all)
289    -p     --port           port (defaults to 3000)
290    -k     --keepalive      enable keep-alive connections
291    -r     --restart        restart when files get modified
292                        (defaults to false)
293    --rd   --restart_delay  delay between file checks
294                       (ignored if you have Linux::Inotify2 installed)
295    --rr   --restart_regex  regex match files that trigger
296                       a restart when modified
297                       (defaults to '\.yml$|\.yaml$|\.conf|\.pm$')
298    --rdir --restart_directory  the directory to search for
299                       modified files, can be set multiple times
300                       (defaults to '[SCRIPT_DIR]/..')
301    --sym  --follow_symlinks   follow symlinks in search directories
302                       (defaults to false. this is a no-op on Win32)
303    --bg   --background        run the process in the background
304    --pid  --pidfile           specify filename for pid file
305
306  See also:
307    perldoc Catalyst::Manual
308    perldoc Catalyst::Manual::Intro
309
310 =head1 DESCRIPTION
311
312 Run a Catalyst test server for this application.
313
314 =head1 AUTHORS
315
316 Catalyst Contributors, see Catalyst.pm
317
318 =head1 COPYRIGHT
319
320 This library is free software. You can redistribute it and/or modify
321 it under the same terms as Perl itself.
322
323 =cut