blib/lib/Mojo/Run.pm

filter: Statementstmt 20.5% 61 / 297 Branchbran 0.0% 0 / 126 Conditioncond 0.0% 0 / 108 MC/DCmcdc 0.0% 0 / 49 Subroutinesub 40.9% 18 / 44 Podpod 9.0% 1 / 11 totaltotal 12.6% 80 / 635 CC 98 SCAR 49.5
CC
98
Cov
11%
spawn
380.0
complete
306.0
_validateRunStruct
302.6
CRAP 141.6
↑ Summary
1 package Mojo::Run;
2  
3 1 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Errno;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Time::HiRes qw(time gettimeofday);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Storable qw(thaw nfreeze);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use POSIX ":sys_wait_h";
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Mojo::Log;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Mojo::Reactor;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 0 ▶has 'num_forks' => sub { 0 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
18 0 ▶has 'max_forks' => sub { 0 };
Subroutine __ANON__: not called CC=1 SCAR=1.2
19 0 ▶has 'log' => sub { Mojo::Log ->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
20 0 ▶has 'ioloop' => sub { Mojo::IOLoop->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
21 1 has [qw/reactor error is_child/];
22  
23 1 our $VERSION = '0.3';
24  
25 1 my $_obj = undef;
26  
27 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=4.7
28 0 ▶ *portable_pipe = sub () { my ($r, $w);
Subroutine __ANON__: not called CC=2 SCAR=17.9
29 0 ▶ pipe $r, $w or return;
Branch: 1 branch
BranchTrueFalseTotal
pipe $r, $w or return 0 0 0
30
31 0 ($r, $w);
32 1 };
33 0 ▶ *portable_socketpair = sub () {
Subroutine __ANON__: not called CC=2 SCAR=17.9
34 0 ▶ socketpair my $fh1, my $fh2, Socket::AF_UNIX(), Socket::SOCK_STREAM(), PF_UNSPEC
Branch: 1 branch
BranchTrueFalseTotal
socketpair my $fh1, my $fh2, 1, 1, 0 or return 0 0 0
35 or return;
36 0 $fh1->autoflush(1);
37 0 $fh2->autoflush(1);
38
39 0 ($fh1, $fh2)
40 1 };
41 }
42  
43 0 ▶sub new { __PACKAGE__->singleton }
Subroutine new: not called CC=1 SCAR=6.9
Pod documented
44  
45 0 ▶sub singleton {
Subroutine singleton: not called CC=2 SCAR=17.9
Pod undocumented
46 0 ▶ return $_obj if defined $_obj;
Branch: 1 branch
BranchTrueFalseTotal
if defined $_obj 0 0 0
47 0 return $_obj = __PACKAGE__->_constructor;
48 }
49  
50 0 ▶sub _constructor {
Subroutine _constructor: not called CC=2 SCAR=17.9
51 0 my $proto = shift;
52 0 ▶ my $class = ref($proto) || $proto;
Condition0%0/3
ref $proto || $proto
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table0%0/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
53 0 my $self = $class->SUPER::new;
54  
55 0 bless $self => $class;
56
57 # install SIGCHLD handler
58 0 ▶ $SIG{'CHLD'} = sub { _sig_chld($self, @_) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
59
60 0 return $self;
61 }
62  
63 0 ▶sub log_level {
Subroutine log_level: not called CC=2 SCAR=17.9
Pod undocumented
64 0 my ($self, $level) = @_;
65
66 0 ▶ $self->log->level($level) if defined $level;
Branch: 1 branch
BranchTrueFalseTotal
if defined $level 0 0 0
67
68 0 return $self->log->level;
69 }
70  
71 0 ▶sub spawn {
Subroutine spawn: not called CC=19 SCAR=59.4
Pod undocumented
72 0 my ($self, %opt) = @_;
73
74 0 ▶ unless (defined $self && blessed($self) && $self->isa(__PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self and builtin::blessed($self) and $self->isa(__PACKAGE__)) 0 0 0
Condition0%0/6
defined $self and builtin::blessed($self) and $self->isa(__PACKAGE__)
!ll&&!rl&&r
000
defined $self and builtin::blessed($self)
!ll&&!rl&&r
000
MC/DC0%0/3
defined $self and builtin::blessed($self) and $self->isa(__PACKAGE__)
defined $self builtin::blessed($self) $self->isa(__PACKAGE__)
Truth table0%0/4
A and B and C
A= defined $selfB= builtin::blessed($self)C= $self->isa(__PACKAGE__)
ABCresult
0XX0
10X0
1100
1111
75 0 my $obj = __PACKAGE__->new;
76 0 return $obj->spawn(%opt);
77 }
78
79 0 $self->error('');
80
81 0 ▶ if ($self->max_forks > 0 && $self->num_forks >= $self->max_forks) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->max_forks > 0 and $self->num_forks >= $self->max_forks) 0 0 0
Condition0%0/3
$self->max_forks > 0 and $self->num_forks >= $self->max_forks
!ll&&!rl&&r
000
MC/DC0%0/2
$self->max_forks > 0 and $self->num_forks >= $self->max_forks
$self->max_forks > 0 $self->num_forks >= $self->max_forks
Truth table0%0/3
A and B
A= $self->max_forks > 0B= $self->num_forks >= $self->max_forks
ABresult
0X0
100
111
82 0 $self->error("Unable to spawn another subprocess: "
83 ."Limit of " . $self->max_forks . " concurrently spawned process(es) is reached."
84 );
85 0 return 0;
86 }
87
88 # normalize and validate run parameters...
89 0 my $proc = $self->_getRunStruct(\%opt);
90 0 ▶ return 0 unless $self->_validateRunStruct($proc);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_validateRunStruct($proc) 0 0 0
91
92 $self->log->debug("Spawning command "
93 ."timeout: "
94 0 ▶ .($proc->{exec_timeout} > 0 ? sprintf("%-.3f seconds]", $proc->{exec_timeout}) : "none")
Branch: 1 branch
BranchTrueFalseTotal
$proc->{'exec_timeout'} > 0 ? : 0 0 0
95 ." : [$proc->{cmd}]"
96 );
97 0 my ($stdout_p, $stdout_c) = portable_socketpair;
98 0 my ($stderr_p, $stderr_c) = portable_socketpair;
99 0 my ($stdres_p, $stdres_c) = portable_socketpair;
100
101 0 $proc->{time_started} = time;
102 0 $proc->{running } = 1;
103 0 $proc->{hdr_stdout } = $stdout_c;
104 0 $proc->{hdr_stderr } = $stderr_c;
105 0 $proc->{hdr_stdres } = $stdres_c;
106
107 0 my $pid = fork;
108
109 0 ▶ if ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) { } 0 0 0
110 # parent
111 0 $self->num_forks($self->num_forks + 1);
112
113 0 $self->log->debug("Subprocess spawned as pid $pid.");
114
115 0 $proc->{pid} = $pid;
116
117 # exec timeout
118 0 ▶ if (defined $proc->{exec_timeout} && $proc->{exec_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $proc->{"exec_timeout"} and $proc->{"exec_timeout"} > 0) 0 0 0
Condition0%0/3
defined $proc->{"exec_timeout"} and $proc->{"exec_timeout"} > 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $proc->{"exec_timeout"} and $proc->{"exec_timeout"} > 0
defined $proc->{"exec_timeout"} $proc->{"exec_timeout"} > 0
Truth table0%0/3
A and B
A= defined $proc->{"exec_timeout"}B= $proc->{"exec_timeout"} > 0
ABresult
0X0
100
111
119 $self->log->debug(
120 "[process $pid]: Setting execution timeout to " .
121 sprintf("%-.3f seconds.", $proc->{exec_timeout})
122 0 );
123 my $timer = $self->ioloop->timer(
124 $proc->{exec_timeout},
125 0 ▶ sub { _timeout_cb($self, $pid) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
126 0 );
127
128 # save timer
129 0 $proc->{id_timeout} = $timer;
130 }
131
132 0 $self->{_data}->{$pid} = $proc;
133
134 0 close $stdout_p;
135 0 close $stderr_p;
136 0 close $stdres_p;
137
138 0 $self->watch('stdout', $pid);
139 0 $self->watch('stderr', $pid);
140 0 $self->watch('stdres', $pid);
141 } else {
142 # child
143
144 0 $self->is_child(1);
145
146 0 close $stdout_c;
147 0 close $stderr_c;
148 0 close $stdres_c;
149
150 # Stdio should not be tied.
151 0 ▶ if (tied *STDOUT) {
Branch: 1 branch
BranchTrueFalseTotal
if (tied *STDOUT) 0 0 0
152 0 carp "Cannot redirect into tied STDOUT. Untying it";
153 0 untie *STDOUT;
154 }
155 0 ▶ if (tied *STDERR) {
Branch: 1 branch
BranchTrueFalseTotal
if (tied *STDERR) 0 0 0
156 0 carp "Cannot redirect into tied STDERR. Untying it";
157 0 untie *STDERR;
158 }
159
160 # Redirect STDOUT
161 0 ▶ open STDOUT, ">&" . fileno($stdout_p)
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, '>&' . fileno($stdout_p) or croak("can't redirect stdout in child pid ${$}: $!") 0 0 0
162 or croak "can't redirect stdout in child pid $$: $!";
163 # Redirect STDERR
164 0 ▶ open STDERR, ">&" . fileno($stderr_p)
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, '>&' . fileno($stderr_p) or croak("can't redirect stderr in child pid ${$}: $!") 0 0 0
165 or croak "can't redirect stderr in child pid $$: $!";
166  
167 0 select STDERR; $| = 1;
168 0 select STDOUT; $| = 1;
169
170 0 ▶ if (ref $proc->{cmd} eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $proc->{'cmd'} eq 'CODE') { } 0 0 0
171 0 my @rv = eval { $proc->{cmd}->($$, $proc->{param}); };
172
173 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
174 0 carp "exec of coderef failed: $@\n";
175 0 exit 255;
176 }
177
178 0 print $stdres_p nfreeze(\ @rv);
179
180 } else {
181 0 ▶ exec(ref $proc->{cmd} eq 'ARRAY' ? @{ $proc->{cmd} } : $proc->{cmd}) or do {
Branch: 2 branches
BranchTrueFalseTotal
exec ref $proc->{"cmd"} eq "ARRAY" ? @{$proc->{"cmd"};} : $proc->{"cmd"} or do { carp("exec failed"); exit 255 } 0 0 0
ref $proc->{'cmd'} eq 'ARRAY' ? : 0 0 0
182 0 carp "exec failed";
183 0 exit 255;
184 };
185 }
186
187 0 close $stdout_p;
188 0 close $stderr_p;
189 0 close $stdres_p;
190
191 0 exit 1;
192 }
193
194 0 return $pid;
195 }
196  
197 0 ▶sub start { shift->ioloop->start }
Subroutine start: not called CC=1 SCAR=6.9
Pod undocumented
198  
199 0 ▶sub watch {
Subroutine watch: not called CC=8 SCAR=42.8
Pod undocumented
200 0 my $self = shift;
201 0 ▶ my $io = lc(shift || '');
Condition0%0/2
shift() || ''
l!l
00
MC/DC0%0/1
shift() || ''
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
202 0 my $pid = shift;
203
204 0 my $proc = $self->get_proc($pid);
205
206 0 ▶ $self->log->error('Cant start IO watcher off NULL process' ) and return unless $proc;
Branch: 1 branch
BranchTrueFalseTotal
unless $proc 0 0 0
Condition0%0/5
$proc || $self->log->error('Cant start IO watcher off NULL process') && (return)
l!l&&r!l&&!r
000
$self->log->error("Cant start IO watcher off NULL process") and return
!ll
00
MC/DC0%0/2
$proc || $self->log->error('Cant start IO watcher off NULL process') && (return)
$proc $self->log->error("Cant start IO watcher off NULL process")
Truth table0%0/3
A || B
A= $procB= $self->log->error("Cant start IO watcher off NULL process")
ABresult
1X1
011
000
207 0 ▶ $self->log->error("[process $proc->{pid}]: IO ($io) is unsupported" ) and return unless $io ~~ [qw/stdout stderr stdres/];
Branch: 1 branch
BranchTrueFalseTotal
unless $io ~~ ["stdout", "stderr", "stdres"] 0 0 0
Condition0%0/5
$io ~~ ['stdout', 'stderr', 'stdres'] || $self->log->error("[process $proc->{'pid'}]: IO ($io) is unsupported") && (return)
l!l&&r!l&&!r
000
$self->log->error(qq[[process $proc->{"pid"}]: IO ($io) is unsupported]) and return
!ll
00
MC/DC0%0/2
$io ~~ ['stdout', 'stderr', 'stdres'] || $self->log->error("[process $proc->{'pid'}]: IO ($io) is unsupported") && (return)
$io ~~ ['stdout', 'stderr', 'stdres'] $self->log->error(qq[[process $proc->{"pid"}]: IO ($io) is unsupported])
Truth table0%0/3
A || B
A= $io ~~ ['stdout', 'stderr', 'stdres']B= $self->log->error(qq[[process $proc->{"pid"}]: IO ($io) is unsupported])
ABresult
1X1
011
000
208 0 ▶ $self->log->error("[process $proc->{pid}]: IO handler ($io) is EMPTY") and return unless $proc->{"hdr_$io"};
Branch: 1 branch
BranchTrueFalseTotal
unless $$proc{"hdr_$io"} 0 0 0
Condition0%0/5
$$proc{"hdr_$io"} || $self->log->error("[process $proc->{'pid'}]: IO handler ($io) is EMPTY") && (return)
l!l&&r!l&&!r
000
$self->log->error(qq[[process $proc->{"pid"}]: IO handler ($io) is EMPTY]) and return
!ll
00
MC/DC0%0/2
$$proc{"hdr_$io"} || $self->log->error("[process $proc->{'pid'}]: IO handler ($io) is EMPTY") && (return)
$$proc{"hdr_$io"} $self->log->error(qq[[process $proc->{"pid"}]: IO handler ($io) is EMPTY])
Truth table0%0/3
A || B
A= $$proc{"hdr_$io"}B= $self->log->error(qq[[process $proc->{"pid"}]: IO handler ($io) is EMPTY])
ABresult
1X1
011
000
209
210 0 my $id = fileno $proc->{"hdr_$io"};
211
212 0 ▶ $self->ioloop->reactor->io($proc->{"hdr_$io"}, sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
213 0 my $chunk = undef;
214 0 my $len = sysread $proc->{"hdr_$io"}, $chunk, 65536;
215
216 0 ▶ return unless defined $len or $! != Errno::EINTR;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $len or $! != 4 0 0 0
Condition0%0/3
defined $len or $! != 4
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $len or $! != 4
defined $len $! != 4
Truth table0%0/3
A or B
A= defined $lenB= $! != 4
ABresult
1X1
011
000
217
218 0 ▶ if (!$len) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($len) 0 0 0
219 0 $self->drop_handle($pid, $io);
220 0 return;
221 }
222
223 0 ▶ if (defined $proc->{"$io\_cb"}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$proc{"${io}_cb"}) { } 0 0 0
224 0 $self->log->debug("[process $proc->{pid}]: (handle: $id) Invoking ".uc($io)." callback.");
225
226 0 eval { $proc->{"$io\_cb"}->($proc->{pid}, $chunk) };
227
228 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
229 0 $self->log->error("[process $proc->{pid}]: (handle: $id) Exception in $io\_cb: $@");
230 }
231 } else {
232 # append to buffer
233 0 $self->log->debug("[process $proc->{pid}]: (handle: $id) Appending $len bytes to ".uc($io)." buffer.");
234 0 $proc->{"buf_$io"} .= $chunk;
235 }
236 0 })->watch($proc->{"hdr_$io"}, 1, 0);
237 }
238  
239 0 ▶sub drop_handle {
Subroutine drop_handle: not called CC=5 SCAR=34.0
Pod undocumented
240 0 my $self = shift;
241 0 my $pid = shift;
242 0 ▶ my $io = lc(shift || '');
Condition0%0/2
shift() || ''
l!l
00
MC/DC0%0/1
shift() || ''
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
243
244 0 my $proc = $self->get_proc($pid);
245 0 ▶ return unless $proc;
Branch: 1 branch
BranchTrueFalseTotal
unless $proc 0 0 0
246
247 $self->log->debug("[process $pid]: Got HUP for unmanaged handle ".$proc->{"hdr_$io"}."; ignoring.") and return
248 0 ▶ unless $proc->{"hdr_$io"};
Branch: 1 branch
BranchTrueFalseTotal
unless $$proc{"hdr_$io"} 0 0 0
Condition0%0/5
$$proc{"hdr_$io"} || $self->log->debug("[process $pid]: Got HUP for unmanaged handle " . $$proc{"hdr_$io"} . '; ignoring.') && (return)
l!l&&r!l&&!r
000
$self->log->debug("[process $pid]: Got HUP for unmanaged handle " . $$proc{"hdr_$io"} . '; ignoring.') and return
!ll
00
MC/DC0%0/2
$$proc{"hdr_$io"} || $self->log->debug("[process $pid]: Got HUP for unmanaged handle " . $$proc{"hdr_$io"} . '; ignoring.') && (return)
$$proc{"hdr_$io"} $self->log->debug("[process $pid]: Got HUP for unmanaged handle " . $$proc{"hdr_$io"} . '; ignoring.')
Truth table0%0/3
A || B
A= $$proc{"hdr_$io"}B= $self->log->debug("[process $pid]: Got HUP for unmanaged handle " . $$proc{"hdr_$io"} . '; ignoring.')
ABresult
1X1
011
000
249
250
251 0 $self->ioloop->remove( $proc->{"hdr_$io"} );
252 0 undef $proc->{"hdr_$io"};
253
254 0 $self->log->debug("[process $pid]: ".uc($io)." closed.");
255
256 0 $self->complete($pid);
257 }
258  
259 0 ▶sub get_proc {
Subroutine get_proc: not called CC=4 SCAR=26.1
Pod undocumented
260 0 my ($self, $pid) = @_;
261
262 1 ▶ no warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
263 0 my $err = "[process $pid]: Unable to get process data structure: ";
264
265 0 ▶ unless (defined $pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $pid) 0 0 0
266 0 $self->error($err . "Undefined pid.");
267 0 return undef;
268 }
269
270 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"_data"}{$pid} and defined $self->{"_data"}{$pid}) 0 0 0
Condition0%0/3
exists $self->{"_data"}{$pid} and defined $self->{"_data"}{$pid}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $self->{"_data"}{$pid} and defined $self->{"_data"}{$pid}
exists $self->{"_data"}{$pid} defined $self->{"_data"}{$pid}
Truth table0%0/3
A and B
A= exists $self->{"_data"}{$pid}B= defined $self->{"_data"}{$pid}
ABresult
0X0
100
111
271 exists $self->{_data}->{$pid}
272 && defined $self->{_data}->{$pid}
273 ) {
274 0 $self->error($err . "Non-managed process pid: $pid");
275 0 return undef;
276 }
277  
278 0 return $self->{_data}->{$pid};
279 }
280  
281 0 ▶sub cleanup {
Subroutine cleanup: not called CC=8 SCAR=40.5
Pod undocumented
282 0 my ($self, $pid, $exit_val, $signum, $core) = @_;
283
284 0 my $proc = $self->get_proc($pid);
285 0 ▶ unless (defined $proc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $proc) 0 0 0
286 1 ▶ no warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
287 0 $self->log->warn("Untracked process pid $pid exited with exit status $exit_val by signal $signum, core: $core.");
288 0 return 0;
289 }
290 0 ▶ return 0 if $proc->{cleanup};
Branch: 1 branch
BranchTrueFalseTotal
if $proc->{"cleanup"} 0 0 0
291
292 0 $proc->{cleanup} = 1;
293  
294 0 ▶ $self->log->debug("[process $pid]: Got SIGCHLD, "
Branch: 1 branch
BranchTrueFalseTotal
$core ? : 0 0 0
295 . "exited with exit status: $exit_val by signal $signum"
296 . (($core) ? "with core dump." : ".")
297 );
298  
299 0 ▶ if (defined $proc->{id_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $proc->{"id_timeout"}) 0 0 0
300 0 $self->ioloop->remove($proc->{id_timeout});
301 0 $proc->{id_timeout} = undef;
302 }
303 0 ▶ if ($proc->{hard_kill}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proc->{"hard_kill"}) 0 0 0
304 0 for (qw/stderr stdout stdres/) {
305 0 ▶ $self->drop_handle($pid, $_) if $proc->{"hdr_$_"};
Branch: 1 branch
BranchTrueFalseTotal
if $$proc{"hdr_$_"} 0 0 0
306 }
307 }
308 0 $proc->{exit_status} = $exit_val;
309 0 $proc->{exit_core } = $core;
310 0 $proc->{exit_signal} = $signum;
311  
312 # command timings...
313 0 my $te = time;
314 0 $proc->{time_stopped } = $te;
315 0 $proc->{time_duration_exec} = $te - $proc->{time_started};
316  
317 # this process is no longer running
318 0 $proc->{running} = 0;
319  
320 0 $self->complete($pid);
321 }
322  
323 0 ▶sub complete {
Subroutine complete: not called CC=17 SCAR=57.2
Pod undocumented
324 0 my ($self, $pid, $force) = @_;
325
326 0 my $proc = $self->get_proc($pid);
327
328 return 0 if !$force
329 && (
330 $proc->{running}
331 || defined $proc->{hdr_stdout}
332 || defined $proc->{hdr_stdres}
333 || defined $proc->{hdr_stderr}
334 0 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
if not $force and $proc->{"running"} || defined $proc->{"hdr_stdout"} || defined $proc->{"hdr_stdres"} || defined $proc->{"hdr_stderr"} 0 0 0
Condition0%0/12
not $force and $proc->{"running"} || defined $proc->{"hdr_stdout"} || defined $proc->{"hdr_stdres"} || defined $proc->{"hdr_stderr"}
!ll&&!rl&&r
000
$proc->{"running"} or defined $proc->{"hdr_stdout"} or defined $proc->{"hdr_stdres"} or defined $proc->{"hdr_stderr"}
l!l&&r!l&&!r
000
$proc->{"running"} or defined $proc->{"hdr_stdout"} or defined $proc->{"hdr_stdres"}
l!l&&r!l&&!r
000
$proc->{"running"} or defined $proc->{"hdr_stdout"}
l!l&&r!l&&!r
000
MC/DC0%0/5
not $force and $proc->{"running"} || defined $proc->{"hdr_stdout"} || defined $proc->{"hdr_stdres"} || defined $proc->{"hdr_stderr"}
not $force $proc->{"running"} defined $proc->{"hdr_stdout"} defined $proc->{"hdr_stdres"} defined $proc->{"hdr_stderr"}
Truth table0%0/6
not(A) and B or C or D or E
A= not $forceB= $proc->{"running"}C= defined $proc->{"hdr_stdout"}D= defined $proc->{"hdr_stdres"}E= defined $proc->{"hdr_stderr"}
ABCDEresult
0XXXX0
100000
11XXX1
101XX1
1001X1
100011
335
336  
337 0 ▶ if ($proc && %$proc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proc and %$proc) 0 0 0
Condition0%0/3
$proc and %$proc
!ll&&!rl&&r
000
MC/DC0%0/2
$proc and %$proc
$proc %$proc
Truth table0%0/3
A and B
A= $procB= %$proc
ABresult
0X0
100
111
338 0 $self->log->debug("[process $pid]: All streams closed, process execution complete.");
339
340 0 $proc->{time_duration_total} = time - $proc->{time_started};
341  
342 # fire exit callback!
343 0 ▶ if (defined $proc->{exit_cb} && ref $proc->{exit_cb} eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $proc->{'exit_cb'} and ref $proc->{'exit_cb'} eq 'CODE') { } 0 0 0
Condition0%0/3
defined $proc->{"exit_cb"} and ref $proc->{"exit_cb"} eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $proc->{"exit_cb"} and ref $proc->{"exit_cb"} eq "CODE"
defined $proc->{"exit_cb"} ref $proc->{"exit_cb"} eq "CODE"
Truth table0%0/3
A and B
A= defined $proc->{"exit_cb"}B= ref $proc->{"exit_cb"} eq "CODE"
ABresult
0X0
100
111
344 0 ▶ my $result = eval { $proc->{buf_stdres} ? thaw($proc->{buf_stdres}) : undef};
Branch: 1 branch
BranchTrueFalseTotal
$proc->{'buf_stdres'} ? : 0 0 0
345
346 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
347 0 croak "Error de-serializing subprocess data: $@";
348 }
349
350 # prepare callback structure
351 my $cb_d = {
352 cmd => ref $proc->{cmd} eq 'CODE' ? 'CODE' :
353 0 ▶ ref $proc->{cmd} eq 'ARRAY' ? join(' ', @{$proc->{cmd}}) :
Branch: 2 branches
BranchTrueFalseTotal
$proc->{'buf_stderr'} ? : 0 0 0
$proc->{'stderr'} ? : 0 0 0
354 $proc->{cmd}
355 ,
356 param => $proc->{param},
357 exit_status => $proc->{exit_status},
358 exit_signal => $proc->{exit_signal},
359 exit_core => $proc->{exit_core},
360 stdout => $proc->{buf_stdout},
361 stderr => ($proc->{buf_stderr} ? $proc->{buf_stderr} : '').($proc->{stderr} ? $proc->{stderr} : ''),
362 result => $result,
363 time_started => $proc->{time_started},
364 time_stopped => $proc->{time_stopped},
365 time_duration_exec => $proc->{time_duration_exec},
366 time_duration_total => $proc->{time_duration_total},
367 0 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
ref $proc->{'cmd'} eq 'CODE' ? : 0 0 0
ref $proc->{'cmd'} eq 'ARRAY' ? : 0 0 0
368  
369 # safely invoke callback
370 0 $self->log->debug("[process $pid]: invoking exit_cb callback.");
371 0 eval { $proc->{exit_cb}->($pid, $cb_d); };
372
373 0 ▶ $self->log->error("[process $pid]: Error running exit_cb: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
374 } else {
375 0 $self->log->error("[process $pid]: No exit_cb callback!");
376 }
377 }
378  
379 0 delete $self->{_data}->{$pid};
380 0 $self->num_forks($self->num_forks - 1);
381 }
382  
383 0 ▶sub _sig_chld {
Subroutine _sig_chld: not called CC=3 SCAR=20.6
384 0 my ($self) = @_;
385  
386 1 ▶ no strict 'subs';
Subroutine BEGIN: called CC=1 SCAR=0.0
387
388 0 my $i = 0;
389 0 ▶ while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ((my $pid = waitpid(-1, 1)) > 0) 0 0 0
390 0 $i++;
391 0 my $exit_val = $? >> 8;
392 0 my $signum = $? & 127;
393 0 my $core = $? & 128;
394  
395 # do process cleanup
396 0 $self->cleanup($pid, $exit_val, $signum, $core);
397 }
398
399 0 ▶ $self->log->debug("SIGCHLD handler cleaned up after $i process(es).")
Branch: 1 branch
BranchTrueFalseTotal
if $i > 0 0 0 0
400 if $i > 0;
401 }
402  
403 0 ▶sub _getRunStruct {
Subroutine _getRunStruct: not called CC=2 SCAR=17.9
404 0 my ($self, $opt) = @_;
405
406 0 my $s = {
407 pid => 0,
408 cmd => undef,
409 param => undef,
410 error => undef,
411 stdout_cb => undef,
412 stderr_cb => undef,
413 exit_cb => undef,
414 exec_timeout => 0,
415 buf_stdout => '',
416 buf_stderr => '',
417 buf_stdres => '',
418 hdr_stdout => undef,
419 hdr_stderr => undef,
420 hdr_stdres => undef,
421 };
422  
423 # apply user defined vars...
424 $s->{$_} = $opt->{$_}
425 0 for grep { exists $s->{$_} } keys %$opt;
426  
427 0 return $s;
428 }
429  
430 0 ▶sub _validateRunStruct {
Subroutine _validateRunStruct: not called CC=18 SCAR=57.1
431 0 my ($self, $s) = @_;
432  
433 # command?
434 $self->error('Undefined command.') and return
435 0 ▶ unless defined $s->{cmd};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s->{"cmd"} 0 0 0
Condition0%0/5
defined $s->{'cmd'} || $self->error('Undefined command.') && (return)
l!l&&r!l&&!r
000
$self->error("Undefined command.") and return
!ll
00
MC/DC0%0/2
defined $s->{'cmd'} || $self->error('Undefined command.') && (return)
defined $s->{'cmd'} $self->error("Undefined command.")
Truth table0%0/3
A || B
A= defined $s->{'cmd'}B= $self->error("Undefined command.")
ABresult
1X1
011
000
436
437 # check command...
438 0 my $cmd_ref = ref $s->{cmd};
439 $self->error('Zero-length command.') and return
440 0 ▶ if $cmd_ref eq '' && length $s->{cmd} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cmd_ref eq "" and length $s->{"cmd"} == 0 0 0 0
Condition0%0/8
$cmd_ref eq '' && length $s->{'cmd'} == 0 && ($self->error('Zero-length command.') && (return))
!ll&&!rl&&r
000
$cmd_ref eq "" and length $s->{"cmd"} == 0
!ll&&!rl&&r
000
$self->error("Zero-length command.") and return
!ll
00
MC/DC0%0/3
$cmd_ref eq '' && length $s->{'cmd'} == 0 && ($self->error('Zero-length command.') && (return))
$cmd_ref eq "" length $s->{"cmd"} == 0 $self->error("Zero-length command.")
Truth table0%0/4
A and B && C
A= $cmd_ref eq ""B= length $s->{"cmd"} == 0C= $self->error("Zero-length command.")
ABCresult
0XX0
10X0
1100
1111
441
442 0 ▶ $self->error('Command can be pure scalar, arrayref or coderef.') and return
Branch: 1 branch
BranchTrueFalseTotal
if $cmd_ref ne "" and not $cmd_ref ~~ ["CODE", "ARRAY"] 0 0 0
Condition0%0/8
$cmd_ref ne '' && !($cmd_ref ~~ ['CODE', 'ARRAY']) && ($self->error('Command can be pure scalar, arrayref or coderef.') && (return))
!ll&&!rl&&r
000
$cmd_ref ne "" and not $cmd_ref ~~ ["CODE", "ARRAY"]
!ll&&!rl&&r
000
$self->error("Command can be pure scalar, arrayref or coderef.") and return
!ll
00
MC/DC0%0/3
$cmd_ref ne '' && !($cmd_ref ~~ ['CODE', 'ARRAY']) && ($self->error('Command can be pure scalar, arrayref or coderef.') && (return))
$cmd_ref ne "" not $cmd_ref ~~ ["CODE", "ARRAY"] $self->error("Command can be pure scalar, arrayref or coderef.")
Truth table0%0/4
A and not(B) && C
A= $cmd_ref ne ""B= not $cmd_ref ~~ ["CODE", "ARRAY"]C= $self->error("Command can be pure scalar, arrayref or coderef.")
ABCresult
0XX0
10X0
1100
1111
443 if $cmd_ref ne '' && not $cmd_ref ~~ ['CODE', 'ARRAY'];
444  
445 # callbacks...
446 $self->error("STDOUT callback defined, but is not code reference.") and return
447 0 ▶ if defined $s->{stdout_cb} && ref $s->{stdout_cb} ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if defined $s->{"stdout_cb"} and ref $s->{"stdout_cb"} ne "CODE" 0 0 0
Condition0%0/8
defined $s->{'stdout_cb'} && ref $s->{'stdout_cb'} ne 'CODE' && ($self->error('STDOUT callback defined, but is not code reference.') && (return))
!ll&&!rl&&r
000
defined $s->{"stdout_cb"} and ref $s->{"stdout_cb"} ne "CODE"
!ll&&!rl&&r
000
$self->error("STDOUT callback defined, but is not code reference.") and return
!ll
00
MC/DC0%0/3
defined $s->{'stdout_cb'} && ref $s->{'stdout_cb'} ne 'CODE' && ($self->error('STDOUT callback defined, but is not code reference.') && (return))
defined $s->{"stdout_cb"} ref $s->{"stdout_cb"} ne "CODE" $self->error("STDOUT callback defined, but is not code reference.")
Truth table0%0/4
A and B && C
A= defined $s->{"stdout_cb"}B= ref $s->{"stdout_cb"} ne "CODE"C= $self->error("STDOUT callback defined, but is not code reference.")
ABCresult
0XX0
10X0
1100
1111
448
449 $self->error("STDERR callback defined, but is not code reference.") and return
450 0 ▶ if defined $s->{stderr_cb} && ref $s->{stderr_cb} ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if defined $s->{"stderr_cb"} and ref $s->{"stderr_cb"} ne "CODE" 0 0 0
Condition0%0/8
defined $s->{'stderr_cb'} && ref $s->{'stderr_cb'} ne 'CODE' && ($self->error('STDERR callback defined, but is not code reference.') && (return))
!ll&&!rl&&r
000
defined $s->{"stderr_cb"} and ref $s->{"stderr_cb"} ne "CODE"
!ll&&!rl&&r
000
$self->error("STDERR callback defined, but is not code reference.") and return
!ll
00
MC/DC0%0/3
defined $s->{'stderr_cb'} && ref $s->{'stderr_cb'} ne 'CODE' && ($self->error('STDERR callback defined, but is not code reference.') && (return))
defined $s->{"stderr_cb"} ref $s->{"stderr_cb"} ne "CODE" $self->error("STDERR callback defined, but is not code reference.")
Truth table0%0/4
A and B && C
A= defined $s->{"stderr_cb"}B= ref $s->{"stderr_cb"} ne "CODE"C= $self->error("STDERR callback defined, but is not code reference.")
ABCresult
0XX0
10X0
1100
1111
451
452 $self->error("Process exit_cb callback defined, but is not code reference.") and return
453 0 ▶ if defined $s->{exit_cb} && ref($s->{exit_cb}) ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if defined $s->{"exit_cb"} and ref $s->{"exit_cb"} ne "CODE" 0 0 0
Condition0%0/8
defined $s->{'exit_cb'} && ref $s->{'exit_cb'} ne 'CODE' && ($self->error('Process exit_cb callback defined, but is not code reference.') && (return))
!ll&&!rl&&r
000
defined $s->{"exit_cb"} and ref $s->{"exit_cb"} ne "CODE"
!ll&&!rl&&r
000
$self->error("Process exit_cb callback defined, but is not code reference.") and return
!ll
00
MC/DC0%0/3
defined $s->{'exit_cb'} && ref $s->{'exit_cb'} ne 'CODE' && ($self->error('Process exit_cb callback defined, but is not code reference.') && (return))
defined $s->{"exit_cb"} ref $s->{"exit_cb"} ne "CODE" $self->error("Process exit_cb callback defined, but is not code reference.")
Truth table0%0/4
A and B && C
A= defined $s->{"exit_cb"}B= ref $s->{"exit_cb"} ne "CODE"C= $self->error("Process exit_cb callback defined, but is not code reference.")
ABCresult
0XX0
10X0
1100
1111
454  
455 # exec timeout
456 0 ▶ { no warnings; $s->{exec_timeout} += 0; }
Subroutine BEGIN: called CC=1 SCAR=0.6
457  
458 0 return 1;
459 }
460  
461 0 ▶sub _timeout_cb {
Subroutine _timeout_cb: not called CC=5 SCAR=34.0
462 0 my ($self, $pid) = @_;
463
464 0 my $proc = $self->get_proc($pid);
465 0 ▶ return 0 unless $proc;
Branch: 1 branch
BranchTrueFalseTotal
unless $proc 0 0 0
466
467 # drop timer (can't hurt...)
468 0 ▶ if (defined $proc->{id_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $proc->{"id_timeout"}) 0 0 0
469 0 $self->ioloop->remove($proc->{id_timeout});
470 0 $proc->{id_timeout} = undef;
471 }
472  
473 # is process still alive?
474 0 ▶ return 0 unless kill 0, $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless CORE::kill 0, $pid 0 0 0
475  
476 $self->log->debug("[process $pid]: Execution timeout ("
477 .sprintf("%-.3f seconds).", $proc->{exec_timeout})
478 0 ." Killing process.");
479  
480 0 $proc->{stderr} .= ";Execution timeout.";
481
482 # kill the motherfucker!
483  
484 0 ▶ unless (CORE::kill(9, $pid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (CORE::kill 9, $pid) 0 0 0
485 0 $self->log->warn("[process $pid]: Unable to kill process: $!");
486 }
487 0 $proc->{hard_kill} = 1;
488 0 $self->cleanup($pid, 0, 9, 0);
489  
490 0 return 1;
491 }
492  
493 0 ▶sub kill {
Subroutine kill: not called CC=4 SCAR=30.0
Pod undocumented
494 0 my ($self, $pid, $signal) = @_;
495 0 ▶ $signal = 15 unless defined $signal;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $signal 0 0 0
496
497 0 my $proc = $self->get_proc($pid);
498 0 ▶ return 0 unless $proc;
Branch: 1 branch
BranchTrueFalseTotal
unless $proc 0 0 0
499  
500 # kill the process...
501 0 ▶ unless (kill($signal, $pid)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (CORE::kill $signal, $pid) 0 0 0
502 0 $self->error("Unable to send signal $signal to process $pid: $!");
503 0 return 0;
504 }
505
506 0 return 1;
507 }
508  
509 0 ▶sub DESTROY {
Subroutine DESTROY: not called CC=6 SCAR=37.4
510 0 my ($self) = @_;
511
512 # perform cleanup...
513 0 ▶ unless ($self->is_child) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->is_child) 0 0 0
514 0 foreach my $pid (keys %{$self->{_data}}) {
515 0 my $proc = $self->{_data}->{$pid};
516
517 0 ▶ $self->log->debug("Killing subprocess $pid with SIGKILL") if $self->log;
Branch: 1 branch
BranchTrueFalseTotal
if $self->log 0 0 0
518 # kill process (HARD!)
519 0 $self->kill($pid, 9);
520
521 0 ▶ next unless defined $self->ioloop;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->ioloop 0 0 0
522
523 # drop fds
524 0 $self->drop_handle($pid, $_) for grep {$proc->{"hdr_$_"}} qw/stdout stderr stdres/;
525
526 # fire exit callbacks (if any)
527 0 $self->complete($pid, 1);
528 }
529 }
530  
531 # disable sigchld hander
532 0 $SIG{'CHLD'} = 'IGNORE';
533 }
534  
535 1 1;
536  
537 =pod
538
539 =head1 NAME
540  
541 Mojo::Run - asynchronous external command execution for Mojo
542  
543 =head1 VERSION
544  
545 version 0.3
546  
547 =head1 SYNOPSIS
548  
549 use Mojo::Run;
550 use Mojo::Log;
551  
552 my $run = Mojo::Run->new;
553 $run->max_forks(10);
554 $run->log(Mojo::Log->new(
555 level => 'error',
556 path => 'log/mojo_run.log',
557 ));
558  
559 $run->spawn(
560 cmd => sub {
561 my $pid = shift;
562 my $param = shift; # {a => 1, b => 2}
563
564 my $data = {};
565 ... do something
566 return $data;
567 },
568 param => {a => 1, b => 2},
569 exec_timeout => 120, # sec
570 stdout_cb => sub {
571 my ($pid, $chunk) = @_;
572 },
573 stderr_cb => sub {
574 my ($pid, $chunk) = @_;
575 },
576 exit_cb => sub {
577 my $pid = shift;
578 my $res = shift;
579 warn $res->{result}->[0];
580 },
581 );
582 $run->spawn(
583 cmd => 'ps aux',
584 exit_cb => sub {
585 my $pid = shift;
586 my $res = shift;
587 },
588 );
589 $run->spawn(
590 cmd => ['perl', '-v'],
591 exit_cb => sub {
592 my $pid = shift;
593 my $res = shift;
594 },
595 );
596  
597 $run->start;
598  
599 =head1 Result
600  
601 Result in B< exit_cb > is a HASH with following keys:
602  
603 =over
604
605 =item B< cmd >
606  
607 =item B< param >
608  
609 =item B< exit_status >
610  
611 =item B< exit_signal >
612  
613 =item B< exit_core >
614  
615 =item B< stdout >
616  
617 =item B< stderr >
618  
619 =item B< result >
620  
621 =item B< time_started >
622  
623 =item B< time_stopped >
624  
625 =item B< time_duration_exec >
626  
627 =item B< time_duration_total >
628  
629 =back
630  
631 =head1 SOURCE REPOSITORY
632  
633 L<https://github.com/likhatskiy/Mojo-Run>
634  
635 =head1 AUTHOR
636  
637 Alexey Likhatskiy, <likhatskiy@gmail.com>
638  
639 =head1 LICENSE AND COPYRIGHT
640  
641 Copyright (C) 2012-2013 "Alexey Likhatskiy"
642  
643 This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
↑ Summary