3 package MooseX::Daemonize;
6 use MooseX::Types::Path::Class;
7 use File::Path qw(make_path);
8 use namespace::autoclean;
10 with 'MooseX::Daemonize::WithPidFile',
17 metaclass => 'Getopt',
23 ( my $name = lc $_[0]->meta->name ) =~ s/::/_/g;
26 documentation => 'the name of the daemon',
30 metaclass => 'Getopt',
31 isa => 'Path::Class::Dir',
36 default => sub { Path::Class::Dir->new('', 'var', 'run') },
37 documentation => 'the base for our pid (default: /var/run)',
41 metaclass => 'Getopt',
42 isa => 'Path::Class::Dir',
47 default => sub { Path::Class::Dir->new('/') },
48 documentation => 'the directory to chdir to (default: /)',
52 metaclass => 'Getopt',
57 documentation => 'if true, the process won\'t background',
61 metaclass => 'Getopt',
65 documentation => 'number of seconds to wait for the process to stop, before trying harder to kill it (default: 2 s)',
68 # internal book-keeping
70 has status_message => (
71 metaclass => 'NoGetopt',
74 clearer => 'clear_status_message',
78 metaclass => 'NoGetopt',
81 clearer => 'clear_exit_code',
86 ## PID file related stuff ...
90 my $file = $self->pidbase . '/' . $self->progname . '.pid';
92 if ( !-d $self->pidbase ) {
93 make_path( $self->pidbase, { error => \my $err } );
95 confess sprintf( "Cannot create pidbase directory '%s': %s",
96 $self->pidbase, @$err );
100 confess "Cannot write to $file" unless (-e $file ? -w $file : -w $self->pidbase);
101 MooseX::Daemonize::Pid::File->new( file => $file );
105 sub check { (shift)->pidfile->is_running }
106 sub save_pid { (shift)->pidfile->write }
107 sub remove_pid { (shift)->pidfile->remove }
108 sub get_pid { (shift)->pidfile->pid }
110 ## signal handling ...
114 $SIG{'INT'} = sub { $self->shutdown };
115 # I can't think of a sane default here really ...
116 # $SIG{'HUP'} = sub { $self->handle_sighup };
121 $self->pidfile->remove if $self->pidfile->pid == $$;
125 ## daemon control methods ...
130 $self->clear_status_message;
131 $self->clear_exit_code;
133 if ($self->pidfile->is_running) {
134 $self->exit_code($self->OK);
135 $self->status_message('Daemon is already running with pid (' . $self->pidfile->pid . ')');
136 return !($self->exit_code);
139 if ($self->foreground) {
143 eval { $self->daemonize };
145 $self->exit_code($self->ERROR);
146 $self->status_message('Start failed : ' . $@);
147 return !($self->exit_code);
151 unless ($self->is_daemon) {
152 $self->exit_code($self->OK);
153 $self->status_message('Start succeeded');
154 return !($self->exit_code);
157 $self->pidfile->pid($$);
160 chdir $self->basedir;
162 $self->pidfile->write;
163 $self->setup_signals;
170 $self->clear_status_message;
171 $self->clear_exit_code;
173 if ($self->pidfile->is_running) {
174 $self->exit_code($self->OK);
175 $self->status_message('Daemon is running with pid (' . $self->pidfile->pid . ')');
178 $self->exit_code($self->ERROR);
179 $self->status_message('Daemon is not running with pid (' . $self->pidfile->pid . ')');
182 return !($self->exit_code);
188 $self->clear_status_message;
189 $self->clear_exit_code;
191 unless ($self->stop) {
192 $self->exit_code($self->ERROR);
193 $self->status_message('Restart (Stop) failed : ' . $@);
196 unless ($self->start) {
197 $self->exit_code($self->ERROR);
198 $self->status_message('Restart (Start) failed : ' . $@);
201 if ($self->exit_code == $self->OK) {
202 $self->exit_code($self->OK);
203 $self->status_message("Restart successful");
206 return !($self->exit_code);
209 # Make _kill *really* private
215 $self->clear_status_message;
216 $self->clear_exit_code;
218 # if the pid is not running
219 # then we don't need to stop
221 if ($self->pidfile->is_running) {
223 # if we are foreground, then
224 # no need to try and kill
226 unless ($self->foreground) {
228 # kill the process ...
229 eval { $self->$_kill($self->pidfile->pid) };
230 # and complain if we can't ...
232 $self->exit_code($self->ERROR);
233 $self->status_message('Stop failed : ' . $@);
235 # or gloat if we succeed ..
237 $self->exit_code($self->OK);
238 $self->status_message('Stop succeeded');
244 # this just returns the OK
245 # exit code for now, but
246 # we should make this overridable
247 $self->exit_code($self->OK);
248 $self->status_message("Not running");
251 # if we are returning to our script
252 # then we actually need the opposite
253 # of what the system/OS expects
254 return !($self->exit_code);
258 my ( $self, $pid ) = @_;
260 unless ( CORE::kill 0 => $pid ) {
261 # warn "$pid already appears dead.";
266 die "$pid is us! Can't commit suicide.";
269 my $timeout = $self->stop_timeout;
271 # kill 0 => $pid returns 0 if the process is dead
272 # $!{EPERM} could also be true if we cant kill it (permission error)
274 # Try SIGINT ... 2s ... SIGTERM ... 2s ... SIGKILL ... 3s ... UNDEAD!
275 my $terminating_signal;
276 for ( [ 2, $timeout ], [15, $timeout], [9, $timeout * 1.5] ) {
277 my ($signal, $timeout) = @$_;
278 $timeout = int $timeout;
280 CORE::kill($signal, $pid);
283 unless(CORE::kill 0 => $pid or $!{EPERM}) {
284 $terminating_signal = $signal;
288 sleep(1) if $timeout;
291 last if $terminating_signal;
294 if($terminating_signal) {
295 if($terminating_signal == 9) {
296 # clean up the pidfile ourselves iff we used -9 and it worked
297 warn "Had to resort to 'kill -9' and it worked, wiping pidfile";
298 eval { $self->pidfile->remove };
300 warn "Could not remove pidfile ("
301 . $self->pidfile->file
308 # IF it is still running
309 Carp::carp "$pid doesn't seem to want to die."; # AHH EVIL DEAD!
319 MooseX::Daemonize - Role for daemonizing your Moose based application
323 The maintainers of this module now recommend using L<Daemon::Control> instead.
330 with qw(MooseX::Daemonize);
332 # ... define your class ....
336 return unless $self->is_daemon;
337 # your daemon code here ...
340 # then in your script ...
342 my $daemon = My::Daemon->new_with_options();
344 my ($command) = @{$daemon->extra_argv}
345 defined $command || die "No command specified";
347 $daemon->start if $command eq 'start';
348 $daemon->status if $command eq 'status';
349 $daemon->restart if $command eq 'restart';
350 $daemon->stop if $command eq 'stop';
352 warn($daemon->status_message);
353 exit($daemon->exit_code);
357 Often you want to write a persistent daemon that has a pid file, and responds
358 appropriately to Signals. This module provides a set of basic roles as an
359 infrastructure to do that.
363 When going into background MooseX::Daemonize closes all open file
364 handles. This may interfere with you logging because it may also close the log
365 file handle you want to write to. To prevent this you can either defer opening
366 the log file until after start. Alternatively, use can use the
367 'dont_close_all_files' option either from the command line or in your .sh
370 Assuming you want to use Log::Log4perl for example you could expand the
371 MooseX::Daemonize example above like this.
375 return unless $self->is_daemon;
376 Log::Log4perl->init(\$log4perl_config);
377 my $logger = Log::Log4perl->get_logger();
378 $logger->info("Daemon started");
379 # your daemon code here ...
385 This list includes attributes brought in from other roles as well
386 we include them here for ease of documentation. All of these attributes
387 are settable though L<MooseX::Getopt>'s command line handling, with the
388 exception of C<is_daemon>.
392 =item I<progname Path::Class::Dir | Str>
394 The name of our daemon, defaults to C<$package_name =~ s/::/_/>;
396 =item I<pidbase Path::Class::Dir | Str>
398 The base for our PID, defaults to C</var/run/>
400 =item I<basedir Path::Class::Dir | Str>
402 The directory we chdir to; defaults to C</>.
404 =item I<pidfile MooseX::Daemonize::Pid::File | Str>
406 The file we store our PID in, defaults to C<$pidbase/$progname.pid>
408 =item I<foreground Bool>
410 If true, the process won't background. Useful for debugging. This option can
411 be set via Getopt's -f.
413 =item I<no_double_fork Bool>
415 If true, the process will not perform the typical double-fork, which is extra
416 added protection from your process accidentally acquiring a controlling terminal.
417 More information can be found by Googling "double fork daemonize".
419 =item I<ignore_zombies Bool>
421 If true, the process will not clean up zombie processes.
422 Normally you don't want this.
424 =item I<dont_close_all_files Bool>
426 If true, the objects open filehandles will not be closed when daemonized.
427 Normally you don't want this.
430 =item I<is_daemon Bool>
432 If true, the process is the backgrounded daemon process, if false it is the
433 parent process. This is useful for example in an C<after 'start' => sub { }>
436 B<NOTE:> This option is explicitly B<not> available through L<MooseX::Getopt>.
438 =item I<stop_timeout>
440 Number of seconds to wait for the process to stop, before trying harder to kill
441 it. Defaults to 2 seconds.
445 These are the internal attributes, which are not available through MooseX::Getopt.
449 =item I<exit_code Int>
451 =item I<status_message Str>
457 =head2 Daemon Control Methods
459 These methods can be used to control the daemon behavior. Every effort
460 has been made to have these methods DWIM (Do What I Mean), so that you
461 can focus on just writing the code for your daemon.
463 Extending these methods is best done with the L<Moose> method modifiers,
464 such as C<before>, C<after> and C<around>.
470 Setup a pidfile, fork, then setup the signal handlers.
474 Stop the process matching the pidfile, and unlinks the pidfile.
490 =head2 Pidfile Handling Methods
494 =item B<init_pidfile>
496 This method will create a L<MooseX::Daemonize::Pid::File> object and tell
497 it to store the PID in the file C<$pidbase/$progname.pid>.
501 This checks to see if the daemon process is currently running by checking
506 Returns the PID of the daemon process.
518 =head2 Signal Handling Methods
522 =item B<setup_signals>
524 Setup the signal handlers, by default it only sets up handlers for SIGINT and
525 SIGHUP. If you wish to add more signals just use the C<after> method modifier
528 =item B<handle_sigint>
530 Handle a INT signal, by default calls C<$self->stop()>
532 =item B<handle_sighup>
534 Handle a HUP signal. By default calls C<$self->restart()>
538 =head2 Exit Code Methods
540 These are overridable constant methods used for setting the exit code.
560 The C<meta()> method from L<Class::MOP::Class>
566 L<Moose>, L<MooseX::Getopt>, L<MooseX::Types::Path::Class> and L<POSIX>
568 =head1 INCOMPATIBILITIES
570 None reported. Although obviously this will not work on Windows.
572 =head1 BUGS AND LIMITATIONS
574 No bugs have been reported.
576 Please report any bugs or feature requests to
577 C<bug-MooseX-Daemonize@rt.cpan.org>, or through the web interface at
578 L<http://rt.cpan.org>.
582 L<Daemon::Control>, L<Proc::Daemon>, L<Daemon::Generic>
586 Chris Prather C<< <chris@prather.org >>
588 Stevan Little C<< <stevan.little@iinteractive.com> >>
592 Mike Boyko, Matt S. Trout, Stevan Little, Brandon Black, Ash Berlin and the
595 Some bug fixes sponsored by Takkle Inc.
597 =head1 LICENCE AND COPYRIGHT
599 Copyright (c) 2007-2011, Chris Prather C<< <chris@prather.org> >>. Some rights
602 This module is free software; you can redistribute it and/or
603 modify it under the same terms as Perl itself. See L<perlartistic>.
605 =head1 DISCLAIMER OF WARRANTY
607 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
608 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
609 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
610 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
611 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
612 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
613 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
614 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
615 NECESSARY SERVICING, REPAIR, OR CORRECTION.
617 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
618 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
619 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
620 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
621 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
622 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
623 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
624 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
625 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF