ok,.. more tests and stuff
[gitmo/MooseX-Daemonize.git] / lib / MooseX / Daemonize.pm
CommitLineData
a4952679 1package MooseX::Daemonize;
a392fa53 2use strict; # because Kwalitee is pedantic
a4952679 3use Moose::Role;
8ac4733f 4use MooseX::Types::Path::Class;
a392fa53 5
d9e417f4 6our $VERSION = 0.05;
a4952679 7
18cc5c89 8with qw[
9 MooseX::Daemonize::Core
ba19d02e 10 MooseX::Daemonize::WithSignalHandling
d9e417f4 11 MooseX::Daemonize::WithPidFile
18cc5c89 12 MooseX::Getopt
13];
a4952679 14
15has progname => (
a392fa53 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 },
a4952679 24);
25
d9e417f4 26has pidbase => (
2eced271 27 isa => 'Path::Class::Dir',
cbff8e52 28 is => 'ro',
2eced271 29 coerce => 1,
d9e417f4 30 required => 1,
cbff8e52 31 lazy => 1,
d9e417f4 32 default => sub { Path::Class::Dir->new('var', 'run') },
24a6a660 33);
34
d9e417f4 35has basedir => (
2eced271 36 isa => 'Path::Class::Dir',
cbff8e52 37 is => 'ro',
2eced271 38 coerce => 1,
d9e417f4 39 required => 1,
cbff8e52 40 lazy => 1,
d9e417f4 41 default => sub { Path::Class::Dir->new('/') },
a4952679 42);
43
44has foreground => (
2eced271 45 metaclass => 'Getopt',
cbff8e52 46 cmd_aliases => 'f',
a4952679 47 isa => 'Bool',
48 is => 'ro',
49 default => sub { 0 },
50);
51
b916501e 52has stop_timeout => (
53 isa => 'Int',
54 is => 'rw',
2eced271 55 default => sub { 2 }
b916501e 56);
57
d9e417f4 58sub 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);
d8985b7d 62 MooseX::Daemonize::Pid::File->new( file => $file );
d9e417f4 63}
64
a4952679 65sub start {
66 my ($self) = @_;
2eced271 67
d8985b7d 68 confess "instance already running" if $self->pidfile->is_running;
2eced271 69
a4952679 70 $self->daemonize unless $self->foreground;
71
8ac4733f 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
cbff8e52 77 return unless $self->is_daemon;
78
79 $self->pidfile->pid($$);
8ac4733f 80
81 # Avoid 'stdin reopened for output'
82 # warning with newer perls
83 open( NULL, '/dev/null' );
84 <NULL> if (0);
cbff8e52 85
24a6a660 86 # Change to basedir
87 chdir $self->basedir;
fa2b72a4 88
ff5cee29 89 $self->pidfile->write;
3543c999 90 $self->setup_signals;
91 return $$;
92}
93
b916501e 94# Make _kill *really* private
95my $_kill;
96
3543c999 97sub stop {
98 my ( $self, %args ) = @_;
ff5cee29 99 my $pid = $self->pidfile->pid;
b916501e 100 $self->$_kill($pid) unless $self->foreground();
ff5cee29 101 $self->pidfile->remove;
3543c999 102 return 1 if $args{no_exit};
103 exit;
104}
105
a4952679 106sub restart {
107 my ($self) = @_;
7ada91b8 108 $self->stop( no_exit => 1 );
a4952679 109 $self->start();
110}
111
18cc5c89 112sub handle_signal {
113 my ($self, $signal) = @_;
114 return $self->handle_sigint if $signal eq 'INT';
115 return $self->handle_sighup if $signal eq 'HUP';
a4952679 116}
117
2361a590 118sub handle_sigint { $_[0]->stop; }
119sub handle_sighup { $_[0]->restart; }
a4952679 120
b916501e 121$_kill = sub {
a4952679 122 my ( $self, $pid ) = @_;
2361a590 123 return unless $pid;
3543c999 124 unless ( CORE::kill 0 => $pid ) {
125
126 # warn "$pid already appears dead.";
127 return;
128 }
129
130 if ( $pid eq $$ ) {
131
b916501e 132 # warn "$pid is us! Can't commit suicide.";
a4952679 133 return;
134 }
135
b916501e 136 my $timeout = $self->stop_timeout;
a4952679 137
b916501e 138 # kill 0 => $pid returns 0 if the process is dead
139 # $!{EPERM} could also be true if we cant kill it (permission error)
a4952679 140
b916501e 141 # Try SIGINT ... 2s ... SIGTERM ... 2s ... SIGKILL ... 3s ... UNDEAD!
142 for ( [ 2, $timeout ], [15, $timeout], [9, $timeout * 1.5] ) {
ea9485d8 143 my ($signal, $timeout) = @$_;
144 $timeout = int $timeout;
145
146 CORE::kill($signal, $pid);
147
b916501e 148 last unless CORE::kill 0 => $pid or $!{EPERM};
ea9485d8 149
150 while ($timeout) {
151 sleep(1);
152 last unless CORE::kill 0 => $pid or $!{EPERM};
153 $timeout--;
154 }
a4952679 155 }
156
b916501e 157 return unless ( CORE::kill 0 => $pid or $!{EPERM} );
158
159 # IF it is still running
d9e417f4 160 Carp::carp "$pid doesn't seem to want to die."; # AHH EVIL DEAD!
b916501e 161};
a4952679 162
1631;
164__END__
165
8ac4733f 166=pod
167
a4952679 168=head1 NAME
169
b916501e 170MooseX::Daemonize - provides a Role that daemonizes your Moose based
171application.
a4952679 172
173=head1 VERSION
174
b916501e 175This document describes MooseX::Daemonize version 0.04
a4952679 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
b916501e 200Often you want to write a persistant daemon that has a pid file, and responds
201appropriately to Signals. This module helps provide the basic infrastructure
202to do that.
a4952679 203
204=head1 ATTRIBUTES
205
206=over
207
2eced271 208=item progname Path::Class::Dir | Str
a4952679 209
cbff8e52 210The name of our daemon, defaults to $self->meta->name =~ s/::/_/;
a4952679 211
2eced271 212=item pidbase Path::Class::Dir | Str
a4952679 213
214The base for our bid, defaults to /var/run/$progname
215
d8985b7d 216=item pidfile MooseX::Daemonize::Pid::File | Str
a4952679 217
2eced271 218The file we store our PID in, defaults to /var/run/$progname
a4952679 219
220=item foreground Bool
221
b916501e 222If true, the process won't background. Useful for debugging. This option can
223be set via Getopt's -f.
a4952679 224
e7a196e7 225=item is_daemon Bool
226
b916501e 227If true, the process is the backgrounded process. This is useful for example
228in an after 'start' => sub { } block
229
230=item stop_timeout
231
232Number of seconds to wait for the process to stop, before trying harder to kill
233it. Defaults to 2 seconds
e7a196e7 234
a4952679 235=back
236
237=head1 METHODS
238
239=over
240
a4952679 241=item start()
242
243Setup a pidfile, fork, then setup the signal handlers.
244
245=item stop()
246
247Stop the process matching the pidfile, and unlinks the pidfile.
248
249=item restart()
250
251Litterally
252
253 $self->stop();
254 $self->start();
255
256=item daemonize()
257
8ac4733f 258Calls daemonize from MooseX::Daemonize::Core.
a4952679 259
a4952679 260=item setup_signals()
261
262Setup the signal handlers, by default it only sets up handlers for SIGINT and SIGHUP
263
264=item handle_sigint()
265
cecbee2d 266Handle a INT signal, by default calls C<$self->stop()>
a4952679 267
268=item handle_sighup()
269
cecbee2d 270Handle a HUP signal. By default calls C<$self->restart()>
a4952679 271
272=item meta()
273
cecbee2d 274The C<meta()> method from L<Class::MOP::Class>
a4952679 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
2eced271 286Obviously L<Moose>, and L<Proc::Daemon>
a4952679 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
297None 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
311No bugs have been reported.
312
313Please report any bugs or feature requests to
314C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
315L<http://rt.cpan.org>.
316
317=head1 SEE ALSO
318
319L<Proc::Daemon>, L<Daemon::Generic>, L<MooseX::Getopt>
320
321=head1 AUTHOR
322
323Chris Prather C<< <perigrin@cpan.org> >>
324
7ada91b8 325=head1 THANKS
326
b916501e 327Mike Boyko, Matt S. Trout, Stevan Little, Brandon Black, Ash Berlin and the
328#moose denzians
a4952679 329
637573c4 330Some bug fixes sponsored by Takkle Inc.
331
a4952679 332=head1 LICENCE AND COPYRIGHT
333
b916501e 334Copyright (c) 2007, Chris Prather C<< <perigrin@cpan.org> >>. All rights
335reserved.
a4952679 336
337This module is free software; you can redistribute it and/or
338modify it under the same terms as Perl itself. See L<perlartistic>.
339
340
341=head1 DISCLAIMER OF WARRANTY
342
343BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
344FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
345OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
346PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
347EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
348WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
349ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
350YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
351NECESSARY SERVICING, REPAIR, OR CORRECTION.
352
353IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
354WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
355REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
356LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
357OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
358THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
359RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
360FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
361SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
362SUCH DAMAGES.
8ac4733f 363
364=cut