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