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