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