blib/lib/Parallel/Fork/BossWorkerAsync.pm

filter: Statementstmt 90.1% 293 / 325 Branchbran 68.0% 102 / 150 Conditioncond 65.2% 30 / 46 MC/DCmcdc 37.0% 10 / 27 Subroutinesub 100% 27 / 27 Podpod 27.7% 5 / 18 totaltotal 78.7% 467 / 593 SCAR 51.0
CC
101
Cov
82%
boss_loop
28.7
read
18.8
new
12.2
CRAP 164.8
↑ Summary
1 package Parallel::Fork::BossWorkerAsync;
2 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 23 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 23 ▶use Data::Dumper qw( Dumper );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 23 ▶use Socket qw( AF_UNIX SOCK_STREAM PF_UNSPEC );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use Fcntl qw( F_GETFL F_SETFL O_NONBLOCK );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use POSIX qw( EINTR EWOULDBLOCK );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use IO::Select ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 23 our @ISA = qw();
12 23 our $VERSION = '0.08';
13  
14 # TO DO (wish list):
15 # Restart crashed child workers.
16  
17 # -----------------------------------------------------------------
18 sub new {
19 23 ▶ my ($class, %attrs)=@_;
Subroutine new: called CC=10 SCAR=25.0
Pod documented
20 my $self = {
21 work_handler => $attrs{work_handler}, # required
22 init_handler => $attrs{init_handler} || undef, # optional
23 result_handler => $attrs{result_handler} || undef, # optional
24 worker_count => $attrs{worker_count} || 3, # optional, how many child workers
25 global_timeout => $attrs{global_timeout} || 0, # optional, in seconds, 0 is unlimited
26 msg_delimiter => $attrs{msg_delimiter} || "\0\0\0", # optional, may not appear in data
27 read_size => $attrs{read_size} || 1024*1024, # optional, defaults to 1 MB
28 23 ▶ verbose => $attrs{verbose} || 0, # optional, *undocumented*, 0=silence, 1=debug
Condition71%10/14
$attrs{'init_handler'} || undef
l!l
023
$attrs{'result_handler'} || undef
l!l
230
$attrs{'worker_count'} || 3
l!l
320
$attrs{'global_timeout'} || 0
l!l
320
$attrs{'msg_delimiter'} || "\000\000\000"
l!l
518
$attrs{'read_size'} || 1048576
l!l
023
$attrs{'verbose'} || 0
l!l
023
MC/DC0%0/1
$attrs{'init_handler'} || undef
$attrs{'init_handler'}
MC/DC0%0/1
$attrs{'result_handler'} || undef
$attrs{'result_handler'}
MC/DC100%1/1
$attrs{'worker_count'} || 3
$attrs{'worker_count'}
MC/DC100%1/1
$attrs{'global_timeout'} || 0
$attrs{'global_timeout'}
MC/DC100%1/1
$attrs{'msg_delimiter'} || "\000\000\000"
$attrs{'msg_delimiter'}
MC/DC0%0/1
$attrs{'read_size'} || 1048576
$attrs{'read_size'}
MC/DC0%0/1
$attrs{'verbose'} || 0
$attrs{'verbose'}
Truth table50%1/2
A
A= $attrs{'init_handler'}
Aresult
11
00
Truth table50%1/2
A
A= $attrs{'result_handler'}
Aresult
11
00
Truth table100%2/2
A
A= $attrs{'worker_count'}
Aresult
11
00
Truth table100%2/2
A
A= $attrs{'global_timeout'}
Aresult
11
00
Truth table100%2/2
A
A= $attrs{'msg_delimiter'}
Aresult
11
00
Truth table50%1/2
A
A= $attrs{'read_size'}
Aresult
11
00
Truth table50%1/2
A
A= $attrs{'verbose'}
Aresult
11
00
29 shutting_down => 0,
30 force_down => 0,
31 pending => 0,
32 result_stream => '',
33 result_queue => [],
34 job_queue => [],
35 };
36 23 ▶ bless($self, ref($class) || $class);
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
0230
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
37  
38 23 ▶ croak("Parameter 'work_handler' is required") if ! defined($self->{work_handler});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"work_handler"} 0 23 23
39  
40 # Start the "boss" process, which will start the workers
41 23 $self->start_boss();
42  
43 5 return $self;
44 }
45  
46 # -----------------------------------------------------------------
47 sub serialize {
48 66 ▶ my ($self, $ref)=@_;
Subroutine serialize: called CC=1 SCAR=0.0
Pod undocumented
49 66 local $Data::Dumper::Deepcopy = 1;
50 66 local $Data::Dumper::Indent = 0;
51 66 local $Data::Dumper::Purity = 1;
52 66 return Dumper($ref) . $self->{msg_delimiter};
53 }
54  
55 # -----------------------------------------------------------------
56 sub deserialize {
57 66 ▶ my ($self, $data)=@_;
Subroutine deserialize: called CC=2 SCAR=7.1
Pod undocumented
58 66 $data = substr($data, 0, - length($self->{msg_delimiter}));
59 66 my $VAR1;
60 66 my $ref = eval($data);
61 66 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 66 66
62 0 confess("failed to deserialize: $@");
63 }
64 66 return $ref;
65 }
66  
67 # -----------------------------------------------------------------
68 # Pass one or more hashrefs for the jobs.
69 # Main app sends jobs to Boss.
70 sub add_work {
71 33 ▶ my ($self, @jobs)=@_;
Subroutine add_work: called CC=3 SCAR=11.0
Pod documented
72 33 $self->blocking($self->{boss_socket}, 1);
73 33 ▶ while (@jobs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@jobs) 33 33 66
74 33 $self->log("add_work: adding job to queue\n");
75 33 my $job = shift(@jobs);
76 33 my $n = syswrite( $self->{boss_socket}, $self->serialize($job) );
77 33 ▶ croak("add_work: app write to boss: syswrite: $!") if ! defined($n);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 0 33 33
78 33 $self->{pending} ++;
79 33 $self->log("add_work: job added to queue, $self->{pending} pending\n");
80 }
81 }
82  
83 # -----------------------------------------------------------------
84 # Syntactic nicety
85 sub get_result_nb {
86 1 ▶ my ($self)=@_;
Subroutine get_result_nb: called CC=1 SCAR=0.0
Pod undocumented
87 1 return $self->get_result(blocking => 0);
88 }
89  
90 # -----------------------------------------------------------------
91 # Main app gets a complete, single result from Boss.
92 # If defined, result_handler fires here.
93 # Return is result of work_handler, or result_handler (if defined),
94 # or {} (empty hash ref).
95 # Undef is returned if socket marked nonblocking and read would have
96 # blocked.
97 sub get_result {
98 34 ▶ my ($self, %args)=@_;
Subroutine get_result: called CC=10 SCAR=23.6
Pod documented
99 34 ▶ $args{blocking} = 1 if ! defined($args{blocking});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"blocking"} 33 1 34
100 34 ▶ carp("get_result() when no results pending") if ! $self->pending();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->pending 0 34 34
101  
102 34 my $rq_count = scalar(@{ $self->{result_queue} });
103 34 $self->log("get_result: $self->{pending} jobs in process, $rq_count results ready\n");
104  
105 34 ▶ if ( ! @{ $self->{result_queue} }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@{$self->{"result_queue"};}) 24 10 34
106 24 $self->blocking($self->{boss_socket}, $args{blocking});
107 24 $self->read($self->{boss_socket}, $self->{result_queue}, \$self->{result_stream}, 'app');
108
109 # Handle nonblocking case
110 24 ▶ if ( ! $args{blocking} && ! @{ $self->{result_queue} }) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"blocking"} or @{$self->{"result_queue"};}) 1 23 24
Condition66%2/3
$args{"blocking"} or @{$self->{"result_queue"};}
l!l&&r!l&&!r
2301
MC/DC50%1/2
$args{"blocking"} or @{$self->{"result_queue"};}
$args{"blocking"} @{$self->{"result_queue"};}
Truth table66%2/3
A or B
A= $args{"blocking"}B= @{$self->{"result_queue"};}
ABresult
1X1
011
000
111 1 return undef;
112 }
113 }
114  
115 33 $self->log("get_result: got result\n");
116  
117 33 $self->{pending} --;
118 33 ▶ if ($self->{pending} == 0 && $self->{shutting_down}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pending"} == 0 and $self->{"shutting_down"}) 0 33 33
Condition66%2/3
$self->{"pending"} == 0 and $self->{"shutting_down"}
!ll&&!rl&&r
2850
MC/DC0%0/2
$self->{"pending"} == 0 and $self->{"shutting_down"}
$self->{"pending"} == 0 $self->{"shutting_down"}
Truth table66%2/3
A and B
A= $self->{"pending"} == 0B= $self->{"shutting_down"}
ABresult
0X0
100
111
119 0 $self->log("get_result: no jobs pending; closing boss\n");
120 0 close($self->{boss_socket});
121 }
122 33 my $ref = $self->deserialize( shift( @{ $self->{result_queue} } ) );
123 33 ▶ my $retval = $self->{result_handler} ? $self->{result_handler}->($ref) : $ref;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'result_handler'} ? : 33 0 33
124 33 ▶ $retval = {} if ! defined($retval);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $retval 0 33 33
125 33 return $retval;
126 }
127  
128 # -----------------------------------------------------------------
129 # Main app calls to see if there are submitted jobs for which no
130 # response has been collected. It doesn't mean the responses are
131 # ready yet.
132 sub pending {
133 75 ▶ my ($self)=@_;
Subroutine pending: called CC=1 SCAR=0.0
Pod documented
134 75 return $self->{pending};
135 }
136  
137 # -----------------------------------------------------------------
138 # App tells boss to shut down by half-close.
139 # Boss then finishes work in progress, and eventually tells
140 # workers to exit.
141 # Boss sends all results back to app before exiting itself.
142 # Note: Boss won't be able to close cleanly if app ignores
143 # final reads...
144 # args: force => 0,1 defaults to 0
145 sub shut_down {
146 5 ▶ my ($self, %args)=@_;
Subroutine shut_down: called CC=5 SCAR=18.1
Pod documented
147 5 ▶ $args{force} ||= 0;
Condition50%1/2
$args{"force"} ||= 0
l!l
05
MC/DC0%0/1
$args{"force"} ||= 0
$args{"force"}
Truth table50%1/2
A
A= $args{"force"}
Aresult
11
00
148 5 $self->{shutting_down} = 1;
149  
150 5 $self->log("shut_down: MARK\n");
151  
152 5 ▶ if ($args{force}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'force'}) { } 0 5 5
elsif ($self->pending) { } 0 5 5
153 # kill boss pid
154 0 kill(9, $self->{boss_pid});
155 } elsif ($self->pending()) {
156 0 shutdown($self->{boss_socket}, 1);
157 } else {
158 5 close($self->{boss_socket});
159 }
160  
161 5 ▶ while (wait() != -1) {}; # waits/reaps Boss process
Branch: 1 branch
BranchTrueFalseTotal
if (wait != -1) 0 5 5
162 }
163  
164 # -----------------------------------------------------------------
165 # Make socket blocking/nonblocking
166 sub blocking {
167 100 ▶ my ($self, $socket, $makeblocking)=@_;
Subroutine blocking: called CC=7 SCAR=19.6
Pod undocumented
168 100 ▶ my $flags = fcntl($socket, F_GETFL, 0)
Branch: 1 branch
BranchTrueFalseTotal
my $flags = fcntl($socket, 3, 0) or croak("fcntl failed: $!") 0 100 100
169 or croak("fcntl failed: $!");
170 100 my $blocking = ($flags & O_NONBLOCK) == 0;
171 100 ▶ if ($blocking && ! $makeblocking) {
Branch: 2 branches
BranchTrueFalseTotal
if ($blocking and not $makeblocking) { } 44 56 100
elsif (not $blocking and $makeblocking) { } 1 55 56
Condition100%3/3
$blocking and not $makeblocking
!ll&&!rl&&r
15544
MC/DC100%2/2
$blocking and not $makeblocking
$blocking not $makeblocking
Truth table100%3/3
A and not(B)
A= $blockingB= not $makeblocking
ABresult
0X0
100
111
172 44 $flags |= O_NONBLOCK;
173 ▶ } elsif (! $blocking && $makeblocking) {
Condition66%2/3
not $blocking and $makeblocking
!ll&&!rl&&r
5501
MC/DC50%1/2
not $blocking and $makeblocking
not $blocking $makeblocking
Truth table66%2/3
not(A) and B
A= not $blockingB= $makeblocking
ABresult
0X0
100
111
174 1 $flags &= ~O_NONBLOCK;
175 } else {
176 # do nothing
177 55 return $blocking;
178 }
179
180 45 ▶ fcntl($socket, F_SETFL, $flags)
Branch: 1 branch
BranchTrueFalseTotal
fcntl $socket, 4, $flags or croak("fcntl failed: $!") 0 45 45
181 or croak("fcntl failed: $!");
182 45 return $blocking;
183 }
184  
185 # -----------------------------------------------------------------
186 sub start_boss {
187 23 ▶ my ($self)=@_;
Subroutine start_boss: called CC=6 SCAR=18.1
Pod undocumented
188 23 $self->log("start_boss: start\n");
189 23 eval {
190 23 my ($b1, $b2);
191 23 ▶ socketpair($b1, $b2, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
Branch: 1 branch
BranchTrueFalseTotal
socketpair $b1, $b2, 1, 1, 0 or die "socketpair: $!" 0 23 23
192 or die("socketpair: $!");
193  
194 23 my $pid = fork();
195 23 ▶ defined $pid || confess("fork failed: $!");
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or confess("fork failed: $!") 0 23 23
196  
197 23 ▶ if ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) { } 5 18 23
198 # Application (parent)
199 5 $self->{boss_pid} = $pid;
200  
201 # App won't write to, or read from itself.
202 5 close($b2);
203 5 $self->{boss_socket} = $b1;
204  
205 5 $self->log("start_boss: Application: Boss started\n");
206  
207 } else {
208 # Manager aka Boss (child)
209 # Boss won't write to, or read from itself.
210 18 close($b1);
211
212 18 $self->{app_socket} = $b2;
213
214 # Make nonblocking
215 18 $self->blocking( $self->{app_socket}, 0 );
216 18 open(STDIN, '/dev/null');
217
218 18 $self->start_workers();
219 5 $self->boss_loop();
220 5 ▶ while (wait() != -1) {}; # waits/reaps workers only
Branch: 1 branch
BranchTrueFalseTotal
if (wait != -1) 0 5 5
221  
222 5 $self->log("start_boss: Boss: exiting\n");
223 5 exit;
224 }
225 };
226 5 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 5 5
227 0 croak($@);
228 }
229 }
230  
231 # -----------------------------------------------------------------
232 sub start_workers {
233 18 ▶ my ($self)=@_;
Subroutine start_workers: called CC=6 SCAR=18.1
Pod undocumented
234 18 $self->log("start_workers: starting $self->{worker_count} workers\n");
235 18 eval {
236 18 for (1 .. $self->{worker_count}) {
237 38 my ($w1, $w2);
238 38 ▶ socketpair($w1, $w2, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
Branch: 1 branch
BranchTrueFalseTotal
socketpair $w1, $w2, 1, 1, 0 or die "socketpair: $!" 0 38 38
239 or die("socketpair: $!");
240
241 38 my $pid = fork();
242 38 ▶ defined $pid || confess("fork failed: $!");
Branch: 1 branch
BranchTrueFalseTotal
defined $pid or confess("fork failed: $!") 0 38 38
243  
244 38 ▶ if ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) { } 25 13 38
245 # Boss (parent)
246 25 close($w2);
247 25 $self->{workers}->{ $w1 } = { pid => $pid, socket => $w1 };
248  
249 # Make nonblocking
250 25 $self->blocking( $w1, 0 );
251
252 } else {
253 # Worker (child)
254 13 close($self->{app_socket});
255 13 delete($self->{workers});
256 13 close($w1);
257 13 $self->{socket} = $w2;
258 13 open(STDIN, '/dev/null');
259
260 13 $self->worker_loop();
261 13 exit;
262 }
263 }
264  
265 5 $self->log("start_workers: start workers complete\n");
266 };
267 5 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 5 5
268 0 croak($@);
269 }
270 }
271  
272 # -----------------------------------------------------------------
273 # Boss process; have an open socket to the app, and one to each worker.
274 # Loop select(), checking for read and write on app socket, and read
275 # on working children, and write on idle children.
276 # Keep track of idle vs. working children.
277 # When receive a shutdown order from the app, keep looping until the
278 # job queue is empty, and all results have been retrieved (all
279 # children will now be idle.) Then close the worker sockets.
280 # They'll be reading, and will notice this and exit.
281 # Don't deserialize any data. Just look for the delimiters to know
282 # we're processing whole records.
283 #
284  
285 sub boss_loop {
286 5 ▶ my ($self)=@_;
Subroutine boss_loop: called CC=24 SCAR=33.6
Pod undocumented
287  
288 5 $self->log("boss_loop: start\n");
289 5 eval {
290 # handy
291 5 my $workers = $self->{workers};
292
293 # All workers start out idle
294 5 for my $s (keys(%$workers)) {
295 13 $workers->{ $s }->{idle} = 1;
296 }
297
298 5 while ( 1 ) {
299 # When to exit loop?
300 # shutting_down = 1
301 # job_queue empty
302 # all workers idle, and no partial jobs
303 # result_queue empty
304 69 ▶ if ($self->{shutting_down} &&
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutting_down"} and not @{$self->{"job_queue"};} and not @{$self->{"result_queue"};}) 5 64 69
Condition66%4/6
$self->{"shutting_down"} and not @{$self->{"job_queue"};} and not @{$self->{"result_queue"};}
!ll&&!rl&&r
6405
$self->{"shutting_down"} and not @{$self->{"job_queue"};}
!ll&&!rl&&r
6405
MC/DC33%1/3
$self->{"shutting_down"} and not @{$self->{"job_queue"};} and not @{$self->{"result_queue"};}
$self->{"shutting_down"} not @{$self->{"job_queue"};} not @{$self->{"result_queue"};}
Truth table50%2/4
A and not(B) and not(C)
A= $self->{"shutting_down"}B= not @{$self->{"job_queue"};}C= not @{$self->{"result_queue"};}
ABCresult
0XX0
10X0
1100
1111
305 5 ! @{ $self->{job_queue} } &&
306 5 ! @{ $self->{result_queue} } ) {
307 5 my $busy=0;
308 5 my $partials = 0;
309 5 for my $s (keys(%$workers)) {
310 13 ▶ if ( ! $workers->{ $s }->{idle}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $workers->{$s}{'idle'}) { } 0 13 13
elsif (exists $workers->{$s}{'partial_job'}) { } 0 13 13
311 0 $busy ++;
312 0 last;
313 } elsif (exists($workers->{ $s }->{partial_job})) {
314 0 $partials ++;
315 0 last;
316 }
317 }
318 5 ▶ if ( ! $busy && ! $partials) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($busy or $partials) 5 0 5
Condition33%1/3
$busy or $partials
l!l&&r!l&&!r
005
MC/DC0%0/2
$busy or $partials
$busy $partials
Truth table33%1/3
A or B
A= $busyB= $partials
ABresult
1X1
011
000
319 # Close all workers
320 5 for my $s (keys(%$workers)) {
321 13 close($workers->{ $s }->{socket});
322 }
323 5 close($self->{app_socket});
324 5 last;
325 }
326 }
327
328 # Set up selectors:
329 # Always check app for read, unless shutting down. App write only if
330 # there's something in @result_queue.
331 64 my (@rpids, @wpids);
332 64 my $rs = IO::Select->new();
333 64 ▶ if ( ! $self->{shutting_down}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"shutting_down"}) 64 0 64
334 64 $rs->add($self->{app_socket});
335 64 push(@rpids, "app");
336 }
337 64 my $ws = IO::Select->new();
338 64 ▶ if ( @{ $self->{result_queue} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"result_queue"};}) 23 41 64
339 23 $ws->add($self->{app_socket});
340 23 push(@wpids, "app");
341 }
342
343 # Check workers for read only if not idle
344 # Otherwise, IF job_queue isn't empty,
345 # check nonidle workers for write.
346 64 for my $s (keys(%$workers)) {
347 178 ▶ if ( $workers->{ $s }->{idle}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($workers->{$s}{'idle'}) { } 86 92 178
348 86 ▶ if ( @{ $self->{job_queue} } || exists($workers->{ $s }->{partial_job})) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"job_queue"};} or exists $workers->{$s}{"partial_job"}) 36 50 86
Condition66%2/3
@{$self->{"job_queue"};} or exists $workers->{$s}{"partial_job"}
l!l&&r!l&&!r
36050
MC/DC50%1/2
@{$self->{"job_queue"};} or exists $workers->{$s}{"partial_job"}
@{$self->{"job_queue"};} exists $workers->{$s}{"partial_job"}
Truth table66%2/3
A or B
A= @{$self->{"job_queue"};}B= exists $workers->{$s}{"partial_job"}
ABresult
1X1
011
000
349 36 $ws->add($workers->{ $s }->{socket});
350 36 push(@wpids, $workers->{ $s }->{pid});
351 }
352 } else {
353 92 $rs->add($workers->{ $s }->{socket});
354 92 push(@rpids, $workers->{ $s }->{pid});
355 }
356 }
357
358 # Blocking
359 64 my @rdy = IO::Select->select($rs, $ws, undef);
360 64 ▶ if ( ! @rdy) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@rdy) 0 64 64
361 0 ▶ if ($! == EINTR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($! == 4) 0 0 0
362 # signal interrupt, continue waiting
363 0 next;
364 }
365 0 croak("select failed: $!");
366 }
367 64 my ($r, $w) = @rdy[0,1];
368
369 # Now we have zero or more reabable sockets, and
370 # zero or more writable sockets, but there's at
371 # least one socket among the two groups.
372 # Read first, as things read can be further handled
373 # by writables immediately afterwards.
374
375 64 for my $rh (@$r) {
376 43 my ($source, $queue, $rstream);
377 43 ▶ if ($rh != $self->{app_socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh != $self->{'app_socket'}) { } 33 10 43
378 33 $source = $workers->{$rh}->{pid};
379 33 $queue = $self->{result_queue};
380 33 $rstream = \$workers->{$rh}->{result_stream};
381 } else {
382 10 $source = 'app';
383 10 $queue = $self->{job_queue};
384 10 $rstream = \$self->{job_stream};
385 }
386  
387 43 $self->log("boss_loop: reading socket\n");
388 43 $self->read($rh, $queue, $rstream, 'boss');
389 43 $self->log("boss_loop: read socket complete\n");
390 }
391  
392 64 for my $wh (@$w) {
393 59 ▶ my $source = exists($workers->{ $wh }) ? $workers->{ $wh }->{pid} : "app";
Branch: 1 branch
BranchTrueFalseTotal
exists $workers->{$wh} ? : 36 23 59
394 59 $self->log("boss_loop: writing socket\n");
395 59 $self->write($wh);
396 59 $self->log("boss_loop: write socket complete\n");
397 }
398 }
399 };
400 5 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 5 5
401 0 croak($@);
402 }
403 }
404  
405 # -----------------------------------------------------------------
406 sub write {
407 59 ▶ my ($self, $socket)=@_;
Subroutine write: called CC=2 SCAR=6.9
Pod undocumented
408 59 ▶ if ($socket == $self->{app_socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($socket == $self->{'app_socket'}) { } 23 36 59
409 23 $self->write_app($socket);
410 } else {
411 36 $self->write_worker($socket);
412 }
413 }
414  
415 # -----------------------------------------------------------------
416 sub write_app {
417 23 ▶ my ($self, $socket)=@_;
Subroutine write_app: called CC=6 SCAR=19.7
Pod undocumented
418
419 # App socket: write all bytes until would block, or complete.
420 # This means process result_queue in order, doing as many elems
421 # as possible. Don't remove from the queue until complete. In
422 # other words, the first item on the queue may be a partial from
423 # the previous write attempt.
424 23 my $queue = $self->{result_queue};
425 23 ▶ while (@$queue) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$queue) 33 23 56
426 33 $self->log("write_app: processing queue entry\n");
427 33 ▶ while ( $queue->[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($queue->[0]) 33 33 66
428 33 my $n = syswrite($socket, $queue->[0]);
429 33 ▶ if ( ! defined($n)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $n) { } 0 33 33
elsif ($n == 0) { } 0 33 33
430 # Block or real socket error
431 0 ▶ if ($! == EWOULDBLOCK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($! == 11) { } 0 0 0
432 # That's it for this socket, try another, or select again.
433 0 return;
434 } else {
435 0 croak("boss write to app: syswrite: $!");
436 }
437 }
438
439 elsif ($n == 0) {
440 # Application error: socket has been closed prematurely by other party.
441 # Boss is supposed to close app socket before app. App tells Boss to
442 # stop, but it only happens after all existing work is completed, and
443 # data is sent back to app.
444 0 croak("boss write to app: peer closed prematurely");
445
446 } else {
447 # wrote some bytes, remove them from the queue elem
448 33 substr($queue->[0], 0, $n) = '';
449 }
450 }
451 # queue elem is empty, remove it, go try next one
452 33 $self->log("write_app: process queue entry complete\n");
453 33 shift(@$queue);
454 }
455 23 $self->log("write_app: all queue entries have been written\n");
456 # queue is empty, all written!
457 }
458
459 # -----------------------------------------------------------------
460 sub write_worker {
461 36 ▶ my ($self, $socket)=@_;
Subroutine write_worker: called CC=7 SCAR=21.0
Pod undocumented
462
463 # A worker: check to see if we have a remaining partial
464 # job we already started to send. If so, continue with this.
465 # Otherwise, take a *single* job off the job_queue, and send that.
466 # When we've gotten either complete, or would block, write remaining
467 # portion to per-worker job-in-progress, or make it '' if complete.
468 # With worker, we only send ONE job, never more.
469 # Once job send is complete, mark worker not-idle.
470
471 36 ▶ if ( ! exists($self->{workers}->{ $socket }->{partial_job})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $self->{'workers'}{$socket}{'partial_job'}) { } 36 0 36
472 36 $self->log("write_worker: processing new job\n");
473 36 ▶ if (@{ $self->{job_queue} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{'job_queue'};}) { } 33 3 36
474 33 $self->{workers}->{ $socket }->{partial_job} = shift(@{ $self->{job_queue} });
475 } else {
476 # Nothing left on queue. Remember, we select on *all* idle workers,
477 # even if there's only one job on the queue.
478 3 return;
479 }
480 } else {
481 0 $self->log("write_worker: processing job remnant\n");
482 }
483 33 my $rjob = \$self->{workers}->{ $socket }->{partial_job};
484
485 33 ▶ while ( length($$rjob) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $$rjob) 33 33 66
486 33 $self->log("write_worker: writing...\n");
487 33 my $n = syswrite($socket, $$rjob);
488 33 ▶ if ( ! defined($n)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $n) { } 0 33 33
elsif ($n == 0) { } 0 33 33
489 # Block or real socket error
490 0 ▶ if ($! == EWOULDBLOCK) {
Branch: 1 branch
BranchTrueFalseTotal
if ($! == 11) { } 0 0 0
491 # That's it for this socket, try another, or select again.
492 0 return;
493 } else {
494 0 croak("boss write to worker: syswrite: $!");
495 }
496 }
497
498 elsif ($n == 0) {
499 # Application error: socket has been closed prematurely by other party.
500 # Boss is supposed to close worker socket before worker - that's how
501 # worker knows to exit.
502 0 croak("boss write to worker: peer closed prematurely (pid " . $self->{workers}->{ $socket }->{pid} . ")");
503
504 } else {
505 # wrote some bytes, remove them from the job
506 33 substr($$rjob, 0, $n) = '';
507 33 $self->log("write_worker: wrote $n bytes\n");
508 }
509 }
510 # job all written!
511 33 $self->log("write_worker: job complete\n");
512 33 delete($self->{workers}->{ $socket }->{partial_job});
513 33 $self->{workers}->{ $socket }->{idle} = 0;
514 }
515  
516 # -----------------------------------------------------------------
517 # Boss exits loop on error, wouldblock, or shutdown msg (socket close).
518 # Worker exits loop on error, recd full record, or boss socket close.
519 # App exits loop on error, recd full record, wouldblock (nb only), early boss close (error).
520 # Stream (as external ref) isn't needed for worker, as it's blocking, and only reads a single
521 # record, no more.
522 # So $rstream can be undef, and if so, we init locally.
523 sub read {
524 113 ▶ my ($self, $socket, $queue, $rstream, $iam)=@_;
Subroutine read: called CC=17 SCAR=29.3
Pod undocumented
525 113 my $stream;
526 113 ▶ $rstream = \$stream if ! defined($rstream);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rstream 46 67 113
527 113 ▶ $$rstream = '' if ! defined($$rstream);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$rstream 62 51 113
528  
529 # croak messaging details...
530 113 my $source;
531 113 ▶ if ($iam eq 'boss') {
Branch: 1 branch
BranchTrueFalseTotal
if ($iam eq 'boss') { } 43 70 113
532 43 ▶ if ($socket == $self->{app_socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($socket == $self->{'app_socket'}) { } 10 33 43
533 10 $source = 'app';
534 } else {
535 33 $source = "worker [$self->{workers}->{$socket}->{pid}]";
536 }
537 } else { # app or worker, same source
538 70 $source = "boss";
539 }
540  
541 113 while ( 1 ) {
542 152 $self->log("read: $iam is reading...\n");
543  
544 152 my $n = sysread($socket, $$rstream, $self->{read_size}, length($$rstream));
545 152 ▶ if ( ! defined($n)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $n) { } 39 113 152
elsif ($n == 0) { } 18 95 113
546 39 ▶ if ($! == EINTR) {
Branch: 2 branches
BranchTrueFalseTotal
if ($! == 4) { } 0 39 39
elsif ($! == 11) { } 39 0 39
547 # signal interrupt, continue reading
548 0 next;
549 } elsif ($! == EWOULDBLOCK) {
550 39 last; # No bytes recd, no need to chunk.
551 } else {
552 0 croak("$iam read from $source: sysread: $!");
553 }
554
555 } elsif ($n == 0) {
556 # Application error: socket has been closed prematurely by other party.
557 # Boss is supposed to close worker socket before worker - that's how
558 # worker knows to exit.
559 # Boss is supposed to close app socket before app. App tells Boss to
560 # stop, but it only happens after all existing work is completed, and
561 # data is sent back to app.
562 18 ▶ if ($iam eq 'boss') {
Branch: 2 branches
BranchTrueFalseTotal
if ($iam eq 'boss') { } 5 13 18
elsif ($iam eq 'worker') { } 13 0 13
563 5 ▶ if ($socket == $self->{app_socket}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($socket == $self->{'app_socket'}) { } 5 0 5
elsif (exists $self->{'workers'}{$socket}) { } 0 0 0
564 5 $self->{shutting_down} = 1;
565 } elsif (exists($self->{workers}->{$socket})) {
566 0 croak("$iam read from $source: peer closed prematurely (pid " . $self->{workers}->{ $socket }->{pid} . ")");
567 }
568 } elsif ($iam eq 'worker') {
569 13 close($socket);
570 } else { # i am app
571 0 croak("$iam read from $source: peer closed prematurely (pid " . $self->{boss_pid} . ")");
572 }
573  
574 # if we didn't croak...
575 18 last;
576
577 } else {
578 # We actually read some bytes. See if we can chunk
579 # out any record(s).
580 95 $self->log("read: $iam read $n bytes\n");
581
582 # Split on delimiter
583 95 my @records = split(/(?<=$self->{msg_delimiter})/, $$rstream);
584  
585 # All but last elem are full records
586 95 my $rcount=$#records;
587 95 push(@$queue, @records[0..$#records-1]);
588  
589 # Deal with last elem, which may or may not be full record
590 95 ▶ if ($records[ $#records ] =~ /$self->{msg_delimiter}$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($records[$#records] =~ /$self->{'msg_delimiter'}$/) { } 95 0 95
591 # We have a full record
592 95 $rcount++;
593 95 $self->log("read: $iam pushing full record onto queue\n");
594 95 push(@$queue, $records[ $#records ]);
595 95 $$rstream = '';
596 95 ▶ if (exists($self->{workers}->{ $socket })) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"workers"}{$socket}) 33 62 95
597 33 $self->{workers}->{ $socket }->{idle} = 1;
598 }
599 } else {
600 0 $$rstream = $records[$#records];
601 }
602  
603 # Boss grabs all it can get, only exiting loop on wouldblock.
604 # App (even nb method), and workers all exit when one full
605 # record is received.
606 95 ▶ last if $rcount && $iam ne 'boss';
Branch: 1 branch
BranchTrueFalseTotal
if $rcount and $iam ne "boss" 56 39 95
Condition66%2/3
$rcount and $iam ne "boss"
!ll&&!rl&&r
03956
MC/DC50%1/2
$rcount and $iam ne "boss"
$rcount $iam ne "boss"
Truth table66%2/3
A and B
A= $rcountB= $iam ne "boss"
ABresult
0X0
100
111
607 }
608 }
609 }
610  
611 # -----------------------------------------------------------------
612 # Worker process; single blocking socket open to boss.
613 # Blocking select loop:
614 # Only do read OR write, not both. We never want more than a single
615 # job at a time. So, if no job currently, read, waiting for one.
616 # Get a job, perform it, and try to write results.
617 # Send delimiter, which tells boss it has all the results, and we're ready
618 # for another job.
619 #
620 sub worker_loop {
621 13 ▶ my ($self)=@_;
Subroutine worker_loop: called CC=8 SCAR=21.1
Pod undocumented
622 13 eval {
623 13 ▶ if ($self->{init_handler}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"init_handler"}) 0 13 13
624 0 $self->log("worker_loop: calling init_handler()\n");
625 0 $self->{init_handler}->();
626 }
627  
628 # String buffers to store serialized data: in and out.
629 13 my $result_stream;
630 13 while ( 1 ) {
631 79 ▶ if (defined($result_stream)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result_stream) { } 33 46 79
632 # We have a result: write it to boss
633 33 $self->log("worker_loop: writing result...\n");
634
635 33 my $n = syswrite( $self->{socket}, $result_stream);
636 33 ▶ croak("worker [$$] write to boss: syswrite: $!") if ! defined($n);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 0 33 33
637 33 ▶ $self->log("worker_loop: wrote $n bytes\n") if defined($n);
Branch: 1 branch
BranchTrueFalseTotal
if defined $n 33 0 33
638 33 $result_stream = undef;
639 # will return to top of loop
640
641 } else {
642 # Get job from boss
643
644 46 my @queue;
645 46 $self->log("worker_loop: reading job from queue...\n");
646 46 $self->read($self->{socket}, \@queue, undef, 'worker');
647 46 ▶ return if ! @queue;
Branch: 1 branch
BranchTrueFalseTotal
unless @queue 13 33 46
648 33 $self->log("worker_loop: read job complete, we have a job\n");
649  
650 33 my $job = $self->deserialize($queue[0]);
651 33 my $result;
652 33 eval {
653 local $SIG{ALRM} = sub {
654 1 ▶ die("BossWorkerAsync: timed out");
Subroutine __ANON__: called CC=1 SCAR=0.0
655 33 };
656  
657 # Set alarm
658 33 alarm($self->{global_timeout});
659  
660 # Invoke handler and get result
661 33 $self->log("worker_loop: calling work_handler for this job\n");
662 33 $result = $self->{work_handler}->($job);
663  
664 # Disable alarm
665 32 alarm(0);
666 };
667  
668 33 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 32 33
669 1 $result = {ERROR => $@};
670 1 $self->log("worker_loop: ERROR: $@\n");
671 }
672
673 33 $result_stream = $self->serialize($result);
674 }
675 }
676 };
677 13 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 13 13
678 0 croak($@);
679 }
680 }
681  
682  
683 # -----------------------------------------------------------------
684 # IN: log message
685 # If verbose is enabled, print the message.
686 sub log {
687 1148 ▶ my ($self, $msg) = @_;
Subroutine log: called CC=2 SCAR=7.2
Pod undocumented
688 1148 ▶ print STDERR $msg if $self->{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 1148 1148
689 }
690  
691  
692 23 1;
693 __END__
↑ Summary