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