rollin, rollin, rollin on the river
[gitmo/MooseX-Daemonize.git] / lib / MooseX / Daemonize.pm
1 package MooseX::Daemonize;
2 use strict;    # because Kwalitee is pedantic
3 use Moose::Role;
4 use MooseX::Types::Path::Class;
5 use Moose::Util::TypeConstraints;
6
7 our $VERSION = 0.05;
8
9 use Carp 'carp';
10 use Proc::Daemon;
11 use MooseX::Daemonize::PidFile;
12
13 with qw[
14     MooseX::Daemonize::Core
15     MooseX::Daemonize::SignalHandling
16     MooseX::Getopt
17 ];
18
19 has progname => (
20     isa      => 'Str',
21     is       => 'ro',
22     lazy     => 1,
23     required => 1,
24     default  => sub {
25         ( my $name = lc $_[0]->meta->name ) =~ s/::/_/g;
26         return $name;
27     },
28 );
29
30 has basedir => (
31     isa      => 'Path::Class::Dir',
32     is       => 'ro',
33     coerce   => 1,
34     required => 1,
35     lazy     => 1,
36     default  => sub { Path::Class::Dir->new('/') },
37 );
38
39 has pidbase => (
40     isa      => 'Path::Class::Dir',
41     is       => 'ro',
42     coerce   => 1,
43     required => 1,    
44     lazy     => 1,
45     default  => sub { Path::Class::Dir->new('var', 'run') },
46 );
47
48 coerce 'MooseX::Daemonize::PidFile' 
49     => from 'Str' 
50         => via { MooseX::Daemonize::PidFile->new( file => $_ ) };
51
52 has pidfile => (
53     isa       => 'MooseX::Daemonize::PidFile',
54     is        => 'rw',
55     lazy      => 1,
56     required  => 1,
57     coerce    => 1,
58     predicate => 'has_pidfile',
59     default   => sub {
60         my $file = $_[0]->pidbase . '/' . $_[0]->progname . '.pid';
61         confess "Cannot write to $file" unless (-e $file ? -w $file : -w $_[0]->pidbase);
62         MooseX::Daemonize::PidFile->new( file => $file );
63     },
64     handles => {
65         check      => 'running',
66         save_pid   => 'write',
67         remove_pid => 'remove',
68         get_pid    => 'pid',
69     },
70 );
71
72 has foreground => (
73     metaclass   => 'Getopt',
74     cmd_aliases => 'f',
75     isa         => 'Bool',
76     is          => 'ro',
77     default     => sub { 0 },
78 );
79
80
81 has stop_timeout => (
82     isa     => 'Int',
83     is      => 'rw',
84     default => sub { 2 }
85 );
86
87 sub start {
88     my ($self) = @_;
89     
90     confess "instance already running" if $self->check;
91     
92     $self->daemonize unless $self->foreground;
93
94     return unless $self->is_daemon;
95
96     $self->pidfile->pid($$);
97
98     # Avoid 'stdin reopened for output' warning with newer perls
99     ## no critic
100     open( NULL, '/dev/null' );
101     <NULL> if (0);
102     ## use critic
103
104     # Change to basedir
105     chdir $self->basedir;
106
107     $self->save_pid;
108     $self->setup_signals;
109     return $$;
110 }
111
112 # Make _kill *really* private
113 my $_kill;
114
115 sub stop {
116     my ( $self, %args ) = @_;
117     my $pid = $self->get_pid;
118     $self->$_kill($pid) unless $self->foreground();
119     $self->remove_pid;
120     return 1 if $args{no_exit};
121     exit;
122 }
123
124 sub restart {
125     my ($self) = @_;
126     $self->stop( no_exit => 1 );
127     $self->start();
128 }
129
130 sub handle_signal {
131     my ($self, $signal) = @_;
132     return $self->handle_sigint if $signal eq 'INT';
133     return $self->handle_sighup if $signal eq 'HUP';    
134 }
135
136 sub handle_sigint { $_[0]->stop; }
137 sub handle_sighup { $_[0]->restart; }
138
139 $_kill = sub {
140     my ( $self, $pid ) = @_;
141     return unless $pid;
142     unless ( CORE::kill 0 => $pid ) {
143
144         # warn "$pid already appears dead.";
145         return;
146     }
147
148     if ( $pid eq $$ ) {
149
150         # warn "$pid is us! Can't commit suicide.";
151         return;
152     }
153
154     my $timeout = $self->stop_timeout;
155
156     # kill 0 => $pid returns 0 if the process is dead
157     # $!{EPERM} could also be true if we cant kill it (permission error)
158
159     # Try SIGINT ... 2s ... SIGTERM ... 2s ... SIGKILL ... 3s ... UNDEAD!
160     for ( [ 2, $timeout ], [15, $timeout], [9, $timeout * 1.5] ) {
161       my ($signal, $timeout) = @$_;
162       $timeout = int $timeout;
163
164       CORE::kill($signal, $pid);
165
166       last unless CORE::kill 0 => $pid or $!{EPERM};
167
168       while ($timeout) {
169         sleep(1);
170         last unless CORE::kill 0 => $pid or $!{EPERM};
171         $timeout--;
172       }
173     }
174
175     return unless ( CORE::kill 0 => $pid or $!{EPERM} );
176
177     # IF it is still running
178     carp "$pid doesn't seem to want to die.";     # AHH EVIL DEAD!
179 };
180
181 1;
182 __END__
183
184 =head1 NAME
185
186 MooseX::Daemonize - provides a Role that daemonizes your Moose based 
187 application.
188
189 =head1 VERSION
190
191 This document describes MooseX::Daemonize version 0.04
192
193 =head1 SYNOPSIS
194
195     package FileMaker;
196     use Moose;
197     with qw(MooseX::Daemonize);
198
199     sub create_file {
200         my ( $self, $file ) = @_;
201         open( FILE, ">$file" ) || die;
202         close(FILE);
203     }
204
205     no Moose;
206
207     # then in the main package ... 
208     
209     my $daemon = FileMaker->new();
210     $daemon->start();
211     $daemon->create_file($file);
212     $daemon->stop();
213      
214 =head1 DESCRIPTION
215
216 Often you want to write a persistant daemon that has a pid file, and responds
217 appropriately to Signals.  This module helps provide the basic infrastructure
218 to do that.
219
220 =head1 ATTRIBUTES
221
222 =over
223
224 =item progname Path::Class::Dir | Str
225
226 The name of our daemon, defaults to $self->meta->name =~ s/::/_/;
227
228 =item pidbase Path::Class::Dir | Str
229
230 The base for our bid, defaults to /var/run/$progname
231
232 =item pidfile MooseX::Daemonize::PidFile | Str
233
234 The file we store our PID in, defaults to /var/run/$progname
235
236 =item foreground Bool
237
238 If true, the process won't background. Useful for debugging. This option can 
239 be set via Getopt's -f.
240
241 =item is_daemon Bool
242
243 If true, the process is the backgrounded process. This is useful for example
244 in an after 'start' => sub { } block
245
246 =item stop_timeout
247
248 Number of seconds to wait for the process to stop, before trying harder to kill
249 it. Defaults to 2 seconds
250
251 =back
252
253 =head1 METHODS 
254
255 =over
256
257 =item check()
258
259 Check to see if an instance is already running.
260
261 =item start()
262
263 Setup a pidfile, fork, then setup the signal handlers.
264
265 =item stop()
266
267 Stop the process matching the pidfile, and unlinks the pidfile.
268
269 =item restart()
270
271 Litterally 
272
273     $self->stop();
274     $self->start();
275
276 =item daemonize()
277
278 Calls C<Proc::Daemon::Init> to daemonize this process. 
279
280 =item setup_signals()
281
282 Setup the signal handlers, by default it only sets up handlers for SIGINT and SIGHUP
283
284 =item handle_sigint()
285
286 Handle a INT signal, by default calls C<$self->stop()>
287
288 =item handle_sighup()
289
290 Handle a HUP signal. By default calls C<$self->restart()>
291
292 =item get_pid
293
294 Lookup the pid from our pidfile.
295
296 =item save_pid
297
298 Save the current pid in our pidfile
299
300 =item remove_pid
301
302 Delete our pidfile
303
304 =item meta()
305
306 The C<meta()> method from L<Class::MOP::Class>
307
308 =back
309
310 =head1 DEPENDENCIES
311
312 =for author to fill in:
313     A list of all the other modules that this module relies upon,
314     including any restrictions on versions, and an indication whether
315     the module is part of the standard Perl distribution, part of the
316     module's distribution, or must be installed separately. ]
317
318 Obviously L<Moose>, and L<Proc::Daemon>
319
320 =head1 INCOMPATIBILITIES
321
322 =for author to fill in:
323     A list of any modules that this module cannot be used in conjunction
324     with. This may be due to name conflicts in the interface, or
325     competition for system or program resources, or due to internal
326     limitations of Perl (for example, many modules that use source code
327     filters are mutually incompatible).
328
329 None reported.
330
331
332 =head1 BUGS AND LIMITATIONS
333
334 =for author to fill in:
335     A list of known problems with the module, together with some
336     indication Whether they are likely to be fixed in an upcoming
337     release. Also a list of restrictions on the features the module
338     does provide: data types that cannot be handled, performance issues
339     and the circumstances in which they may arise, practical
340     limitations on the size of data sets, special cases that are not
341     (yet) handled, etc.
342
343 No bugs have been reported.
344
345 Please report any bugs or feature requests to
346 C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
347 L<http://rt.cpan.org>.
348
349 =head1 SEE ALSO
350
351 L<Proc::Daemon>, L<Daemon::Generic>, L<MooseX::Getopt>
352
353 =head1 AUTHOR
354
355 Chris Prather  C<< <perigrin@cpan.org> >>
356
357 =head1 THANKS
358
359 Mike Boyko, Matt S. Trout, Stevan Little, Brandon Black, Ash Berlin and the 
360 #moose denzians
361
362 Some bug fixes sponsored by Takkle Inc.
363
364 =head1 LICENCE AND COPYRIGHT
365
366 Copyright (c) 2007, Chris Prather C<< <perigrin@cpan.org> >>. All rights 
367 reserved.
368
369 This module is free software; you can redistribute it and/or
370 modify it under the same terms as Perl itself. See L<perlartistic>.
371
372
373 =head1 DISCLAIMER OF WARRANTY
374
375 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
376 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
377 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
378 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
379 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
380 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
381 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
382 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
383 NECESSARY SERVICING, REPAIR, OR CORRECTION.
384
385 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
386 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
387 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
388 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
389 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
390 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
391 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
392 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
393 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
394 SUCH DAMAGES.