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