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