TaskExecutor/Task.pm

filter: Statementstmt 100% 108 / 108 Branchbran 83.3% 40 / 48 Conditioncond 66.6% 2 / 3 MC/DCmcdc 50.0% 1 / 2 Subroutinesub 100% 22 / 22 Podpod 77.7% 7 / 9 totaltotal 93.7% 180 / 192 CC 26 SCAR 13.9
CC
26
Cov
94%
_process_done
9.0
wait
5.0
DESTROY
5.0
CRAP 4.0
« TaskExecutor.pm ↑ Summary
1 package Parallel::TaskExecutor::Task;
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 English;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 54 ▶use Hash::Util 'lock_keys';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 54 ▶use Log::Any::Simple ':default';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 54 ▶use POSIX ':sys_wait_h';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 54 ▶use Scalar::Util 'unweaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 54 our $VERSION = '0.05'; # Remember to change it in TaskExecutor.pm too.
14  
15 =pod
16  
17 =encoding utf8
18  
19 =head1 NAME
20  
21 Parallel::TaskExecutor::Tasks
22  
23 =head1 SYNOPSIS
24  
25 A simple task (or promise) class for the L<Parallel::TaskExecutor> package.
26  
27 my $executor = Parallel::TaskExecutor->new();
28 my $task = $executor->run(sub { return 'foo' });
29 $task->wait();
30 is($task->data(), 'foo');
31  
32 =head1 DESCRIPTION
33  
34 The tasks that this class exposes are lightweight promises that can be used to
35 wait for the end of the parallel processing and read the result of that
36 processing.
37  
38 =head1 METHODS
39  
40 =head2 constructor
41  
42 The constructor of this class is private, it can only be built by
43 L<Parallel::TaskExecutor> through a call to L<run()|Parallel::TaskExecutor/run>.
44  
45 =cut
46  
47 519 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
48 519 my ($class, %data) = @_;
49 # %data can be anything that is needed by Parallel::TaskExecutor. However the
50 # following values are used by Parallel::TaskExecutor::Task too:
51 # - state: one of new, running, done
52 # - pid: the PID of the task
53 # - parent: the PID of the parent process. We don’t do anything if we’re
54 # called in a different process.
55 # - task_id: arbitrary identifier for the task
56 # - runner: Parallel::TaskExecutor runner for this task, kept as a weak
57 # reference
58 # - untracked: don’t count this task toward the task limit of its runner
59 # - catch_error: if false, a failed task will abort the parent.
60 # - channel: may be set to read the data produced by the task
61 # - data: will contain the data read from the channel.
62 519 my $this = bless {%data, data => undef, error => undef}, $class;
63 519 lock_keys(%{$this});
64 519 return $this;
65 }
66  
67 =pod
68  
69 =head2 destructor
70  
71 The destructor of a B<Parallel::TaskExecutor::Task> object will block until the
72 task is done if you no longer keep a reference to its parent
73 L<Parallel::TaskExecutor> object. If the parent executor is still live, then
74 that object will be responsible to wait for the end of the task (either through
75 an explicit call to L<wait()|Parallel::TaskExecutor/wait> or in its destructor).
76  
77 =cut
78  
79 526 ▶sub DESTROY {
Subroutine DESTROY: called CC=5 SCAR=16.1
80 526 my ($this) = @_;
81 # TODO: consider if this is the correct thing to do or if we should instead
82 # wait for the task here.
83 526 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 526 526
84 526 ▶ return unless $PID == $this->{parent};
Branch: 1 branch
BranchTrueFalseTotal
unless $Parallel::TaskExecutor::Task::PID == $this->{"parent"} 235 291 526
85 # TODO: provide a system to not wait here, but defer that to the deletion of
86 # the runner.
87 291 ▶ if ($this->running()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($this->running) 17 274 291
88 17 ▶ if ($this->{runner}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($this->{'runner'}) { } 7 10 17
89 7 trace("Deferring reaping of task $this->{task_id}");
90 # We could unweaken the entry in the tasks hash, but it’s cleaner to have
91 # only weak objects there, and non-weak objects in zombies (otherwise we
92 # would need to rely on isweak in the TaskExecutor DESTROY method).
93 7 $this->{runner}{zombies}{$this} = $this;
94 7 delete $this->{runner}{tasks}{$this};
95 # Once we are a zombie, we can be deleted only once done, so this code path
96 # will not keep creating reference to the object.
97 } else {
98 10 $this->wait();
99 }
100 }
101 291 return;
102 }
103  
104 =pod
105  
106 =head2 wait
107  
108 $task->wait();
109  
110 Blocks until the task is done. When this function returns, it is guaranteed that
111 the task is in the I<done> state (that is, that done() will return true).
112  
113 Returns a true value if the child task succeeded. If the task failed and
114 B<catch_error> was set in the parent executor when the
115 task started, then this method will return a false value.
116  
117  
118 =cut
119  
120 299 ▶sub wait { ## no critic (ProhibitBuiltinHomonyms)
Subroutine wait: called CC=5 SCAR=16.2
Pod documented
121 299 my ($this) = @_;
122 299 ▶ return if $this->{state} eq 'done';
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"state"} eq "done" 199 100 299
123 100 trace("Starting blocking waitpid($this->{pid})");
124 100 local ($ERRNO, $CHILD_ERROR) = (0, 0);
125 100 my $ret = waitpid($this->{pid}, 0);
126 100 ▶ fatal("No children with pid $this->{pid} for task $this->{task_id}") if $ret == -1;
Branch: 1 branch
BranchTrueFalseTotal
if $ret == -1 0 100 100
127 fatal(
128 "Incoherent PID returned by waitpid: actual $ret; expected $this->{pid} for task $this->{task_id}"
129 100 ▶ ) if $ret != $this->{pid};
Branch: 1 branch
BranchTrueFalseTotal
if $ret != $this->{"pid"} 0 100 100
130 100 $this->_process_done();
131 99 ▶ return $this->{error} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$this->{'error'} ? : 9 90 99
132 }
133  
134 =pod
135  
136 =head2 data
137  
138 my @data = $task->data();
139 my $data = $task->data();
140  
141 Returns the result value of a finished task (produced by the code-reference that
142 was passed to the run() call of the executor). If called in list context,
143 returns all the produced value. If called in scalar context, returns only the
144 first value. Note that the code-reference itself in the task has been called in
145 a list context by default, unless the B<scalar> option was passed to its
146 executor.
147  
148 It is an error to call this method on a task that is still running. So you must
149 be sure that the task is done before you call it (either through a call to
150 wait() or to done() for example). See also the get() method which combines a
151 call to wait() and to data().
152  
153 If the task failed and B<catch_error> was set in the parent executor when the
154 task started, then this method will die() with the child task error.
155  
156 =cut
157  
158 256 ▶sub data {
Subroutine data: called CC=4 SCAR=13.9
Pod documented
159 256 my ($this) = @_;
160 256 ▶ fatal('Trying to read the data of a still running task') unless $this->done();
Branch: 1 branch
BranchTrueFalseTotal
unless $this->done 2 254 256
161 254 ▶ die $this->{error} if defined $this->{error}; ## no critic (RequireCarping)
Branch: 1 branch
BranchTrueFalseTotal
if defined $this->{"error"} 5 249 254
162 # TODO: we should have a variant for undef wantarray that does not setup
163 # the whole pipe to get the return data.
164 # Note: wantarray here is not necessarily the same as when the task was set
165 # up, it is the responsibility of the caller to set the 'scalar' option
166 # correctly.
167 249 ▶ return wantarray ? @{$this->{data}} : $this->{data}[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 4 245 249
168 }
169  
170 =pod
171  
172 =head2 running
173  
174 print "Still running\n" if $task->running();
175  
176 Returns whether the task is still running.
177  
178 =cut
179  
180 303 ▶sub running {
Subroutine running: called CC=2 SCAR=6.9
Pod documented
181 303 my ($this) = @_;
182 303 ▶ $this->_try_wait() if $this->{state} eq 'running';
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"state"} eq "running" 22 281 303
183 303 return $this->{state} eq 'running';
184 }
185  
186 =pod
187  
188 =head2 done
189  
190 print "Done\n" if $task->done();
191  
192 Returns whether the task is done. This is guaranteed to always be the opposite
193 of done().
194  
195 =cut
196  
197 # This method is the opposite of running() because the task can only be in the
198 # state running or done once it has been returned to the caller.
199  
200 256 ▶sub done {
Subroutine done: called CC=2 SCAR=6.9
Pod documented
201 256 my ($this) = @_;
202 256 ▶ $this->_try_wait() if $this->{state} eq 'running';
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"state"} eq "running" 2 254 256
203 256 return $this->{state} eq 'done';
204 }
205  
206 =pod
207  
208 =head2 get
209  
210 my $data = $task->get();
211  
212 Waits until the task is done and returns the result of the task. See the
213 documentation of the L<wait()|/wait> and L<data()|/data> methods for more
214 details, in particular regarding scalar and list context data.
215  
216 =cut
217  
218 233 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
219 233 my ($this) = @_;
220 233 $this->wait();
221 233 return $this->data();
222 }
223  
224 152102 ▶sub _try_wait {
Subroutine _try_wait: called CC=4 SCAR=13.9
225 152102 my ($this) = @_;
226 152102 ▶ return if $this->{state} ne 'running';
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"state"} ne "running" 0 152102 152102
227 152102 trace("Starting non blocking waitpid($this->{pid})");
228 152102 local ($ERRNO, $CHILD_ERROR) = (0, 0);
229 152102 my $pid = waitpid($this->{pid}, WNOHANG);
230 152102 ▶ if ($pid > 0 || $pid < -1) { # Perl fake processes on Windows use negative PIDs.
Branch: 1 branch
BranchTrueFalseTotal
if ($pid > 0 or $pid < -1) 356 151746 152102
Condition66%2/3
$pid > 0 or $pid < -1
l!l&&r!l&&!r
3560151746
MC/DC50%1/2
$pid > 0 or $pid < -1
$pid > 0 $pid < -1
Truth table66%2/3
A or B
A= $pid > 0B= $pid < -1
ABresult
1X1
011
000
231 # TODO: do the same validation on $pid than in the wait() method.
232 356 $this->_process_done();
233 356 return 1;
234 }
235 151746 return;
236 }
237  
238 456 ▶sub _process_done {
Subroutine _process_done: called CC=9 SCAR=22.0
239 456 my ($this) = @_;
240 456 $this->{state} = 'done';
241 456 ▶ if ($this->{runner}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($this->{"runner"}) 433 23 456
242 433 ▶ $this->{runner}{current_tasks}-- unless $this->{untracked};
Branch: 1 branch
BranchTrueFalseTotal
unless $this->{"untracked"} 418 15 433
243 433 delete $this->{runner}{tasks}{$this}; # might not exist if we are a zombie, this is fine.
244 }
245 456 ▶ if ($CHILD_ERROR) {
Branch: 2 branches
BranchTrueFalseTotal
if ($Parallel::TaskExecutor::Task::CHILD_ERROR) { } 10 446 456
elsif ($this->{'channel'}) { } 446 0 446
246 10 ▶ if ($this->{catch_error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($this->{'catch_error'}) { } 9 1 10
247 9 $this->{error} = "Child command failed: ${CHILD_ERROR}";
248 } else {
249 # Ideally, we should first wait for all child processes of all runners
250 # before dying, to print the dying message last.
251 1 error(
252 "Child process (pid == $this->{pid}, task_id == $this->{task_id}) failed (${CHILD_ERROR})");
253 1 exit 2;
254 }
255 } elsif ($this->{channel}) {
256 446 local $INPUT_RECORD_SEPARATOR = undef;
257 446 my $fh = $this->{channel};
258 446 my $data = <$fh>;
259 446 ▶ close $fh or warning("Cannot close task output channel: ${ERRNO}");
Branch: 1 branch
BranchTrueFalseTotal
close $fh or warning("Cannot close task output channel: $Parallel::TaskExecutor::Task::ERRNO") 446 0 446
260 {
261 54 ▶ no strict; ## no critic (ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=0.0
262 54 ▶ no warnings; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
263 446 $this->{data} = eval $data; ## no critic (ProhibitStringyEval)
264 }
265 fatal(
266 446 ▶ "Cannot parse the output of child task $this->{task_id} (pid == $this->{pid}): ${EVAL_ERROR}")
Branch: 1 branch
BranchTrueFalseTotal
if $Parallel::TaskExecutor::Task::EVAL_ERROR 0 446 446
267 if $EVAL_ERROR;
268 }
269 455 trace("Child pid == $this->{pid} returned (task id == $this->{task_id})");
270 455 ▶ trace(" --> current tasks == $this->{runner}{current_tasks}") if $this->{runner};
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"runner"} 432 23 455
271 455 return;
272 }
273  
274 # Undocumented because there is too much risk that the behavior of the library
275 # would be broken if the user started doing weird thing with that.
276 5 ▶sub pid {
Subroutine pid: called CC=1 SCAR=0.0
Pod undocumented
277 5 my ($this) = @_;
278 5 return $this->{pid};
279 }
280  
281 =pod
282  
283 =head2 signal
284  
285 $task->signal('HUP');
286  
287 Sends the given signal to the task. Signal can be anything accepted by the
288 L<kill()|/kill SIGNAL> method, so either a signal name or a signal number. See
289 L<kill()|/kill SIGNAL> for how to get the list of supported signals.
290  
291 Note that even if the signal kills the task you should still in general wait()
292 for it at some point. Also, unless the task gracefully handles the signal, you
293 will probably need to pass the C<catch_error> option to the run() call when the
294 task is started, otherwise your whole program will be aborted.
295  
296 =cut
297  
298 3 ▶sub signal {
Subroutine signal: called CC=2 SCAR=7.0
Pod documented
299 3 my ($this, $signal) = @_;
300 3 ▶ return if $this->{state} ne 'running';
Branch: 1 branch
BranchTrueFalseTotal
if $this->{"state"} ne "running" 0 3 3
301 3 trace("Sending signal ${signal} to process $this->{pid}");
302 3 kill $signal, $this->{pid};
303 3 return;
304 }
305  
306 =pod
307  
308 =head2 kill
309  
310 $task->kill();
311  
312 This is a synonym of L<signal()>|/signal> but where the default argument is
313 C<SIGKILL>. You can still pass a different signal name if you want.
314  
315 =cut
316  
317 2 ▶sub kill { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
Subroutine kill: called CC=1 SCAR=0.0
Pod documented
318 2 my ($this, $signal) = (@_, 'KILL');
319 2 return $this->signal($signal);
320 }
321  
322 54 1;
« TaskExecutor.pm ↑ Summary