Class::MOP::load_class, is_class_loaded was deprecated in Moose-2.1100
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Script / Server.pm
1 package Catalyst::Script::Server;
2 use Moose;
3 use Catalyst::Utils;
4 use Class::Load qw(try_load_class load_class);
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     my ($success, $error) = try_load_class("MooseX::Daemonize::Pid::File");
53     warn("Could not load MooseX::Daemonize::Pid::File, needed for --pid option: $error\n"),
54         exit 1 if not $success;
55     MooseX::Daemonize::Pid::File->new( file => $_ );
56 };
57 MooseX::Getopt::OptionTypeMap->add_option_type_to_map(
58     'Catalyst::Script::Server::Types::Pidfile' => '=s',
59 );
60 has pidfile => (
61     traits        => [qw(Getopt)],
62     cmd_aliases   => 'pid',
63     isa           => 'Catalyst::Script::Server::Types::Pidfile',
64     is            => 'ro',
65     documentation => 'Specify a pidfile',
66     coerce        => 1,
67     predicate     => '_has_pidfile',
68 );
69
70 # Override MooseX::Daemonize
71 sub dont_close_all_files { 1 }
72 sub BUILD {
73     my $self = shift;
74
75     if ($self->background) {
76         # FIXME - This is evil. Should we just add MX::Daemonize to the deps?
77         my ($success, $error) = try_load_class("MooseX::Daemonize::Core");
78         warn("MooseX::Daemonize is needed for the --background option: $error\n"),
79             exit 1 if not $success;
80         my ($success, $error) = try_load_class("POSIX");
81         warn("$error\n"), exit 1 if not $success;
82         MooseX::Daemonize::Core->meta->apply($self);
83         POSIX::close($_) foreach (0..2);
84     }
85 }
86
87 has keepalive => (
88     traits        => [qw(Getopt)],
89     cmd_aliases   => 'k',
90     isa           => 'Bool',
91     is            => 'ro',
92     default       => 0,
93     documentation => 'Support keepalive',
94 );
95
96 has background => (
97     traits        => [qw(Getopt)],
98     cmd_aliases   => 'bg',
99     isa           => 'Bool',
100     is            => 'ro',
101     default       => 0,
102     documentation => 'Run in the background',
103 );
104
105 has restart => (
106     traits        => [qw(Getopt)],
107     cmd_aliases   => 'r',
108     isa           => 'Bool',
109     is            => 'ro',
110     default       => sub {
111         Catalyst::Utils::env_value(shift->application_name, 'reload') || 0;
112     },
113     documentation => 'use Catalyst::Restarter to detect code changes and restart the application',
114 );
115
116 has restart_directory => (
117     traits        => [qw(Getopt)],
118     cmd_aliases   => [ 'rdir', 'restartdirectory' ],
119     isa           => 'ArrayRef[Str]',
120     is            => 'ro',
121     documentation => 'Restarter directory to watch',
122     predicate     => '_has_restart_directory',
123 );
124
125 has restart_delay => (
126     traits        => [qw(Getopt)],
127     cmd_aliases   => 'rd',
128     isa           => 'Int',
129     is            => 'ro',
130     documentation => 'Set a restart delay',
131     predicate     => '_has_restart_delay',
132 );
133
134 {
135     use Moose::Util::TypeConstraints;
136
137     my $tc = subtype 'Catalyst::Script::Server::Types::RegexpRef', as 'RegexpRef';
138     coerce $tc, from 'Str', via { qr/$_/ };
139
140     MooseX::Getopt::OptionTypeMap->add_option_type_to_map($tc => '=s');
141
142     has restart_regex => (
143         traits        => [qw(Getopt)],
144         cmd_aliases   => 'rr',
145         isa           => $tc,
146         coerce        => 1,
147         is            => 'ro',
148         documentation => 'Restart regex',
149         predicate     => '_has_restart_regex',
150     );
151 }
152
153 has follow_symlinks => (
154     traits        => [qw(Getopt)],
155     cmd_aliases   => 'sym',
156     isa           => 'Bool',
157     is            => 'ro',
158     default       => 0,
159     documentation => 'Follow symbolic links',
160     predicate     => '_has_follow_symlinks',
161 );
162
163 sub _plack_engine_name {
164     my $self = shift;
165     return $self->fork || $self->keepalive ? 'Starman' : 'Standalone';
166 }
167
168 sub _restarter_args {
169     my $self = shift;
170
171     return (
172         argv => $self->ARGV,
173         start_sub => sub { $self->_run_application },
174         ($self->_has_follow_symlinks   ? (follow_symlinks => $self->follow_symlinks)   : ()),
175         ($self->_has_restart_delay     ? (sleep_interval  => $self->restart_delay)     : ()),
176         ($self->_has_restart_directory ? (directories     => $self->restart_directory) : ()),
177         ($self->_has_restart_regex     ? (filter          => $self->restart_regex)     : ()),
178     ),
179     (
180         map { $_ => $self->$_ } qw(application_name host port debug pidfile fork background keepalive)
181     );
182 }
183
184 has restarter_class => (
185     is => 'ro',
186     isa => 'Str',
187     lazy => 1,
188     default => sub {
189         my $self = shift;
190         Catalyst::Utils::env_value($self->application_name, 'RESTARTER') || 'Catalyst::Restarter';
191     }
192 );
193
194 sub run {
195     my $self = shift;
196
197     local $ENV{CATALYST_DEBUG} = 1
198         if $self->debug;
199
200     if ( $self->restart ) {
201         die "Cannot run in the background and also watch for changed files.\n"
202             if $self->background;
203         die "Cannot write out a pid file and fork for the restarter.\n"
204             if $self->_has_pidfile;
205
206         # If we load this here, then in the case of a restarter, it does not
207         # need to be reloaded for each restart.
208         require Catalyst;
209
210         # If this isn't done, then the Catalyst::Devel tests for the restarter
211         # fail.
212         $| = 1 if $ENV{HARNESS_ACTIVE};
213
214         Catalyst::Utils::ensure_class_loaded($self->restarter_class);
215
216         my $subclass = $self->restarter_class->pick_subclass;
217
218         my $restarter = $subclass->new(
219             $self->_restarter_args()
220         );
221
222         $restarter->run_and_watch;
223     }
224     else {
225         if ($self->background) {
226             $self->daemon_fork;
227
228             return 1 unless $self->is_daemon;
229
230             load_class($self->application_name);
231
232             $self->daemon_detach;
233         }
234
235         $self->pidfile->write
236             if $self->_has_pidfile;
237
238         $self->_run_application;
239     }
240
241
242 }
243
244 sub _plack_loader_args {
245     my ($self) = shift;
246     return (
247         port => $self->port,
248         host => $self->host,
249         keepalive => $self->keepalive ? 100 : 1,
250         server_ready => sub {
251             my ($args) = @_;
252
253             my $name  = $args->{server_software} || ref($args); # $args is $server
254             my $host  = $args->{host} || 0;
255             my $proto = $args->{proto} || 'http';
256
257             print STDERR "$name: Accepting connections at $proto://$host:$args->{port}/\n";
258         },
259     );
260 }
261
262 around _application_args => sub {
263     my ($orig, $self) = @_;
264     return (
265         $self->port,
266         $self->host,
267         {
268            %{ $self->$orig },
269            map { $_ => $self->$_ } qw/
270                 fork
271                 keepalive
272                 background
273                 pidfile
274                 keepalive
275                 follow_symlinks
276                 port
277                 host
278             /,
279         },
280     );
281 };
282
283 __PACKAGE__->meta->make_immutable;
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