1 package MooseX::Daemonize;
2 use strict; # because Kwalitee is pedantic
4 use MooseX::Types::Path::Class;
8 with 'MooseX::Daemonize::WithPidFile',
15 metaclass => 'Getopt',
21 ( my $name = lc $_[0]->meta->name ) =~ s/::/_/g;
27 metaclass => 'Getopt',
28 isa => 'Path::Class::Dir',
33 default => sub { Path::Class::Dir->new('', 'var', 'run') },
37 metaclass => 'Getopt',
38 isa => 'Path::Class::Dir',
43 default => sub { Path::Class::Dir->new('/') },
47 metaclass => 'Getopt',
55 metaclass => 'Getopt',
61 # internal book-keeping
63 has status_message => (
64 metaclass => 'NoGetopt',
67 clearer => 'clear_status_message',
71 metaclass => 'NoGetopt',
74 clearer => 'clear_exit_code',
79 ## PID file related stuff ...
83 my $file = $self->pidbase . '/' . $self->progname . '.pid';
84 confess "Cannot write to $file" unless (-e $file ? -w $file : -w $self->pidbase);
85 MooseX::Daemonize::Pid::File->new( file => $file );
89 sub check { (shift)->pidfile->is_running }
90 sub save_pid { (shift)->pidfile->write }
91 sub remove_pid { (shift)->pidfile->remove }
92 sub get_pid { (shift)->pidfile->pid }
94 ## signal handling ...
98 $SIG{'INT'} = sub { $self->shutdown };
99 # I can't think of a sane default here really ...
100 # $SIG{'HUP'} = sub { $self->handle_sighup };
105 $self->pidfile->remove if $self->pidfile->pid == $$;
109 ## daemon control methods ...
114 $self->clear_status_message;
115 $self->clear_exit_code;
117 if ($self->pidfile->is_running) {
118 $self->exit_code($self->OK);
119 $self->status_message('Daemon is already running with pid (' . $self->pidfile->pid . ')');
120 return !($self->exit_code);
123 if ($self->foreground) {
127 eval { $self->daemonize };
129 $self->exit_code($self->ERROR);
130 $self->status_message('Start failed : ' . $@);
131 return !($self->exit_code);
135 unless ($self->is_daemon) {
136 $self->exit_code($self->OK);
137 $self->status_message('Start succeeded');
138 return !($self->exit_code);
141 $self->pidfile->pid($$);
144 chdir $self->basedir;
146 $self->pidfile->write;
147 $self->setup_signals;
154 $self->clear_status_message;
155 $self->clear_exit_code;
157 if ($self->pidfile->is_running) {
158 $self->exit_code($self->OK);
159 $self->status_message('Daemon is running with pid (' . $self->pidfile->pid . ')');
162 $self->exit_code($self->ERROR);
163 $self->status_message('Daemon is not running with pid (' . $self->pidfile->pid . ')');
166 return !($self->exit_code);
172 $self->clear_status_message;
173 $self->clear_exit_code;
175 unless ($self->stop) {
176 $self->exit_code($self->ERROR);
177 $self->status_message('Restart (Stop) failed : ' . $@);
180 unless ($self->start) {
181 $self->exit_code($self->ERROR);
182 $self->status_message('Restart (Start) failed : ' . $@);
185 if ($self->exit_code == $self->OK) {
186 $self->exit_code($self->OK);
187 $self->status_message("Restart successful");
190 return !($self->exit_code);
193 # Make _kill *really* private
199 $self->clear_status_message;
200 $self->clear_exit_code;
202 # if the pid is not running
203 # then we dont need to stop
205 if ($self->pidfile->is_running) {
207 # if we are foreground, then
208 # no need to try and kill
210 unless ($self->foreground) {
212 # kill the process ...
213 eval { $self->$_kill($self->pidfile->pid) };
214 # and complain if we can't ...
216 $self->exit_code($self->ERROR);
217 $self->status_message('Stop failed : ' . $@);
219 # or gloat if we succeed ..
221 $self->exit_code($self->OK);
222 $self->status_message('Stop succeeded');
228 # this just returns the OK
229 # exit code for now, but
230 # we should make this overridable
231 $self->exit_code($self->OK);
232 $self->status_message("Not running");
235 # if we are returning to our script
236 # then we actually need the opposite
237 # of what the system/OS expects
238 return !($self->exit_code);
242 my ( $self, $pid ) = @_;
244 unless ( CORE::kill 0 => $pid ) {
245 # warn "$pid already appears dead.";
250 die "$pid is us! Can't commit suicide.";
253 my $timeout = $self->stop_timeout;
255 # kill 0 => $pid returns 0 if the process is dead
256 # $!{EPERM} could also be true if we cant kill it (permission error)
258 # Try SIGINT ... 2s ... SIGTERM ... 2s ... SIGKILL ... 3s ... UNDEAD!
259 my $terminating_signal;
260 for ( [ 2, $timeout ], [15, $timeout], [9, $timeout * 1.5] ) {
261 my ($signal, $timeout) = @$_;
262 $timeout = int $timeout;
264 CORE::kill($signal, $pid);
267 unless(CORE::kill 0 => $pid or $!{EPERM}) {
268 $terminating_signal = $signal;
272 sleep(1) if $timeout;
275 last if $terminating_signal;
278 if($terminating_signal) {
279 if($terminating_signal == 9) {
280 # clean up the pidfile ourselves iff we used -9 and it worked
281 warn "Had to resort to 'kill -9' and it worked, wiping pidfile";
282 eval { $self->pidfile->remove };
284 warn "Could not remove pidfile ("
285 . $self->pidfile->file
292 # IF it is still running
293 Carp::carp "$pid doesn't seem to want to die."; # AHH EVIL DEAD!
303 MooseX::Daemonize - Role for daemonizing your Moose based application
307 This document describes MooseX::Daemonize version 0.05
314 with qw(MooseX::Daemonize);
316 # ... define your class ....
320 return unless $self->is_daemon;
321 # your daemon code here ...
324 # then in your script ...
326 my $daemon = My::Daemon->new_with_options();
328 my ($command) = @{$daemon->extra_argv}
329 defined $command || die "No command specified";
331 $daemon->start if $command eq 'start';
332 $daemon->status if $command eq 'status';
333 $daemon->restart if $command eq 'restart';
334 $daemon->stop if $command eq 'stop';
336 warn($daemon->status_message);
337 exit($daemon->exit_code);
341 Often you want to write a persistant daemon that has a pid file, and responds
342 appropriately to Signals. This module provides a set of basic roles as an
343 infrastructure to do that.
347 This list includes attributes brought in from other roles as well
348 we include them here for ease of documentation. All of these attributes
349 are settable though L<MooseX::Getopt>'s command line handling, with the
350 exception of C<is_daemon>.
354 =item I<progname Path::Class::Dir | Str>
356 The name of our daemon, defaults to C<$package_name =~ s/::/_/>;
358 =item I<pidbase Path::Class::Dir | Str>
360 The base for our bid, defaults to C</var/run/$progname>
362 =item I<pidfile MooseX::Daemonize::Pid::File | Str>
364 The file we store our PID in, defaults to C</var/run/$progname>
366 =item I<foreground Bool>
368 If true, the process won't background. Useful for debugging. This option can
369 be set via Getopt's -f.
371 =item I<is_daemon Bool>
373 If true, the process is the backgrounded daemon process, if false it is the
374 parent process. This is useful for example in an C<after 'start' => sub { }>
377 B<NOTE:> This option is explicitly B<not> available through L<MooseX::Getopt>.
379 =item I<stop_timeout>
381 Number of seconds to wait for the process to stop, before trying harder to kill
382 it. Defaults to 2 seconds.
386 These are the internal attributes, which are not available through MooseX::Getopt.
390 =item I<exit_code Int>
392 =item I<status_message Str>
398 =head2 Daemon Control Methods
400 These methods can be used to control the daemon behavior. Every effort
401 has been made to have these methods DWIM (Do What I Mean), so that you
402 can focus on just writing the code for your daemon.
404 Extending these methods is best done with the L<Moose> method modifiers,
405 such as C<before>, C<after> and C<around>.
411 Setup a pidfile, fork, then setup the signal handlers.
415 Stop the process matching the pidfile, and unlinks the pidfile.
431 =head2 Pidfile Handling Methods
435 =item B<init_pidfile>
437 This method will create a L<MooseX::Daemonize::Pid::File> object and tell
438 it to store the PID in the file C<$pidbase/$progname.pid>.
442 This checks to see if the daemon process is currently running by checking
447 Returns the PID of the daemon process.
459 =head2 Signal Handling Methods
463 =item B<setup_signals>
465 Setup the signal handlers, by default it only sets up handlers for SIGINT and
466 SIGHUP. If you wish to add more signals just use the C<after> method modifier
469 =item B<handle_sigint>
471 Handle a INT signal, by default calls C<$self->stop()>
473 =item B<handle_sighup>
475 Handle a HUP signal. By default calls C<$self->restart()>
479 =head2 Exit Code Methods
481 These are overriable constant methods used for setting the exit code.
501 The C<meta()> method from L<Class::MOP::Class>
507 L<Moose>, L<MooseX::Getopt>, L<MooseX::Types::Path::Class> and L<POSIX>
509 =head1 INCOMPATIBILITIES
511 None reported. Although obviously this will not work on Windows.
513 =head1 BUGS AND LIMITATIONS
515 No bugs have been reported.
517 Please report any bugs or feature requests to
518 C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
519 L<http://rt.cpan.org>.
523 L<Proc::Daemon>, L<Daemon::Generic>
527 Chris Prather C<< <chris@prather.org >>
529 Stevan Little C<< <stevan.little@iinteractive.com> >>
533 Mike Boyko, Matt S. Trout, Stevan Little, Brandon Black, Ash Berlin and the
536 Some bug fixes sponsored by Takkle Inc.
538 =head1 LICENCE AND COPYRIGHT
540 Copyright (c) 2007-2009, Chris Prather C<< <chris@prather.org> >>. Some rights
543 This module is free software; you can redistribute it and/or
544 modify it under the same terms as Perl itself. See L<perlartistic>.
546 =head1 DISCLAIMER OF WARRANTY
548 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
549 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
550 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
551 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
552 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
553 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
554 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
555 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
556 NECESSARY SERVICING, REPAIR, OR CORRECTION.
558 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
559 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
560 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
561 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
562 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
563 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
564 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
565 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
566 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF