prep for release
[gitmo/MooseX-Daemonize.git] / lib / MooseX / Daemonize / Core.pm
CommitLineData
18cc5c89 1package MooseX::Daemonize::Core;
4327fe98 2use strict; # cause Perl::Critic errors are annoying
3use MooseX::Getopt; # to load the NoGetopt metaclass
18cc5c89 4use Moose::Role;
5
61d0473c 6our $VERSION = '0.16';
18cc5c89 7
ea9485d8 8use POSIX ();
18cc5c89 9
10has is_daemon => (
4327fe98 11 # NOTE:
12 # this should never be accessible
13 # from the command line
14 # - SL
15 metaclass => 'NoGetopt',
16 isa => 'Bool',
17 is => 'rw',
18 default => sub { 0 },
18cc5c89 19);
20
2ecc2ccb 21has ignore_zombies => (
22 metaclass => 'Getopt',
23 isa => 'Bool',
24 is => 'rw',
25 default => sub { 0 },
26);
27
28has no_double_fork => (
29 metaclass => 'Getopt',
30 isa => 'Bool',
31 is => 'rw',
32 default => sub { 0 },
33);
34
35has dont_close_all_files => (
36 metaclass => 'Getopt',
37 isa => 'Bool',
38 is => 'rw',
39 default => sub { 0 },
40);
41
42sub _get_options {
43 my ($self, %options) = @_;
44 # backwards compability.. old code might be calling daemon_fork/_detach with options
45 foreach my $opt (qw( ignore_zombies no_double_fork dont_close_all_files )) {
46 $self->$opt( $options{ $opt } ) if ( defined $options{ $opt } );
47 }
48}
49
50
d8985b7d 51sub daemon_fork {
52 my ($self, %options) = @_;
53
2ecc2ccb 54 $self->_get_options( %options );
55
d8985b7d 56 $SIG{CHLD} = 'IGNORE'
2ecc2ccb 57 if $self->ignore_zombies;;
d8985b7d 58
129f5643 59 if (my $pid = fork) {
60 return $pid;
61 }
62 else {
289fcbc7 63 $self->is_daemon(1);
129f5643 64 return;
65 }
66}
d8985b7d 67
68sub daemon_detach {
69 my ($self, %options) = @_;
70
71 return unless $self->is_daemon; # return if parent ...
72
2ecc2ccb 73 $self->_get_options( %options );
d8985b7d 74 # now we are in the daemon ...
75
129f5643 76 (POSIX::setsid) # set session id
d8985b7d 77 || confess "Cannot detach from controlling process";
78
2ecc2ccb 79 unless ( $self->no_double_fork ) {
d8985b7d 80 $SIG{'HUP'} = 'IGNORE';
81 fork && exit;
82 }
83
ea9485d8 84 chdir '/'; # change to root directory
d8985b7d 85 umask 0; # clear the file creation mask
86
2ecc2ccb 87 unless ( $self->dont_close_all_files ) {
3c0d9597 88 # get the max numnber of possible file descriptors
89 my $openmax = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
90 $openmax = 64 if !defined($openmax) || $openmax < 0;
d8985b7d 91
3c0d9597 92 # close them all
93 POSIX::close($_) foreach (0 .. $openmax);
94 }
ea9485d8 95
4327fe98 96 # fixup STDIN ...
97
98 open(STDIN, "+>/dev/null")
99 or confess "Could not redirect STDOUT to /dev/null";
100
101 # fixup STDOUT ...
d8985b7d 102
129f5643 103 if (my $stdout_file = $ENV{MX_DAEMON_STDOUT}) {
d8985b7d 104 open STDOUT, ">", $stdout_file
129f5643 105 or confess "Could not redirect STDOUT to $stdout_file : $!";
106 }
107 else {
4327fe98 108 open(STDOUT, "+>&STDIN")
109 or confess "Could not redirect STDOUT to /dev/null";
129f5643 110 }
111
4327fe98 112 # fixup STDERR ...
113
d8985b7d 114 if (my $stderr_file = $ENV{MX_DAEMON_STDERR}) {
3c0d9597 115 open STDERR, ">", $stderr_file
d8985b7d 116 or confess "Could not redirect STDERR to $stderr_file : $!";
129f5643 117 }
d8985b7d 118 else {
4327fe98 119 open(STDERR, "+>&STDIN")
120 or confess "Could not redirect STDERR to /dev/null"; ;
121 }
122
123 # do a little house cleaning ...
124
125 # Avoid 'stdin reopened for output'
126 # warning with newer perls
127 open( NULL, '/dev/null' );
128 <NULL> if (0);
129
130 # return success
131 return 1;
ea9485d8 132}
18cc5c89 133
134sub daemonize {
d8985b7d 135 my ($self, %options) = @_;
136 $self->daemon_fork(%options);
137 $self->daemon_detach(%options);
18cc5c89 138}
139
1401;
d8985b7d 141
18cc5c89 142__END__
143
d8985b7d 144=pod
18cc5c89 145
d8985b7d 146=head1 NAME
18cc5c89 147
d8985b7d 148MooseX::Daemonize::Core - A Role with the core daemonization features
18cc5c89 149
150=head1 SYNOPSIS
d8985b7d 151
152 package My::Daemon;
153 use Moose;
4327fe98 154
d8985b7d 155 with 'MooseX::Daemonize::Core';
4327fe98 156
d8985b7d 157 sub start {
158 my $self = shift;
159 # daemonize me ...
160 $self->daemonize;
161 # return from the parent,...
162 return unless $self->is_daemon;
163 # but continue on in the child (daemon)
164 }
165
18cc5c89 166=head1 DESCRIPTION
167
4327fe98 168This is the basic daemonization Role, it provides a few methods (see
d8985b7d 169below) and the minimum features needed to properly daemonize your code.
170
171=head2 Important Notes
129f5643 172
d8985b7d 173None of the methods in this role will exit the parent process for you,
174it only forks and detaches your child (daemon) process. It is your
175responsibility to exit the parent process in some way.
176
4327fe98 177There is no PID or PID file management in this role, that is your
178responsibility (see some of the other roles in this distro for that).
129f5643 179
18cc5c89 180=head1 ATTRIBUTES
181
182=over
183
129f5643 184=item I<is_daemon (is => rw, isa => Bool)>
18cc5c89 185
d8985b7d 186This attribute is used to signal if we are within the
187daemon process or not.
18cc5c89 188
2ecc2ccb 189=item I<no_double_fork (is => rw, isa => Bool)>
190
191Setting this attribute to true will cause this method to not perform the
192typical double-fork, which is extra added protection from your process
193accidentally aquiring a controlling terminal. More information can be
194found above, and by Googling "double fork daemonize".
195
196If you the double-fork behavior off, you might want to enable the
197I<ignore_zombies>.
198
199=item I<ignore_zombies (is => rw, isa => Bool)>
200
201Setting this attribute to a true value will result in setting the C<$SIG{CHLD}>
202handler to C<IGNORE>. This tells perl to clean up zombie processes. By
203default, and for the most part you don't I<need> it, only when you turn off
204the double fork behavior (with the I<no_double_fork> attribute)
205do you sometimes want this behavior.
206
207=item I<dont_close_all_files (is => rw, isa => Bool)>
208
209Setting this attribute to true will cause it to skip closing all the
210filehandles. This is useful if you are opening things like sockets
211and such in the pre-fork.
212
18cc5c89 213=back
214
d8985b7d 215=head1 METHODS
18cc5c89 216
217=over
218
2ecc2ccb 219=item B<daemon_fork (?%options)>
129f5643 220
d8985b7d 221This forks off the child process to be daemonized. Just as with
222the built in fork, it returns the child pid to the parent process,
2230 to the child process. It will also set the is_daemon flag
129f5643 224appropriately.
225
2ecc2ccb 226The C<%options> argument remains for backwards compatability, but
227it is suggested that you use the attributes listed above instead.
d8985b7d 228
2ecc2ccb 229=item B<daemon_detach (?%options)>
129f5643 230
d8985b7d 231This detaches the new child process from the terminal by doing
232the following things.
129f5643 233
2ecc2ccb 234The C<%options> argument remains for backwards compatability, but
235it is suggested that you use the attributes listed above instead.
236
129f5643 237=over 4
238
d8985b7d 239=item Becomes a session leader
18cc5c89 240
d8985b7d 241This detaches the program from the controlling terminal, it is
129f5643 242accomplished by calling POSIX::setsid.
18cc5c89 243
d8985b7d 244=item Performing the double-fork
245
246See below for information on how to change this part of the process.
247
129f5643 248=item Changes the current working directory to "/"
18cc5c89 249
d8985b7d 250This is standard daemon behavior, if you want a different working
251directory then simply change it later in your daemons code.
18cc5c89 252
129f5643 253=item Clears the file creation mask.
18cc5c89 254
129f5643 255=item Closes all open file descriptors.
18cc5c89 256
2ecc2ccb 257See the I<dont_close_all_files> attribute for information on how to
258change this part of the process.
3c0d9597 259
129f5643 260=item Reopen STDERR, STDOUT & STDIN to /dev/null
18cc5c89 261
d8985b7d 262This behavior can be controlled slightly though the MX_DAEMON_STDERR
129f5643 263and MX_DAEMON_STDOUT environment variables. It will look for a filename
264in either of these variables and redirect STDOUT and/or STDERR to those
265files. This is useful for debugging and/or testing purposes.
18cc5c89 266
d8985b7d 267B<NOTE>
268
269If called from within the parent process (the is_daemon flag is set to
270false), this method will simply return and do nothing.
271
2ecc2ccb 272=item B<daemonize (?%options)>
273
274This will simply call C<daemon_fork> followed by C<daemon_detach>.
d8985b7d 275
2ecc2ccb 276The C<%options> argument remains for backwards compatability, but
277it is suggested that you use the attributes listed above instead.
18cc5c89 278
279=item meta()
280
281The C<meta()> method from L<Class::MOP::Class>
282
283=back
284
d8985b7d 285=head1 STUFF YOU SHOULD READ
286
287=over 4
288
289=item Note about double fork
290
291Taken from L<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012>
4327fe98 292in a comment entitled I<The second fork _is_ necessary by Jonathan Bartlett>,
293it is not the definitive statement on the issue, but it's clear and well
d8985b7d 294written enough so I decided to reproduce it here.
295
296 The first fork accomplishes two things - allow the shell to return,
297 and allow you to do a setsid().
298
299 The setsid() removes yourself from your controlling terminal. You
300 see, before, you were still listed as a job of your previous process,
301 and therefore the user might accidentally send you a signal. setsid()
302 gives you a new session, and removes the existing controlling terminal.
303
304 The problem is, you are now a session leader. As a session leader, if
305 you open a file descriptor that is a terminal, it will become your
306 controlling terminal (oops!). Therefore, the second fork makes you NOT
307 be a session leader. Only session leaders can acquire a controlling
308 terminal, so you can open up any file you wish without worrying that
309 it will make you a controlling terminal.
310
311 So - first fork - allow shell to return, and permit you to call setsid()
312
313 Second fork - prevent you from accidentally reacquiring a controlling
314 terminal.
315
316That said, you don't always want this to be the behavior, so you are
2ecc2ccb 317free to specify otherwise using the I<no_double_fork> attribute.
d8985b7d 318
319=item Note about zombies
320
321Doing the double fork (see above) tends to get rid of your zombies since
4327fe98 322by the time you have double forked your daemon process is then owned by
323the init process. However, sometimes the double-fork is more than you
d8985b7d 324really need, and you want to keep your daemon processes a little closer
325to you. In this case you have to watch out for zombies, you can avoid then
2ecc2ccb 326by just setting the I<ignore_zombies> attribute (see above).
d8985b7d 327
328=back
329
330=head1 ENVIRONMENT VARIABLES
331
4327fe98 332These variables are best just used for debugging and/or testing, but
333not used for actual logging. For that, you should reopen STDOUT/ERR on
334your own.
d8985b7d 335
336=over 4
337
338=item B<MX_DAEMON_STDOUT>
339
340A filename to redirect the daemon STDOUT to.
341
342=item B<MX_DAEMON_STDERR>
343
344A filename to redirect the daemon STDERR to.
345
346=back
347
18cc5c89 348=head1 DEPENDENCIES
349
129f5643 350L<Moose::Role>, L<POSIX>
18cc5c89 351
352=head1 INCOMPATIBILITIES
353
18cc5c89 354None reported.
355
18cc5c89 356=head1 BUGS AND LIMITATIONS
357
18cc5c89 358No bugs have been reported.
359
360Please report any bugs or feature requests to
361C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
362L<http://rt.cpan.org>.
363
364=head1 SEE ALSO
365
129f5643 366L<Proc::Daemon>
367
d8985b7d 368This code is based B<HEAVILY> on L<Proc::Daemon>, we originally
129f5643 369depended on it, but we needed some more flexibility, so instead
d8985b7d 370we just stole the code.
18cc5c89 371
372=head1 AUTHOR
373
129f5643 374Stevan Little C<< <stevan.little@iinteractive.com> >>
18cc5c89 375
18cc5c89 376=head1 LICENCE AND COPYRIGHT
377
05b96f4d 378Copyright (c) 2007-2011, Chris Prather C<< <perigrin@cpan.org> >>. All rights
18cc5c89 379reserved.
380
129f5643 381Portions heavily borrowed from L<Proc::Daemon> which is copyright Earl Hood.
382
18cc5c89 383This module is free software; you can redistribute it and/or
384modify it under the same terms as Perl itself. See L<perlartistic>.
385
18cc5c89 386=head1 DISCLAIMER OF WARRANTY
387
388BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
389FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
390OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
391PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
392EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
393WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
394ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
395YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
396NECESSARY SERVICING, REPAIR, OR CORRECTION.
397
398IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
399WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
400REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
401LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
402OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
403THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
404RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
405FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
406SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
407SUCH DAMAGES.
d8985b7d 408
409=cut