1 package MooseX::Daemonize;
2 use strict; # because Kwalitee is pedantic
4 use MooseX::Types::Path::Class;
5 use File::Path qw(make_path);
9 with 'MooseX::Daemonize::WithPidFile',
16 metaclass => 'Getopt',
22 ( my $name = lc $_[0]->meta->name ) =~ s/::/_/g;
25 documentation => 'the name of the daemon',
29 metaclass => 'Getopt',
30 isa => 'Path::Class::Dir',
35 default => sub { Path::Class::Dir->new('', 'var', 'run') },
36 documentation => 'the base for our pid (default: /var/run)',
40 metaclass => 'Getopt',
41 isa => 'Path::Class::Dir',
46 default => sub { Path::Class::Dir->new('/') },
47 documentation => 'the directory to chdir to (default: /)',
51 metaclass => 'Getopt',
56 documentation => 'if true, the process won\'t background',
60 metaclass => 'Getopt',
64 documentation => 'number of seconds to wait for the process to stop, before trying harder to kill it (default: 2 s)',
67 # internal book-keeping
69 has status_message => (
70 metaclass => 'NoGetopt',
73 clearer => 'clear_status_message',
77 metaclass => 'NoGetopt',
80 clearer => 'clear_exit_code',
85 ## PID file related stuff ...
89 my $file = $self->pidbase . '/' . $self->progname . '.pid';
91 if ( !-d $self->pidbase ) {
92 make_path( $self->pidbase, { error => \my $err } );
94 confess sprintf( "Cannot create pidbase directory '%s': %s",
95 $self->pidbase, @$err );
99 confess "Cannot write to $file" unless (-e $file ? -w $file : -w $self->pidbase);
100 MooseX::Daemonize::Pid::File->new( file => $file );
104 sub check { (shift)->pidfile->is_running }
105 sub save_pid { (shift)->pidfile->write }
106 sub remove_pid { (shift)->pidfile->remove }
107 sub get_pid { (shift)->pidfile->pid }
109 ## signal handling ...
113 $SIG{'INT'} = sub { $self->shutdown };
114 # I can't think of a sane default here really ...
115 # $SIG{'HUP'} = sub { $self->handle_sighup };
120 $self->pidfile->remove if $self->pidfile->pid == $$;
124 ## daemon control methods ...
129 $self->clear_status_message;
130 $self->clear_exit_code;
132 if ($self->pidfile->is_running) {
133 $self->exit_code($self->OK);
134 $self->status_message('Daemon is already running with pid (' . $self->pidfile->pid . ')');
135 return !($self->exit_code);
138 if ($self->foreground) {
142 eval { $self->daemonize };
144 $self->exit_code($self->ERROR);
145 $self->status_message('Start failed : ' . $@);
146 return !($self->exit_code);
150 unless ($self->is_daemon) {
151 $self->exit_code($self->OK);
152 $self->status_message('Start succeeded');
153 return !($self->exit_code);
156 $self->pidfile->pid($$);
159 chdir $self->basedir;
161 $self->pidfile->write;
162 $self->setup_signals;
169 $self->clear_status_message;
170 $self->clear_exit_code;
172 if ($self->pidfile->is_running) {
173 $self->exit_code($self->OK);
174 $self->status_message('Daemon is running with pid (' . $self->pidfile->pid . ')');
177 $self->exit_code($self->ERROR);
178 $self->status_message('Daemon is not running with pid (' . $self->pidfile->pid . ')');
181 return !($self->exit_code);
187 $self->clear_status_message;
188 $self->clear_exit_code;
190 unless ($self->stop) {
191 $self->exit_code($self->ERROR);
192 $self->status_message('Restart (Stop) failed : ' . $@);
195 unless ($self->start) {
196 $self->exit_code($self->ERROR);
197 $self->status_message('Restart (Start) failed : ' . $@);
200 if ($self->exit_code == $self->OK) {
201 $self->exit_code($self->OK);
202 $self->status_message("Restart successful");
205 return !($self->exit_code);
208 # Make _kill *really* private
214 $self->clear_status_message;
215 $self->clear_exit_code;
217 # if the pid is not running
218 # then we dont need to stop
220 if ($self->pidfile->is_running) {
222 # if we are foreground, then
223 # no need to try and kill
225 unless ($self->foreground) {
227 # kill the process ...
228 eval { $self->$_kill($self->pidfile->pid) };
229 # and complain if we can't ...
231 $self->exit_code($self->ERROR);
232 $self->status_message('Stop failed : ' . $@);
234 # or gloat if we succeed ..
236 $self->exit_code($self->OK);
237 $self->status_message('Stop succeeded');
243 # this just returns the OK
244 # exit code for now, but
245 # we should make this overridable
246 $self->exit_code($self->OK);
247 $self->status_message("Not running");
250 # if we are returning to our script
251 # then we actually need the opposite
252 # of what the system/OS expects
253 return !($self->exit_code);
257 my ( $self, $pid ) = @_;
259 unless ( CORE::kill 0 => $pid ) {
260 # warn "$pid already appears dead.";
265 die "$pid is us! Can't commit suicide.";
268 my $timeout = $self->stop_timeout;
270 # kill 0 => $pid returns 0 if the process is dead
271 # $!{EPERM} could also be true if we cant kill it (permission error)
273 # Try SIGINT ... 2s ... SIGTERM ... 2s ... SIGKILL ... 3s ... UNDEAD!
274 my $terminating_signal;
275 for ( [ 2, $timeout ], [15, $timeout], [9, $timeout * 1.5] ) {
276 my ($signal, $timeout) = @$_;
277 $timeout = int $timeout;
279 CORE::kill($signal, $pid);
282 unless(CORE::kill 0 => $pid or $!{EPERM}) {
283 $terminating_signal = $signal;
287 sleep(1) if $timeout;
290 last if $terminating_signal;
293 if($terminating_signal) {
294 if($terminating_signal == 9) {
295 # clean up the pidfile ourselves iff we used -9 and it worked
296 warn "Had to resort to 'kill -9' and it worked, wiping pidfile";
297 eval { $self->pidfile->remove };
299 warn "Could not remove pidfile ("
300 . $self->pidfile->file
307 # IF it is still running
308 Carp::carp "$pid doesn't seem to want to die."; # AHH EVIL DEAD!
318 MooseX::Daemonize - Role for daemonizing your Moose based application
322 The maintainers of this module now recommend using L<Daemon::Control> instead.
329 with qw(MooseX::Daemonize);
331 # ... define your class ....
335 return unless $self->is_daemon;
336 # your daemon code here ...
339 # then in your script ...
341 my $daemon = My::Daemon->new_with_options();
343 my ($command) = @{$daemon->extra_argv}
344 defined $command || die "No command specified";
346 $daemon->start if $command eq 'start';
347 $daemon->status if $command eq 'status';
348 $daemon->restart if $command eq 'restart';
349 $daemon->stop if $command eq 'stop';
351 warn($daemon->status_message);
352 exit($daemon->exit_code);
356 Often you want to write a persistant daemon that has a pid file, and responds
357 appropriately to Signals. This module provides a set of basic roles as an
358 infrastructure to do that.
362 When going into background MooseX::Daemonize closes all open file
363 handles. This may interfere with you logging because it may also close the log
364 file handle you want to write to. To prevent this you can either defer opening
365 the log file until after start. Alternatively, use can use the
366 'dont_close_all_files' option either from the command line or in your .sh
369 Assuming you want to use Log::Log4perl for example you could expand the
370 MooseX::Daemonize example above like this.
374 return unless $self->is_daemon;
375 Log::Log4perl->init(\$log4perl_config);
376 my $logger = Log::Log4perl->get_logger();
377 $logger->info("Daemon started");
378 # your daemon code here ...
384 This list includes attributes brought in from other roles as well
385 we include them here for ease of documentation. All of these attributes
386 are settable though L<MooseX::Getopt>'s command line handling, with the
387 exception of C<is_daemon>.
391 =item I<progname Path::Class::Dir | Str>
393 The name of our daemon, defaults to C<$package_name =~ s/::/_/>;
395 =item I<pidbase Path::Class::Dir | Str>
397 The base for our PID, defaults to C</var/run/>
399 =item I<basedir Path::Class::Dir | Str>
401 The directory we chdir to; defaults to C</>.
403 =item I<pidfile MooseX::Daemonize::Pid::File | Str>
405 The file we store our PID in, defaults to C<$pidbase/$progname.pid>
407 =item I<foreground Bool>
409 If true, the process won't background. Useful for debugging. This option can
410 be set via Getopt's -f.
412 =item I<no_double_fork Bool>
414 If true, the process will not perform the typical double-fork, which is extra
415 added protection from your process accidentally aquiring a controlling terminal.
416 More information can be found by Googling "double fork daemonize".
418 =item I<ignore_zombies Bool>
420 If true, the process will not clean up zombie processes.
421 Normally you don't want this.
423 =item I<dont_close_all_files Bool>
425 If true, the objects open filehandles will not be closed when daemonized.
426 Normally you don't want this.
429 =item I<is_daemon Bool>
431 If true, the process is the backgrounded daemon process, if false it is the
432 parent process. This is useful for example in an C<after 'start' => sub { }>
435 B<NOTE:> This option is explicitly B<not> available through L<MooseX::Getopt>.
437 =item I<stop_timeout>
439 Number of seconds to wait for the process to stop, before trying harder to kill
440 it. Defaults to 2 seconds.
444 These are the internal attributes, which are not available through MooseX::Getopt.
448 =item I<exit_code Int>
450 =item I<status_message Str>
456 =head2 Daemon Control Methods
458 These methods can be used to control the daemon behavior. Every effort
459 has been made to have these methods DWIM (Do What I Mean), so that you
460 can focus on just writing the code for your daemon.
462 Extending these methods is best done with the L<Moose> method modifiers,
463 such as C<before>, C<after> and C<around>.
469 Setup a pidfile, fork, then setup the signal handlers.
473 Stop the process matching the pidfile, and unlinks the pidfile.
489 =head2 Pidfile Handling Methods
493 =item B<init_pidfile>
495 This method will create a L<MooseX::Daemonize::Pid::File> object and tell
496 it to store the PID in the file C<$pidbase/$progname.pid>.
500 This checks to see if the daemon process is currently running by checking
505 Returns the PID of the daemon process.
517 =head2 Signal Handling Methods
521 =item B<setup_signals>
523 Setup the signal handlers, by default it only sets up handlers for SIGINT and
524 SIGHUP. If you wish to add more signals just use the C<after> method modifier
527 =item B<handle_sigint>
529 Handle a INT signal, by default calls C<$self->stop()>
531 =item B<handle_sighup>
533 Handle a HUP signal. By default calls C<$self->restart()>
537 =head2 Exit Code Methods
539 These are overriable constant methods used for setting the exit code.
559 The C<meta()> method from L<Class::MOP::Class>
565 L<Moose>, L<MooseX::Getopt>, L<MooseX::Types::Path::Class> and L<POSIX>
567 =head1 INCOMPATIBILITIES
569 None reported. Although obviously this will not work on Windows.
571 =head1 BUGS AND LIMITATIONS
573 No bugs have been reported.
575 Please report any bugs or feature requests to
576 C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
577 L<http://rt.cpan.org>.
581 L<Daemon::Control>, L<Proc::Daemon>, L<Daemon::Generic>
585 Chris Prather C<< <chris@prather.org >>
587 Stevan Little C<< <stevan.little@iinteractive.com> >>
591 Mike Boyko, Matt S. Trout, Stevan Little, Brandon Black, Ash Berlin and the
594 Some bug fixes sponsored by Takkle Inc.
596 =head1 LICENCE AND COPYRIGHT
598 Copyright (c) 2007-2011, Chris Prather C<< <chris@prather.org> >>. Some rights
601 This module is free software; you can redistribute it and/or
602 modify it under the same terms as Perl itself. See L<perlartistic>.
604 =head1 DISCLAIMER OF WARRANTY
606 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
607 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
608 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
609 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
610 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
611 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
612 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
613 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
614 NECESSARY SERVICING, REPAIR, OR CORRECTION.
616 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
617 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
618 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
619 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
620 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
621 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
622 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
623 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
624 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF