blib/lib/Parallel/WorkUnit.pm untested

filter: Statementstmt 0.0% 0 / 454 Branchbran 0.0% 0 / 196 Conditioncond 0.0% 0 / 15 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 48 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 746 CC 99 SCAR 33.4
CC
99
Cov
0%
async
90.0
max_children
56.0
waitall
56.0
CRAP 28.2
1  
2 # Copyright (C) 2015-2020 Joelle Maslak
3 # All Rights Reserved - See License
4 #
5  
6 package Parallel::WorkUnit;
7 $Parallel::WorkUnit::VERSION = '2.202270';
8 use v5.8;
9  
10 # ABSTRACT: Provide multi-paradigm forking with ability to pass back data
11  
12 use strict;
13 use warnings;
14 use autodie;
15  
16 use Carp;
17  
18 use overload;
19 use IO::Handle;
20 use IO::Pipely qw(pipely);
21 use IO::Select;
22 use POSIX ':sys_wait_h';
23 use Scalar::Util qw(blessed reftype weaken);
24 use Storable;
25 use Try::Tiny;
26  
27 use namespace::autoclean;
28  
29  
30 my @ALL_WU; # Holds all active work units so child processes can't
31 # mess with parent work units
32 # Note it holds a reference (strong) to a reference
33 # (weak).
34  
35  
36 sub use_anyevent {
37 if ( $#_ == 0 ) {
38 return shift->{use_anyevent};
39 } elsif ( $#_ == 1 ) {
40 my ( $self, $val ) = @_;
41  
42 my ($old_val) = $self->{use_anyevent};
43 $self->{use_anyevent} = $val;
44  
45 # Trigger
46 $self->_set_anyevent( $val, $old_val );
47  
48 return $val;
49 } else {
50 confess("Invalid call");
51 }
52 }
53  
54 # XXX: Add validation that _cv is a Maybe[AnyEvent::CondVar]
55 sub _cv {
56 if ( $#_ == 0 ) {
57 return shift->{_cv};
58 } elsif ( $#_ == 1 ) {
59 my ( $self, $val ) = @_;
60 $self->{_cv} = $val;
61 return $val;
62 } else {
63 confess("Invalid call");
64 }
65 }
66  
67 # XXX: Add validation that _last_error is a Maybe[Str]
68 sub _last_error {
69 if ( $#_ == 0 ) {
70 return shift->{_last_error};
71 } elsif ( $#_ == 1 ) {
72 my ( $self, $val ) = @_;
73 $self->{_last_error} = $val;
74 return $val;
75 } else {
76 confess("Invalid call");
77 }
78 }
79  
80 # XXX: Add validation that _ordered_count is a non-negative integer
81 sub _ordered_count {
82 if ( $#_ == 0 ) {
83 my $self = shift;
84  
85 # Initialize
86 if ( !exists( $self->{_ordered_count} ) ) { $self->{_ordered_count} = 0; }
87  
88 return $self->{_ordered_count};
89 } elsif ( $#_ == 1 ) {
90 my ( $self, $val ) = @_;
91 $self->{_ordered_count} = $val;
92 return $val;
93 } else {
94 confess("Invalid call");
95 }
96 }
97  
98 # XXX: Add validation that _ordered_responses is an ArrayRef
99 sub _ordered_responses {
100 if ( $#_ == 0 ) {
101 my $self = shift;
102  
103 # Initialize
104 if ( !exists( $self->{_ordered_responses} ) ) { $self->{_ordered_responses} = []; }
105  
106 return $self->{_ordered_responses};
107 } elsif ( $#_ == 1 ) {
108 my ( $self, $val ) = @_;
109 $self->{_ordered_responses} = $val;
110 return $val;
111 } else {
112 confess("Invalid call");
113 }
114 }
115  
116  
117 sub max_children {
118 if ( $#_ == 0 ) {
119 my $self = shift;
120  
121 if ( !exists( $self->{max_children} ) ) { $self->{max_children} = 5; }
122  
123 return $self->{max_children};
124 } elsif ( $#_ == 1 ) {
125 my ( $self, $val ) = @_;
126  
127 # Validate
128 if ( defined($val) ) {
129 if ( $val !~ m/^[0-9]+$/s ) {
130 confess("max_children must be set to a positive integer");
131 }
132 if ( $val <= 0 ) {
133 confess("max_children must be set to a positive integer");
134 }
135 }
136  
137 $self->{max_children} = $val;
138  
139 # Trigger
140 $self->_start_queued_children();
141  
142 return $val;
143 } else {
144 confess("Invalid call");
145 }
146 }
147  
148 # XXX: Add validation that _subprocs is a HashRef
149 sub _subprocs {
150 if ( $#_ == 0 ) {
151 my $self = shift;
152  
153 # Initial value
154 if ( !exists( $self->{_subprocs} ) ) { $self->{_subprocs} = {}; }
155  
156 return $self->{_subprocs};
157 } elsif ( $#_ == 1 ) {
158 my ( $self, $val ) = @_;
159 $self->{_subprocs} = $val;
160 return $val;
161 } else {
162 confess("Invalid call");
163 }
164 }
165  
166 # XXX: Add validation that _count is a positive integer
167 # This only gets used on Win32.
168 sub _count {
169 if ( $#_ == 0 ) {
170 my $self = shift;
171  
172 # Initial value
173 if ( !exists( $self->{_count} ) ) { $self->{_count} = 1; }
174  
175 return $self->{_count};
176 } elsif ( $#_ == 1 ) {
177 my ( $self, $val ) = @_;
178 $self->{_count} = $val;
179 return $val;
180 } else {
181 confess("Invalid call");
182 }
183 }
184  
185 # XXX: Add validation that _parent_pid is a positive integer
186 # We also need to initialize always in the parent process.
187 sub _parent_pid {
188 if ( $#_ == 0 ) {
189 return shift->{_parent_pid};
190 } elsif ( $#_ == 1 ) {
191 my ( $self, $val ) = @_;
192 $self->{_parent_pid} = $val;
193 return $val;
194 } else {
195 confess("Invalid call");
196 }
197 }
198  
199 # Children queued
200 # XXX: Add validation that _queued_cildren is an
201 # ArrayRef[ArrayRef[CodeRef]]
202 sub _queued_children {
203 if ( $#_ == 0 ) {
204 my $self = shift;
205  
206 if ( !exists( $self->{_queued_children} ) ) { $self->{_queued_children} = []; }
207  
208 return $self->{_queued_children};
209 } elsif ( $#_ == 1 ) {
210 my ( $self, $val ) = @_;
211 $self->{_queued_children} = $val;
212 return $val;
213 } else {
214 confess("Invalid call");
215 }
216 }
217  
218  
219 sub new {
220 my $class = shift;
221 my $self = {};
222 bless $self, $class;
223  
224 # Initialize parent PID
225 $self->_parent_pid($$);
226  
227 # Make a weak reference and shove it into the ALL_WU array
228 my $weakself = $self;
229 weaken $weakself;
230 push @ALL_WU, \$weakself;
231  
232 # Do some housekeeping on @ALL_WU, so it is somewhat bounded
233 @ALL_WU = grep { defined $$_ } @ALL_WU;
234  
235 # Do we have any arguments?
236 if (scalar(@_) > 0) {
237 my %args = (scalar(@_) == 1) ? %{shift()} : @_;
238  
239 if (exists $args{use_anyevent}) {
240 $self->use_anyevent($args{use_anyevent});
241 }
242 if (exists $args{max_children}) {
243 $self->max_children($args{max_children});
244 }
245 }
246  
247 return $self;
248 }
249  
250  
251 sub async {
252 if ( $#_ < 1 ) { confess 'invalid call'; }
253 my $self = shift;
254 my $sub = shift;
255  
256 # Test $sub to make sure it is a code ref or a sub ref
257 if ( !_codelike($sub) ) {
258 confess("Parameter to async() is not a code (or codelike) reference");
259 }
260  
261 my $callback;
262 if ( scalar(@_) == 0 ) {
263 # No callback provided
264  
265 my $cbnum = $self->_ordered_count;
266 $self->_ordered_count( $cbnum + 1 );
267  
268 # We create a callback that populates the ordered responses
269 my $selfref = $self;
270 weaken $selfref;
271 $callback = sub {
272 if ( defined $selfref ) { # Incase this went away
273 @{ $selfref->_ordered_responses }[$cbnum] = shift;
274 }
275 };
276 } elsif ( scalar(@_) == 1 ) {
277 # Callback provided
278 $callback = shift;
279 } else {
280 confess 'invalid call';
281 }
282  
283 # If there are pending errors, throw that.
284 if ( defined( $self->_last_error ) ) { die( $self->_last_error ); }
285  
286 my $pipe = [ pipely() ];
287  
288 my $pid = fork();
289  
290 if ($pid) {
291 # We are in the parent process
292  
293 $pipe = $pipe->[0];
294  
295 $self->_subprocs()->{$pid} = {
296 fh => $pipe,
297 anyevent => undef,
298 callback => $callback,
299 caller => [ caller() ],
300 };
301  
302 # Set up anyevent listener if appropriate
303 if ( $self->use_anyevent() ) {
304 $self->_add_anyevent_watcher($pid);
305 }
306  
307 return $pid;
308  
309 } else {
310 # We are in the child process
311 $pipe = $pipe->[1];
312  
313 return $self->_child( $sub, $pipe );
314 }
315 }
316  
317  
318 sub asyncs {
319 if ( $#_ < 2 ) { confess 'invalid call'; }
320 my $self = shift;
321 my $children = shift;
322 my $sub = shift;
323 if ( scalar(@_) > 1 ) { confess("invalid call"); }
324  
325 if ( $children !~ m/^[1-9][0-9]*$/s ) {
326 confess("Number of children must be a numeric value > 0");
327 }
328  
329 for ( my $i = 0; $i < $children; $i++ ) {
330 $self->async( sub { return $sub->($i); }, @_ );
331 }
332  
333 return $children;
334 }
335  
336 sub _child {
337 if ( scalar(@_) != 3 ) { confess 'invalid call'; }
338 my ( $self, $sub, $pipe ) = @_;
339  
340 # Cleanup ALL_WU
341 @ALL_WU = grep { defined $$_ } @ALL_WU;
342 foreach my $wu ( map { $$_ } @ALL_WU ) {
343 $wu->_clear_all();
344 }
345  
346 try {
347 my $result = $sub->();
348 $self->_send_result( $pipe, $result );
349 } catch {
350 $self->_send_error( $pipe, $_ );
351 };
352  
353 exit();
354 }
355  
356  
357 sub waitall {
358 if ( $#_ != 0 ) { confess 'invalid call'; }
359 my ($self) = @_;
360  
361 # No subprocs? Just return.
362 if ( scalar( keys %{ $self->_subprocs } ) == 0 ) {
363 if ( $self->use_anyevent ) {
364 $self->_cv( AnyEvent->condvar );
365 }
366  
367 return $self->_get_and_reset_ordered_responses();
368 }
369  
370 # Using AnyEvent?
371 if ( defined( $self->_cv ) ) {
372 $self->_cv->recv();
373 if ( defined( $self->_last_error ) ) {
374 my $err = $self->_last_error;
375 $self->_last_error(undef);
376  
377 die($err);
378 }
379  
380 return $self->_get_and_reset_ordered_responses();
381 }
382  
383 # Tail recursion
384 if ( $self->_waitone() ) { goto &waitall }
385  
386 return @{ $self->_get_and_reset_ordered_responses() };
387 }
388  
389 # Gets the _ordered_responses and returns the reference. Also
390 # resets the _ordered_responses and the _ordered_counts to an
391 # empty list and zero respectively.
392 sub _get_and_reset_ordered_responses {
393 if ( $#_ != 0 ) { confess 'invalid call'; }
394 my $self = shift;
395  
396 my (@r) = @{ $self->_ordered_responses() };
397  
398 $self->_ordered_responses( [] );
399 $self->_ordered_count(0);
400  
401 return @r;
402 }
403  
404  
405 sub waitone {
406 if ( $#_ != 0 ) { confess 'invalid call'; }
407 my ($self) = @_;
408  
409 my $rv = $self->_waitone();
410  
411 # Using AnyEvent?
412 if ( defined( $self->_last_error ) ) {
413 my $err = $self->_last_error;
414 $self->_last_error(undef);
415  
416 die($err);
417 }
418  
419 return $rv;
420 }
421  
422 # Meat of waitone (but doesn't handle returning an exception when using
423 # anyevent)
424 sub _waitone {
425 if ( $#_ != 0 ) { confess 'invalid call'; }
426 my ($self) = @_;
427  
428 my $sp = $self->_subprocs();
429 weaken $sp; # To avoid some Windows warnings
430 if ( !keys(%$sp) ) { return; }
431  
432 # On everything but Windows
433 #
434 my $s = IO::Select->new();
435 foreach ( keys(%$sp) ) { $s->add( $sp->{$_}{fh} ); }
436  
437 my @ready = $s->can_read();
438  
439 foreach my $fh (@ready) {
440 foreach my $child ( keys(%$sp) ) {
441 if ( defined( $fh->fileno() ) ) {
442 if ( $fh->fileno() == $sp->{$child}{fh}->fileno() ) {
443 $self->_read_result($child);
444  
445 waitpid( $child, 0 );
446  
447 # Start queued children, if needed
448 $self->_start_queued_children();
449  
450 return 1; # We don't want to read more than one!
451 }
452 }
453 }
454 }
455  
456 # We should never get here
457 return;
458 }
459  
460  
461 ## no critic ('Subroutines::ProhibitBuiltinHomonyms')
462 sub wait {
463 if ( $#_ != 1 ) { confess 'invalid call'; }
464 my ( $self, $pid ) = @_;
465  
466 my $rv = $self->_wait($pid);
467  
468 if ( defined( $self->_last_error ) ) {
469 my $err = $self->_last_error;
470 $self->_last_error(undef);
471  
472 die($err);
473 }
474  
475 return $rv;
476 }
477  
478 # Internal version that doesn't check for AnyEvent die needs
479 sub _wait {
480 if ( $#_ != 1 ) { confess 'invalid call'; }
481 my ( $self, $pid ) = @_;
482  
483 if ( !exists( $self->_subprocs()->{$pid} ) ) {
484  
485 # We don't warn/die because it's possible that there is
486 # a race between callback and here, in the main thread.
487 return;
488 }
489  
490 my $result = $self->_read_result($pid);
491  
492 waitpid( $pid, 0 );
493  
494 return $result;
495 }
496 ## use critic
497  
498  
499 sub count {
500 if ( $#_ != 0 ) { confess 'invalid call'; }
501 my ($self) = @_;
502  
503 my $sp = $self->_subprocs();
504 return scalar( keys %$sp );
505 }
506  
507  
508 sub queue {
509 if ( $#_ < 1 ) { confess 'invalid call'; }
510 my $self = shift;
511 my $sub = shift;
512  
513 # Test $sub to make sure it is a code ref or a sub ref
514 if ( !_codelike($sub) ) {
515 confess("Parameter to queue() is not a code (or codelike) reference");
516 }
517  
518 my $callback;
519 if ( scalar(@_) == 0 ) {
520 # We're okay, don't need to do anything - no callback
521 } elsif ( scalar(@_) == 1 ) {
522 # We have a callback
523 $callback = shift;
524 } else {
525 confess 'invalid call';
526 }
527  
528 # If there are pending errors, throw that.
529 if ( defined( $self->_last_error ) ) { die( $self->_last_error ); }
530  
531 push @{ $self->_queued_children }, [ $sub, $callback ];
532 return $self->_start_queued_children();
533 }
534  
535 sub _send_result {
536 if ( $#_ != 2 ) { confess 'invalid call'; }
537 my ( $self, $fh, $msg ) = @_;
538  
539 return $self->_send( $fh, 'RESULT', $msg );
540 }
541  
542 sub _send_error {
543 if ( $#_ != 2 ) { confess 'invalid call'; }
544 my ( $self, $fh, $err ) = @_;
545  
546 return $self->_send( $fh, 'ERROR', $err );
547 }
548  
549 sub _send {
550 if ( $#_ != 3 ) { confess 'invalid call'; }
551 my ( $self, $fh, $type, $data ) = @_;
552  
553 my $msg = Storable::freeze( \$data );
554  
555 if ( !defined($msg) ) {
556 die 'freeze() returned undef for child return value';
557 }
558  
559 $fh->write($type);
560 $fh->write("\n");
561  
562 $fh->write( length($msg) );
563 $fh->write("\n");
564  
565 binmode( $fh, ':raw' );
566  
567 $fh->write($msg);
568  
569 $fh->close();
570 return;
571 }
572  
573 sub _read_result {
574 if ( $#_ != 1 ) { confess 'invalid call'; }
575 my ( $self, $child ) = @_;
576  
577 my $cinfo = $self->_subprocs()->{$child};
578 my $fh = $cinfo->{fh};
579  
580 my $type = <$fh>;
581 if ( !defined($type) ) { die 'Could not read child data'; }
582 chomp($type);
583  
584 my $size = <$fh>;
585 chomp($size);
586  
587 binmode($fh);
588  
589 my $result = '';
590  
591 my $ret = 1;
592 while ( defined($ret) && ( length($result) < $size ) ) {
593 my $s = $size - length($result);
594  
595 my $part = '';
596 $ret = $fh->read( $part, $s );
597 if ( defined($ret) ) { $result .= $part; }
598 }
599  
600 my $data = ${ Storable::thaw($result) };
601  
602 my $caller = $self->_subprocs()->{$child}{caller};
603 delete $self->_subprocs()->{$child};
604 $fh->close();
605  
606 if ( $type eq 'RESULT' ) {
607 $cinfo->{callback}->($data);
608 } else {
609 my $err =
610 "Child (created at "
611 . $caller->[1]
612 . " line "
613 . $caller->[2]
614 . ") died with error: $data";
615  
616 if ( $self->use_anyevent ) {
617 # Can't throw events with anyevent
618 $self->_last_error($err);
619 } else {
620 # Otherwise we do throw it
621 die($err);
622 }
623 }
624  
625 return;
626 }
627  
628 # Start queued children, if possible.
629 # Returns 1 if children were started, undef otherwise
630 sub _start_queued_children {
631 if ( $#_ != 0 ) { confess 'invalid call' }
632 my ($self) = @_;
633  
634 if ( !( @{ $self->_queued_children } ) ) { return; }
635 if ( defined( $self->_last_error ) ) { return; } # Do not queue if there are errors
636  
637 # Can we start a queued process?
638 while ( scalar @{ $self->_queued_children } ) {
639 if ( ( !defined( $self->max_children ) ) || ( $self->count < $self->max_children ) ) {
640 # Start queued child
641 my $ele = shift @{ $self->_queued_children };
642 if ( !defined( $ele->[1] ) ) {
643 $self->async( $ele->[0] );
644 } else {
645 $self->async( $ele->[0], $ele->[1] );
646 }
647 } else {
648 # Can't unqueue
649 return;
650 }
651 }
652  
653 # We started at least one process
654 return 1;
655 }
656  
657 # Sets up AnyEvent or tears it down as needed
658 sub _set_anyevent {
659 if ( $#_ < 1 ) { confess 'invalid call' }
660 if ( $#_ > 2 ) { confess 'invalid call' }
661 my ( $self, $new, $old ) = @_;
662  
663 if ( ( !$old ) && $new ) {
664 # We are setting up AnyEvent
665 require AnyEvent;
666  
667 if ( defined( $self->_subprocs() ) ) {
668 foreach my $pid ( keys %{ $self->_subprocs() } ) {
669 $self->_add_anyevent_watcher($pid);
670 }
671 }
672  
673 $self->_cv( AnyEvent->condvar );
674  
675 } elsif ( $old && ( !$new ) ) {
676 # We are tearing down AnyEvent
677  
678 if ( defined( $self->_subprocs() ) ) {
679 foreach my $pid ( keys %{ $self->_subprocs() } ) {
680 my $proc = $self->_subprocs()->{$pid};
681  
682 $proc->{anyevent} = undef;
683 }
684 }
685  
686 $self->_cv(undef);
687 }
688 return;
689 }
690  
691 # Sets up the listener for AnyEvent
692 sub _add_anyevent_watcher {
693 if ( $#_ != 1 ) { confess 'invalid call' }
694 my ( $self, $pid ) = @_;
695  
696 my $proc = $self->_subprocs()->{$pid};
697  
698 $proc->{anyevent} = AnyEvent->io(
699 fh => $proc->{fh},
700 poll => 'r',
701 cb => sub {
702 $self->_wait($pid);
703 if ( scalar( keys %{ $self->_subprocs() } ) == 0 ) {
704 my $oldcv = $self->_cv;
705 $self->_cv( AnyEvent->condvar );
706 $oldcv->send();
707 }
708  
709 # Start queued children, if needed
710 $self->_start_queued_children();
711 },
712 );
713  
714 return;
715 }
716  
717 # Used to clear all sub-processes, etc, in child process.
718 sub _clear_all {
719 if ( $#_ != 0 ) { confess 'invalid call' }
720 my ( $self ) = @_;
721  
722 $self->_cv(undef);
723 $self->_last_error(undef);
724 $self->_ordered_count(0);
725 $self->_ordered_responses( [] );
726 $self->_count(1);
727 $self->_queued_children( [] );
728  
729 do {
730 # Don't warn on AnyEvent in child threads being DESTROYed
731 local $SIG{__WARN__} = sub { };
732 $self->_subprocs( {} );
733 };
734  
735 return;
736 }
737  
738  
739 sub start {
740 if ( $#_ != 1 ) { confess 'invalid call'; }
741 my $self = shift;
742 my $sub = shift;
743  
744 # Test $sub to make sure it is a code ref or a sub ref
745 if ( !_codelike($sub) ) {
746 confess("Parameter to start() is not a code (or codelike) reference");
747 }
748  
749 my $pid = fork();
750  
751 if ( !$pid ) {
752 # We are in the child process.
753 $sub->();
754 exit();
755 }
756  
757 return;
758 }
759  
760 # Tests to see if something is codelike
761 #
762 # Borrowed from Params::Util (written by Adam Kennedy)
763 sub _codelike {
764 if ( scalar(@_) != 1 ) { confess 'invalid call' }
765 my $thing = shift;
766  
767 if ( reftype($thing) ) { return 1; }
768 if ( blessed($thing) && overload::Method( $thing, '()' ) ) { return 1; }
769  
770 return;
771 }
772  
773 # Destructor emits warning if sub processes are running
774 sub DESTROY {
775 my $self = shift;
776  
777 if ( scalar( keys %{ $self->_subprocs } ) ) {
778 warn "Warning: Subprocesses running when Parallel::WorkUnit object destroyed\n";
779 }
780  
781 return;
782 }
783  
784 1;
785  
786 __END__