TaskExecutor.pm

filter: Statementstmt 96.2% 154 / 160 Branchbran 80.4% 37 / 46 Conditioncond 66.6% 6 / 9 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 95.8% 23 / 24 Podpod 87.5% 7 / 8 totaltotal 90.5% 229 / 253 CC 27 SCAR 15.4
CC
27
Cov
92%
_fork_and_run
11.0
_remove_done_tasks
6.7
DESTROY
4.0
CRAP 4.7
↑ Summary TaskExecutor/Task.pm »
1 package Parallel::TaskExecutor;
2  
3 54 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 54 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 54 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 54 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 54 ▶use English;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 54 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 54 ▶use Hash::Util 'lock_keys';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 54 ▶use IO::Pipe;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 54 ▶use Log::Any::Simple ':default';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 54 ▶use Parallel::TaskExecutor::Task;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 54 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 54 ▶use Scalar::Util 'weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
16 54 ▶use Time::HiRes 'usleep';
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 54 our @EXPORT_OK = qw(default_executor);
19 54 our %EXPORT_TAGS = (all => \@EXPORT_OK);
20  
21 54 our @CARP_NOT = 'Parallel::TaskExecutor::Task';
22  
23 54 our $VERSION = '0.05'; # Remember to change it in Task.pm too.
24  
25 =pod
26  
27 =encoding utf8
28  
29 =head1 NAME
30  
31 Parallel::TaskExecutor
32  
33 =head1 SYNOPSIS
34  
35 Cross-platform executor for parallel tasks executed in forked processes.
36  
37 my $executor = Parallel::TaskExecutor->new();
38 my $task = $executor->run(sub { return 'foo' });
39 $task->wait();
40 is($task->data(), 'foo');
41  
42 =head1 DESCRIPTION
43  
44 This module provides a simple interface to run Perl code in forked processes and
45 receive the result of their processing. This is quite similar to
46 L<Parallel::ForkManager> with a different OO approach, more centered on the task
47 object that can be seen as a very lightweight promise.
48  
49 Note that this module uses L<Log::Any::Simple> for its logging. So you can use
50 any L<Log::Any::Adapter> to consume its log. For example, put the following in
51 your main application file:
52  
53 use Log::Any::Adapter ('Stderr');
54  
55 In addition, when testing a module that uses B<Parallel::TaskExecutor>, if
56 you’re using L<Test2>, you should add the following line at the beginning of
57 each of your tests to initialize the multi-process feature of the test
58 framework:
59  
60 use Test2::IPC;
61  
62 =head1 METHODS
63  
64 =head2 constructor
65  
66 my $executor = Parallel::TaskExecutor->new(%options);
67  
68 Create a new executor. The main possible option is:
69  
70 =over 4
71  
72 =item *
73  
74 B<max_parallel_tasks> (default = 4): how many different sub-processes
75 can be created in total by this object instance.
76  
77 =back
78  
79 But all the options that can be passed to run() can also be passed to new() and
80 they will apply to all the calls to this object (unless overridden in a specific
81 call to run()).
82  
83 =cut
84  
85 54 Readonly::Scalar my $default_max_parallel_tasks => 4;
86  
87 169 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod undocumented
88 169 my ($class, %options) = @_;
89 my $this = bless {
90 169 ▶ max_parallel_tasks => $options{max_parallel_tasks} // $default_max_parallel_tasks,
Condition66%2/3
$options{"max_parallel_tasks"} // $default_max_parallel_tasks
l!l&&r!l&&!r
114550
MC/DC0%0/2
$options{"max_parallel_tasks"} // $default_max_parallel_tasks
$options{"max_parallel_tasks"} $default_max_parallel_tasks
Truth table66%2/3
A // B
A= $options{"max_parallel_tasks"}B= $default_max_parallel_tasks
ABresult
1X1
011
000
91 options => \%options,
92 current_tasks => 0,
93 # Stores a weak reference to all the non-done tasks that have another
94 # reference held by the user.
95 tasks => {},
96 # Stores a non-weak reference to all the non-done tasks that would have went
97 # out of scope otherwise.
98 zombies => {},
99 pid => $PID,
100 }, $class;
101 169 lock_keys(%{$this});
102 169 return $this;
103 }
104  
105 =pod
106  
107 =head2 destructor
108  
109 When a B<Parallel::TaskExecutor> goes out of scope, its destructor will wait
110 for all the tasks that it started and for which the returned task object is not
111 live. This is a complement to the destructor of L<Parallel::TaskExecutor::Task>
112 which waits for a task to be done if its parent executor is no longer live.
113  
114 =cut
115  
116 115 ▶sub DESTROY {
Subroutine DESTROY: called CC=4 SCAR=13.9
117 115 my ($this) = @_;
118 # TODO: consider if this is the correct thing to do or if we should instead
119 # wait for the task here.
120 115 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 115 115
121 115 ▶ return unless $PID == $this->{pid};
Branch: 1 branch
BranchTrueFalseTotal
unless $Parallel::TaskExecutor::PID == $this->{"pid"} 44 71 115
122 71 ▶ while (my (undef, $c) = each %{$this->{zombies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $c) = each %{$$this{"zombies"};}) 5 71 76
123 # TODO: add an option to abandon the children (but they must be awaited by
124 # someone).
125 5 $c->wait();
126 }
127 71 return;
128 }
129  
130 =pod
131  
132 =head2 default_executor()
133  
134 my $executor = default_executor();
135  
136 Returns a default B<Parallel::TaskExecutor> object with an unspecified
137 parallelism (guaranteed to be more than 1 parallel tasks).
138  
139 =cut
140  
141 54 my $default_executor = Parallel::TaskExecutor->new(max_parallel_tasks => 10);
142  
143 6 ▶sub default_executor {
Subroutine default_executor: called CC=1 SCAR=0.0
Pod documented
144 6 return $default_executor;
145 }
146  
147 54 my $task_count = 0;
148  
149 # This is a very conservative estimates. On modern system the limit is 64kB.
150 54 Readonly::Scalar my $default_response_channel_buffer_size => 4096;
151  
152 565 ▶sub _fork_and_run {
Subroutine _fork_and_run: called CC=11 SCAR=24.0
153 565 my ($this, $sub, %options) = @_;
154 565 my $miso = IO::Pipe->new(); # From the child to the parent.
155 565 my $task_id = $task_count++;
156 565 trace("Will fork for task ${task_id}");
157 565 my $pid = fork();
158 565 ▶ fatal('Cannot fork a sub-process') unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 565 565
159 565 ▶ $this->{current_tasks}++ unless $options{untracked};
Branch: 1 branch
BranchTrueFalseTotal
unless $options{"untracked"} 547 18 565
160  
161 565 ▶ if ($pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 46 519 565
162 # In the child task
163 # TODO: the code here should be moved to the Task class. It would be clearer
164 # and probably allow a better separation of the properties of the Task class
165 # between those used by the executor or those used by the task.
166 46 $miso->writer();
167 46 trace("Starting child task (id == ${task_id}) in process ${PID}");
168  
169 46 ▶ if (exists $options{SIG}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{"SIG"}) 2 44 46
170 2 ▶ while (my ($k, $v) = each %{$options{SIG}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$options{"SIG"};}) 2 2 4
171 2 $SIG{$k} = $v; ## no critic (RequireLocalizedPunctuationVars)
172 }
173 }
174  
175 46 print $miso "ready\n";
176 46 $miso->flush();
177  
178 46 my @out;
179 46 trace("Starting user code in child task (id == ${task_id}) in process ${PID}");
180 46 ▶ if ($options{scalar}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{'scalar'}) { } 2 44 46
181 2 @out = scalar($sub->());
182 } else {
183 44 @out = $sub->();
184 }
185 43 trace("Serializing task result in child task (id == ${task_id}) in process ${PID}");
186 43 my $serialized_out;
187 {
188 43 local $Data::Dumper::Indent = 0;
189 43 local $Data::Dumper::Purity = 1;
190 43 local $Data::Dumper::Sparseseen = 1;
191 43 local $Data::Dumper::Varname = 'TASKEXECUTORVAR';
192 43 $serialized_out = Dumper(\@out);
193 }
194 43 trace("Emitting task result in child task (id == ${task_id}) in process ${PID}");
195 43 my $size = length($serialized_out);
196 43 my $max_size = $default_response_channel_buffer_size;
197 43 ▶ warning("Data returned by process ${PID} for task ${task_id} is too large (%dB)", $size)
Branch: 1 branch
BranchTrueFalseTotal
if $size > $max_size 0 43 43
198 if $size > $max_size;
199 # Nothing will be read before the process terminate, so the data
200 43 print $miso scalar($serialized_out);
201 43 trace("Done sending result in child task (id == ${task_id}) in process ${PID}");
202 43 ▶ close $miso or warning("Can’t close writer side of child task miso channel: ${ERRNO}");
Branch: 1 branch
BranchTrueFalseTotal
close $miso or warning("Can\x{2019}t close writer side of child task miso channel: $Parallel::TaskExecutor::ERRNO") 43 0 43
203 43 trace("Exiting child task (id == ${task_id}) in process ${PID}");
204 43 exit 0;
205 }
206  
207 # Still in the parent task
208 519 trace("Started child task (id == ${task_id}) with pid == ${pid}");
209 519 $miso->reader();
210 my $task = Parallel::TaskExecutor::Task->new(
211 untracked => $options{untracked},
212 task_id => $task_id,
213 runner => $this,
214 state => 'running',
215 channel => $miso,
216 pid => $pid,
217 parent => $PID,
218 519 catch_error => $options{catch_error},);
219 519 weaken($task->{runner});
220 519 $this->{tasks}{$task} = $task;
221 519 weaken($this->{tasks}{$task});
222  
223 519 my $ready = <$miso>;
224 519 ▶ fatal(
Branch: 1 branch
BranchTrueFalseTotal
unless $ready eq "ready\n" 0 519 519
225 "Got unexpected data during ready check of child task (id == ${task_id}) with pid == ${pid}: $ready"
226 ) unless $ready eq "ready\n";
227  
228 519 ▶ if ($options{wait}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options{"wait"}) 15 504 519
229 15 trace("Waiting for child $pid to exit (task id == ${task_id})");
230 15 $task->wait();
231 15 trace("OK, child $pid exited (task id == ${task_id})");
232 }
233 519 return $task;
234 }
235  
236 =pod
237  
238 =head2 run()
239  
240 my $task = $executor->run($sub, %options);
241  
242 Fork a new child process and use it to execute the given I<$sub>. The execution
243 can be tracked using the returned I<$task> object of type
244 L<Parallel::TaskExecutor::Task>.
245  
246 If there are already B<max_parallel_tasks> tasks running, then the call will
247 block until the count of running tasks goes below that limit.
248  
249 The possible options are the following:
250  
251 =over 4
252  
253 =item *
254  
255 B<SIG> (hash-reference): if provided, this specifies a set of signal
256 handlers to be set in the child process. These signal handler are installed
257 before the provided I<$sub> is called and before the call to run() returns.
258  
259 =item *
260  
261 B<wait>: if set to a true value, the call to run will wait for the task
262 to be complete before returning (this means that C<$task->done()> will always be
263 true when you get the task).
264  
265 =item *
266  
267 B<catch_error>: by default, a failure of a child task will abort the parent
268 process. If this option is set to true, the failure will be reported by the task
269 instead.
270  
271 =item *
272  
273 B<scalar>: when set to true, the I<$sub> is called in scalar context. Otherwise
274 it is called in list context.
275  
276 =item *
277  
278 B<forced>: if set to true, the task will be run immediately, even if this means
279 exceeding the value for the B<max_parallel_tasks> passed to the constructor.
280 Note however that the task will still increase by one the number of running
281 tasks tracked by the executor (unless B<untracked> is also set to true).
282  
283 =item *
284  
285 B<untracked>: if set to true, the task will not increase the number of running
286 task counted by the executor. However, the call to run() might still be blocked
287 if the number of outstanding tasks exceeds B<max_parallel_tasks> (unless
288 B<forced> is set to true too).
289  
290 =back
291  
292 =cut
293  
294 54 Readonly::Scalar my $busy_loop_wait_time_us => 1000;
295  
296 547 ▶sub run {
Subroutine run: called CC=3 SCAR=11.0
Pod documented
297 547 my ($this, $sub, %options) = @_;
298 547 %options = (%{$this->{options}}, %options);
299 # TODO: add an option to always call _remove_done_tasks here, to cleanup.
300 547 ▶ while (!$options{forced} && $this->{current_tasks} >= $this->{max_parallel_tasks}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $options{"forced"} and $this->{"current_tasks"} >= $this->{"max_parallel_tasks"}) 58348 547 58895
Condition66%2/3
not $options{"forced"} and $this->{"current_tasks"} >= $this->{"max_parallel_tasks"}
!ll&&!rl&&r
054758348
MC/DC50%1/2
not $options{"forced"} and $this->{"current_tasks"} >= $this->{"max_parallel_tasks"}
not $options{"forced"} $this->{"current_tasks"} >= $this->{"max_parallel_tasks"}
Truth table66%2/3
not(A) and B
A= not $options{"forced"}B= $this->{"current_tasks"} >= $this->{"max_parallel_tasks"}
ABresult
0X0
100
111
301 58348 $this->_remove_done_tasks();
302 58348 usleep($busy_loop_wait_time_us);
303 }
304 547 return $this->_fork_and_run($sub, %options);
305 }
306  
307 =pod
308  
309 =head2 run_now()
310  
311 my $data = $executor->run_now($sub, %options);
312  
313 Runs the given I<$sub> in a forked process and waits for its result. This never
314 blocks (the I<$sub> is run even if the executor max parallelism is already
315 reached) and this does not increase the counted parallelism of the executor
316 either (in effect the B<untracked>, B<forced>, and B<wait> options are set to
317 true).
318  
319 In addition, the B<scalar> option is set to true if this method is called in
320 scalar context, unless that option was explicitly passed to the run_now() call.
321  
322 =cut
323  
324 18 ▶sub run_now {
Subroutine run_now: called CC=3 SCAR=11.0
Pod documented
325 18 my ($this, $sub, %options) = @_;
326 18 ▶ $options{scalar} = 1 unless exists $options{scalar} || wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options{"scalar"} or wantarray 13 5 18
Condition66%2/3
exists $options{"scalar"} or wantarray
l!l&&r!l&&!r
0513
MC/DC50%1/2
exists $options{"scalar"} or wantarray
exists $options{"scalar"} wantarray
Truth table66%2/3
A or B
A= exists $options{"scalar"}B= wantarray
ABresult
1X1
011
000
327 18 my $task = $this->_fork_and_run($sub, %options, untracked => 1, wait => 1);
328 15 $task->wait();
329 15 return $task->data();
330 }
331  
332 =pod
333  
334 =head2 wait()
335  
336 $executor->wait();
337  
338 Waits for all the outstanding tasks to terminate. This waits for all the tasks
339 independently of whether their L<Parallel::TaskExecutor::Task> object is still
340 live.
341  
342 =cut
343  
344 3 ▶sub wait { ## no critic (ProhibitBuiltinHomonyms)
Subroutine wait: called CC=4 SCAR=13.9
Pod documented
345 3 my ($this) = @_;
346 3 my $nb_children = $this->{current_tasks};
347 3 ▶ return unless $nb_children;
Branch: 1 branch
BranchTrueFalseTotal
unless $nb_children 0 3 3
348 3 debug("Waiting for ${nb_children} running tasks...");
349 3 ▶ while (my (undef, $c) = each %{$this->{zombies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $c) = each %{$$this{"zombies"};}) 2 3 5
350 # $c is never weak here and wait() will also not delete from this hash
351 # itself
352 2 $c->wait();
353 2 delete $this->{zombies}{$c}; # $c is both the key and the value.
354 }
355 3 ▶ while (my (undef, $c) = each %{$this->{tasks}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $c) = each %{$$this{"tasks"};}) 1 3 4
356 # $c can be a weak reference, but it should never be undef because the task
357 # will remove itself from this hash when it’s done (and the reference is
358 # unweakened when it’s the last reference to the task).
359 # $c->wait() will delete this entry from the hash, but this is legal when
360 # looping with each.
361 1 $c->wait();
362 }
363 3 return;
364 }
365  
366 =pod
367  
368 =head2 set_max_parallel_tasks()
369  
370 $executor->set_max_parallel_tasks(N)
371  
372 Sets the B<max_parallel_tasks> option of the executor.
373  
374 =cut
375  
376 0 ▶sub set_max_parallel_tasks {
Subroutine set_max_parallel_tasks: not called CC=1 SCAR=6.9
Pod documented
377 0 my ($this, $max_parallel_tasks) = @_;
378 0 $this->{max_parallel_tasks} = $max_parallel_tasks;
379 0 return;
380 }
381  
382 58348 ▶sub _remove_done_tasks {
Subroutine _remove_done_tasks: called CC=6 SCAR=19.1
383 58348 my ($this) = @_;
384 58348 my $done = 0;
385 58348 ▶ while (my (undef, $c) = each %{$this->{zombies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $c) = each %{$$this{"zombies"};}) 0 58348 58348
386 0 ▶ if ($c->_try_wait()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->_try_wait) 0 0 0
387 0 delete $this->{zombies}{$c};
388 0 $done += 1;
389 }
390 }
391 58348 ▶ while (my (undef, $c) = each %{$this->{tasks}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(undef, $c) = each %{$$this{"tasks"};}) 152078 58348 210426
392 # See the comment in wait()
393 152078 ▶ $done += $c->_try_wait() ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$c->_try_wait ? : 356 151722 152078
394 }
395 58348 ▶ debug("Removed ${done} done tasks") if $done;
Branch: 1 branch
BranchTrueFalseTotal
if $done 356 57992 58348
396 58348 return;
397 }
398  
399 =pod
400  
401 =head2 signal_all()
402  
403 $executor->signal_all('HUP');
404  
405 Sends the given signal all the tasks. See L<Parallel::TaskExecutor::Task/signal>
406 for more details.
407  
408 =cut
409  
410 1 ▶sub signal_all {
Subroutine signal_all: called CC=1 SCAR=0.0
Pod documented
411 1 my ($this, $signal) = @_;
412 # See the comment in wait() for why $c can never be undef although it is a weak
413 # reference.
414 1 kill $signal, map { $_->pid() } values %{$this->{tasks}}, values %{$this->{zombies}};
415 1 return;
416 }
417  
418 =pod
419  
420 =head2 kill_all()
421  
422 $executor->kill_all();
423  
424 Same as L<signal_all()|/signal_all> but sends the C<SIGKILL> signal by default.
425 You can still pass a specific signal if you want.
426  
427 =cut
428  
429 1 ▶sub kill_all {
Subroutine kill_all: called CC=1 SCAR=0.0
Pod documented
430 1 my ($this, $signal) = (@_, 'KILL');
431 1 return $this->signal_all($signal);
432 }
433  
434 54 1;
435  
436 =pod
437  
438 =head1 CAVEATS AND TODOS
439  
440 =over 4
441  
442 =item *
443  
444 The data returned by a child task can only have a limited size (4kB as of
445 writing this). In a future release, we may switch to using temporary files to
446 pass the result when this limit is reached.
447  
448 =item *
449  
450 There is currently no support to setup uni or bi-directional communication
451 channel with the child task. This must be done manually by the user.
452  
453 =back
454  
455 =head1 AUTHOR
456  
457 This program has been written by L<Mathias Kende|mailto:mathias@cpan.org>.
458  
459 =head1 LICENSE
460  
461 Copyright 2024 Mathias Kende
462  
463 This program is distributed under the MIT (X11) License:
464 L<http://www.opensource.org/licenses/mit-license.php>
465  
466 Permission is hereby granted, free of charge, to any person
467 obtaining a copy of this software and associated documentation
468 files (the "Software"), to deal in the Software without
469 restriction, including without limitation the rights to use,
470 copy, modify, merge, publish, distribute, sublicense, and/or sell
471 copies of the Software, and to permit persons to whom the
472 Software is furnished to do so, subject to the following
473 conditions:
474  
475 The above copyright notice and this permission notice shall be
476 included in all copies or substantial portions of the Software.
477  
478 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
479 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
480 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
481 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
482 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
483 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
484 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
485 OTHER DEALINGS IN THE SOFTWARE.
486  
487 =head1 SEE ALSO
488  
489 =over 4
490  
491 =item L<AnyEvent>
492  
493 =item L<IPC::Run>
494  
495 =item L<Parallel::ForkManager>
496  
497 =item L<Promise::XS>
498  
499 =back
500  
501 =cut
↑ Summary TaskExecutor/Task.pm »