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