SafeExec/Queue.pm untested

filter: Statementstmt 0.0% 0 / 106 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 188 CC 24 SCAR 52.5
CC
24
Cov
0%
do_events
342.0
new
12.0
remaining_children
12.0
CRAP 189.8
1 package Proc::SafeExec::Queue;
2  
3 use 5.006;
4 use strict;
5 use warnings;
6  
7 our $VERSION = "1.5";
8  
9 =pod
10  
11 =head1 NAME
12  
13 Proc::SafeExec::Queue - Uses Proc::SafeExec to manage a group of concurrent processes.
14  
15 =head1 SYNOPSIS
16  
17 use Proc::SafeExec::Queue;
18 my $queue = Proc::SafeExec::Queue->new({
19 "soft_limit" => 4, # Default is 4.
20 "hard_limit" => 8, # Default is soft_limit * 2.
21 });
22  
23 To add a task to the queue:
24  
25 my $id = $queue->add({
26 # Options describing when to execute.
27 "exec_order" => 1, # Default is 1.
28 "callback_prefork" => \&callback_prefork, # Default is undef.
29 "callback_postfork" => \&callback_postfork, # Default is undef.
30 "callback_postwait" => \&callback_postwait, # Default is undef.
31 "callback_error" => \&callback_error, # Default is undef.
32 "exec" => {
33 # Options to new Proc::SafeExec.
34 },
35 "data" => {
36 # Space for the caller to store any ancillary information, for example, to be
37 # used in the callback functions.
38 },
39 });
40  
41 To cancel a task before it starts (okay during prefork):
42  
43 $queue->cancel($id);
44  
45 To wait on exited children and begin executing pending children:
46  
47 my $did_something = $queue->do_events();
48  
49 To get a list of children that haven't finished yet:
50  
51 my @list = $queue->remaining_children();
52  
53 =head1 DESCRIPTION
54  
55 Proc::SafeExec::Queue provides a way of managing a group of concurrent
56 processes.
57  
58 Here's a logical description of what happens. Processes are added to the queue
59 and execute when appropriate. The parent can enqueue them and forget about
60 them. Immediately before a child executes, before forking, the prerun function
61 executes. Immediately after a child is waited on, the postrun function
62 executes.
63  
64 This decides when to execute a child based on exec_order, soft_limit, and
65 hard_limit. The exec_order option describes the ideal order the children should
66 be executed in, however, it's not strictly enforced, since children may be
67 added with a lower exec_order after one with a higher exec_order began
68 execution. When a new child is added to the queue, it always begins executing
69 immediately if there are fewer than soft_limit already executing. Otherwise,
70 it begins executing only if the number of children with an exec_order lower or
71 equal to the new child is lower than soft_limit and there are fewer than
72 hard_limit children executing. The number of children will never exceed
73 hard_limit. Whenever a child exits, this checks the queue to see if any more
74 should be started. If there is a tie when deciding which child to execute next,
75 the first one added to the queue wins.
76  
77 Note that setting soft_limit to undef or greater than hard_limit is the same as
78 setting it to the same value as hard_limit, and both must be an integer greater
79 than zero. exec_order may be any numerical value, including negative and
80 floating point values (although it may be most intuitive to limit it to
81 integers greater than zero). Setting soft_limit or hard_limit to 0 means
82 infinity, but this can be dangerous because no computer can handle an infinite
83 number of processes.
84  
85 =head1 USAGE
86  
87 The parent should call $queue->do_events() whenever it receives SIGCHLD, but
88 should never call it directly from the signal handler, because signal handlers
89 may be invoked at times when it is not safe to do anything but set a variable.
90 It is safe to call $queue->do_events() when there is nothing to do. Thus,
91 alternatively to trapping SIGCHLD, the parent may simply call
92 $queue->do_events() whenever it is convenient, such as at the beginning of an
93 event loop. If you choose to do this, consider the loop:
94  
95 1 while $queue->do_events();
96  
97 This is not the default because it starve the parent of time to do other work.
98  
99 $queue->do_events() first waits on any children that exited and calls the
100 associated callback_postwait functions, then for each child scheduled for
101 execution, it calls the associated callback_prefork function, executes it, and
102 calls the associated callback_postfork function. If there is an error executing
103 a child, it calls callback_error; callback_postfork and callback_postwait are
104 never called. callback_prefork, callback_postfork, and callback_postwait may be
105 undef to indicate a null-op. If callback_error is set to undef and an error
106 occurs, a warning is issued via warn().
107  
108 $queue->add() adds a child to the queue and, if appropriate, begins executing
109 it. It returns a unique ID representing the child.
110  
111 The callback functions always receive the original options hash that was passed
112 to $queue->add(), with some additional elements. The callback functions can
113 inspect this hash to find out some things about the child, however this hash is
114 not to be meddled with, except as documented here. If you need to associate
115 your own information with the child, use the "data" subhash, which is entirely
116 reserved for the caller's use and may be modified at any time.
117  
118 If the child began execution, the element "Proc::SafeExec" is set to the
119 Proc::SafeExec object. (This is always set in callback_postfork and
120 callback_postwait, never in callback_prefork, and sometimes in callback_error.)
121 The query methods of Proc::SafeExec may be called, specifically child_pid,
122 stdin, stdout, stderr, exit_status. The caller may B<not> call the wait method
123 because it affects the execution state. If an error occurred, the element
124 "error" is set to $@ for the duration of the callback_error function. The "id"
125 element is always set to the unique ID assigned to this child. The
126 callback_prefork function may modify the exec hash.
127  
128 The method $queue->cancel() removes a child from the queue, but only if it
129 hasn't started yet. This may be called during callback_prefork, but no later.
130  
131 The method $queue->remaining_children() returns the hashes of the children
132 remaining in the queue (including those that are running). (These are the same
133 hashes that are passed to the callback functions.) They're listed in the order
134 they would be started if none were running yet. The ones that are running might
135 not be the first ones in the list if the exec_order decreased in the sequence
136 that children were added.
137  
138 When used as documented, this module never has an error to report directly to
139 the caller; all errors are reported through callback_error functions. If it
140 does die, there's a good chance the bug or misuse will leave things in an
141 inconsistent state that can't be recovered from automatically. This may be
142 worth improving.
143  
144 XXX: What to do with running children when the queue is destroyed?
145  
146  
147 =head1 CAVEATS
148  
149  
150 =head1 EXAMPLES
151  
152  
153 =head1 INSTALLATION
154  
155  
156 =head1 VERSION AND HISTORY
157  
158 See Proc::SafeExec.
159  
160 =head1 SEE ALSO
161  
162 See also Proc::SafeExec, the package containing this.
163  
164 =head1 AUTHOR
165  
166 Leif Pedersen, E<lt>bilbo@hobbiton.orgE<gt>
167  
168 =head1 COPYRIGHT AND LICENSE
169  
170 This may be distributed under the terms below (BSD'ish) or under the GPL.
171
172 Copyright (c) 2007
173 All Rights Reserved
174 Meridian Environmental Technology, Inc.
175 4324 University Avenue, Grand Forks, ND 58203
176 http://meridian-enviro.com
177
178 Redistribution and use in source and binary forms, with or without
179 modification, are permitted provided that the following conditions are
180 met:
181
182 1. Redistributions of source code must retain the above copyright
183 notice, this list of conditions and the following disclaimer.
184
185 2. Redistributions in binary form must reproduce the above copyright
186 notice, this list of conditions and the following disclaimer in the
187 documentation and/or other materials provided with the
188 distribution.
189
190 THIS SOFTWARE IS PROVIDED BY AUTHORS AND CONTRIBUTORS "AS IS" AND ANY
191 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
192 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
193 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE
194 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
195 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
196 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
197 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
198 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
199 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
200 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
201  
202 =cut
203  
204 use Proc::SafeExec;
205  
206 sub new {
207 my ($package, $options) = @_;
208  
209 my $class_name = (ref($package) or $package);
210 my $self = {};
211 bless $self, $class_name;
212  
213 # Usage checks; set defaults.
214 if(defined $options->{"soft_limit"}) {
215 $self->{"soft_limit"} = $options->{"soft_limit"};
216 } else {
217 $self->{"soft_limit"} = 4;
218 }
219 if(defined $options->{"hard_limit"}) {
220 $self->{"hard_limit"} = $options->{"hard_limit"};
221 } else {
222 $self->{"hard_limit"} = $self->{"soft_limit"} * 2;
223 }
224  
225 $self->{"queue"} = {};
226 $self->{"next_unique_id"} = 1;
227 $self->{"num_executing"} = 0;
228  
229 return $self;
230 }
231  
232 sub do_events {
233 my ($self) = @_;
234 my $did_something;
235  
236 # Make it okay to call $self->do_events() from within a callback handler. A
237 # common case of this is when the callback_postexit function needs to call
238 # $self->add().
239 return () if $self->{"do_events_executing"};
240 local $self->{"do_events_executing"} = 1;
241  
242 # First, wait for exited children so we know how many more to start. For each,
243 # call callback_postwait.
244 foreach my $child (values %{$self->{"queue"}}) {
245 next unless $child->{"Proc::SafeExec"}; # Not yet started.
246 next unless $child->{"Proc::SafeExec"}->wait({"nonblock" => 1}); # Didn't finish yet.
247 $did_something = 1;
248  
249 eval {
250 $child->{"callback_postwait"}->($child) if defined $child->{"callback_postwait"};
251 };
252 if($@) {
253 $child->{"error"} = $@;
254 if(defined $child->{"callback_error"}) {
255 $child->{"callback_error"}->($child);
256 } else {
257 warn "Child ID $child->{'id'} had an error: $child->{'error'}";
258 }
259 $child->{"error"} = undef;
260 }
261 delete $self->{"queue"}{$child->{"id"}};
262 $self->{"num_executing"} -= 1;
263 }
264  
265 my $soft_num_executing = 0; # Counting the current iteration because it increments at the top of the loop. Sorry.
266 foreach my $child ($self->remaining_children()) {
267 $soft_num_executing++;
268 next if $child->{"Proc::SafeExec"}; # Already running
269  
270 # Honor cancel requests before and immediately after callback_prefork.
271 if($child->{"cancel"}) {
272 delete $self->{"queue"}{$child->{"id"}};
273 $soft_num_executing--;
274 next;
275 }
276  
277 # Not yet executed. Should we start it?
278 next if $self->{"hard_limit"} and $self->{"num_executing"} >= $self->{"hard_limit"}; # Too many running.
279 next if $self->{"soft_limit"} and $soft_num_executing > $self->{"soft_limit"}; # Too many running with lower exec_order.
280 $did_something = 1;
281  
282 # Call callback_prefork, then Proc::SafeExec, then callback_postfork. On error,
283 # call callback_error.
284 eval {
285 $child->{"callback_prefork"}->($child) if defined $child->{"callback_prefork"};
286 };
287 if($@) {
288 $child->{"error"} = $@;
289 if(defined $child->{"callback_error"}) {
290 $child->{"callback_error"}->($child);
291 } else {
292 warn "Child ID $child->{'id'}} had an error: $child->{'error'}";
293 }
294 $child->{"error"} = undef;
295 }
296  
297 # Honor cancel requests before and immediately after callback_prefork.
298 if($child->{"cancel"}) {
299 delete $self->{"queue"}{$child->{"id"}};
300 $soft_num_executing--;
301 next;
302 }
303  
304 eval {
305 $child->{"Proc::SafeExec"} = new Proc::SafeExec($child->{"exec"});
306 $self->{"num_executing"} += 1;
307 $child->{"callback_postfork"}->($child) if defined $child->{"callback_postfork"};
308 };
309 if($@) {
310 $child->{"error"} = $@;
311 if(defined $child->{"callback_error"}) {
312 $child->{"callback_error"}->($child);
313 } else {
314 warn "Child ID $child->{'id'}} had an error: $child->{'error'}";
315 }
316 $child->{"error"} = undef;
317 }
318 }
319  
320 return $did_something;
321 }
322  
323 sub add {
324 my ($self, $options) = @_;
325  
326 $options->{"id"} = $self->{"next_unique_id"}++;
327 $options->{"exec_order"} = 1 unless defined $options->{"exec_order"};
328 $options->{"Proc::SafeExec"} = undef; # Safety.
329 $options->{"error"} = undef; # Safety.
330  
331 $self->{"queue"}{$options->{"id"}} = $options;
332  
333 $self->do_events();
334  
335 return $options->{"id"};
336 }
337  
338 sub cancel {
339 my ($self, $id) = @_;
340 $self->{"queue"}{$id}{"cancel"} = 1;
341 return ();
342 }
343  
344 sub remaining_children {
345 my ($self) = @_;
346  
347 unless(wantarray) {
348 return 1 if %{$self->{"queue"}};
349 return undef;
350 }
351  
352 # Sort first by exec_order, then by the order they were added.
353 return sort {
354 $a->{"exec_order"} <=> $b->{"exec_order"} or
355 $a->{"id"} <=> $b->{"id"}
356 } values %{$self->{"queue"}};
357 }
358  
359 sub DESTROY {
360 my ($self) = @_;
361  
362 # XXX: Not sure what to do here.
363 my @children = $self->remaining_children();
364 @children = map {$_->{"id"}} @children;
365 warn("The following child IDs haven't finished yet, and may not have executed: @children") if @children;
366 }
367  
368 # XXX: Add a test function.
369  
370 1