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