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