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