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