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