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