PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/MooseX-Daemonize-0.15/lib/MooseX/Daemonize/Core.pm

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