RWDE/Runnable.pm untested

filter: Statementstmt 0.0% 0 / 80 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 129 CC 7 SCAR 26.7
CC
7
Cov
0%
Start
42.0
daemonize
6.0
setup
2.0
CRAP 14.4
1 package RWDE::Runnable;
2  
3 use strict;
4 use warnings;
5  
6 use Error qw(:try);
7 use Getopt::Std;
8 use POSIX qw(:sys_wait_h setsid ceil);
9  
10 use RWDE::DB::DbRegistry;
11 use RWDE::Exceptions;
12  
13 use base qw(RWDE::Logging);
14  
15 use vars qw($VERSION);
16 $VERSION = sprintf "%d", q$Revision: 564 $ =~ /(\d+)/;
17  
18 sub Start {
19 my ($self, $params) = @_;
20  
21 # Process command line options:
22 # -d turn on debugging (remains in foreground)
23 # -c number of children to run
24 my %opt = ();
25 getopts('d:s:m:n:c:', \%opt);
26  
27 RWDE::Logger->set_debug()
28 if exists($opt{d});
29  
30 my $runnable = $self->new();
31  
32 $SIG{INT} = sub { $runnable->shutdown() };
33 $SIG{TERM} = sub { $runnable->shutdown() };
34 $SIG{'USR1'} = sub { $self->toggle_debug(); };
35  
36 $runnable->setup(\%opt);
37  
38 my $num_of_children = defined $opt{c} ? $opt{c} : 1;
39  
40 if ($self->is_debug){
41 $runnable->start();
42 }
43 else{
44 for(my $i=1; $i<= $num_of_children; $i++) {
45 my $pid;
46 next if $pid = fork; # Parent goes to next server.
47 if (not defined $pid){
48 $self->syslog_msg('info', "Fork failed: $!");
49 die "fork failed: $!";
50 }
51  
52 # From here on, we're in the child. Do whatever the
53 # child has to do...
54 $self->syslog_msg('info', 'Runnable starting: ' . ref $runnable);
55  
56 $self->daemonize();
57  
58 $runnable->start();
59  
60 exit; # Ends the child process.
61 }
62  
63 }
64 return ();
65 }
66  
67 sub setup {
68 my ($self, $params) = @_;
69  
70 #give subclasses a chance to setup
71  
72 return ();
73 }
74  
75 sub start {
76 my ($self, $params) = @_;
77  
78 throw RWDE::DevelException({ info => 'start has to be overriden, no work to be done in the abstract clas' });
79  
80 return ();
81 }
82  
83 sub shutdown {
84 my ($self, $params) = @_;
85  
86 $self->syslog_msg('info', 'Closing...');
87  
88 try {
89 my $registry = RWDE::DB::DbRegistry->get_instance();
90 $registry->cleanup();
91 }
92  
93 catch Error with {
94 my $ex = shift;
95  
96 $self->syslog_msg('info', 'Closing...' . $ex);
97 };
98  
99 exit(0);
100 }
101  
102 # daemonize: From perlipc man page, fork into background and redirect input and output to dev/null
103 sub daemonize {
104 chdir '/' or die "Can't chdir to /: $!";
105 open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
106 open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
107 defined(my $pid = fork) or die "Can't fork: $!";
108 exit if $pid; # parent exits...
109 setsid or die "Can't start a new session: $!";
110 open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
111 return;
112 }
113  
114 1;