blib/lib/HPCI/Group.pm untested

filter: Statementstmt 0.0% 0 / 367 Branchbran 0.0% 0 / 76 Conditioncond 0.0% 0 / 36 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 504 CC 5 SCAR 21.6
CC
5
Cov
0%
_build_stage_list
30.0
_match_stages
2.0
BEGIN
2.0
CRAP 8.7
1 package HPCI::Group;
2  
3 ### INCLUDES ##################################################################
4  
5 # safe Perl
6 use warnings;
7 use strict;
8 use Carp;
9 use Data::Dumper;
10 use File::ShareDir;
11 use File::Path qw(make_path);
12 use File::Spec;
13 use Time::HiRes qw(usleep gettimeofday);
14 use Try::Tiny;
15 use DateTime;
16 use Module::Load;
17 use HPCI::File;
18  
19 use MooseX::Role::Parameterized;
20 use MooseX::Types::Path::Class qw(Dir File);
21 use Moose::Util::TypeConstraints;
22  
23 ## no critic BoutrosLab::HangingComma
24 ## no critic BoutrosLab::IndentationCheck
25  
26 parameter theDriver => (
27 isa => 'Str',
28 required => 1,
29 );
30  
31 role {
32 my $p = shift;
33 my $theDriver = $p->theDriver;
34 my $StageClass = "${theDriver}::Stage";
35  
36 has '_stage_class' => (
37 is => 'ro',
38 isa => 'Str',
39 init_arg => undef,
40 default => $StageClass,
41 );
42  
43 sub name; # tell Logger we provide a name attribute
44 sub group_dir; # tell Logger we provide a group_dir attribute
45 sub _unique_name; # tell Logger we provide a _unique_name attribute
46  
47 # do nothing, but let roles write before/after/around wrappers
48 method BUILD => sub {
49 };
50  
51 with qw(
52 HPCI::Logger
53 HPCI::Env
54 );
55 # Future considerations for adding:
56 #
57 # HPCI::HTML - generate a report about an execution
58 # HPCI::Template - templates for reports
59 # - was formerly used for script
60 # - now generated dynamically
61 # - allowing for easier control by plugins
62  
63 method wait_for_completed_stage => sub {
64 my $self = shift;
65 my $finished_job = $self->next_finished_job;
66 my $name = $finished_job->stage->name;
67 my $stage = $self->_stages->{$name};
68 if ($stage->_has_command) {
69 $stage->_analyse_completion_state($finished_job);
70 }
71 else {
72 $stage->_set_state( $finished_job->status ? 'fail' : 'pass' );
73 }
74 # if ($stage->is_pass && ! $stage->_files_acceptable_for_completed_stage($finished_job)) {
75 # $self->fail_stage( $stage )
76 # }
77 if ($stage->is_fail
78 && $stage->_chosen_retries < $stage->choose_retries
79 && ($finished_job->_analysis_chose_retry
80 || ( $stage->_has_should_choose_retry
81 && $stage->should_choose_retry->(
82 $finished_job->stats,
83 $finished_job->_stderr
84 )
85 )
86 )
87 ) {
88 $stage->_set_state('retry');
89 $stage->_chosen_retries($stage->_chosen_retries+1);
90 $self->info( "Using user chosen retry: ",
91 $stage->_chosen_retries,
92 " of ",
93 $stage->choose_retries,
94 );
95 }
96 if ($stage->is_fail && $stage->_forced_retries < $stage->force_retries) {
97 $stage->_set_state('retry');
98 $stage->_forced_retries($stage->_forced_retries+1);
99 $self->info( "Using forced retry: ",
100 $stage->_forced_retries,
101 " of ",
102 $stage->force_retries,
103 );
104 }
105 $stage->_files_actions_after_success if $stage->is_pass;
106  
107 my $state = $stage->state;
108 $finished_job->stats->{final_job_state} = $state;
109 my $index = $finished_job->index;
110 $self->info("stage($name) run($index) completion state: $state");
111 return $stage;
112 };
113  
114 =head1 NAME
115  
116 HPCI::Group
117  
118 =head1 SYNOPSIS
119  
120 Role for building a cluster-specific driver for a group
121 of stages. This should only be used internally to the
122 C<HPCI> module - code that uses this driver will
123 not load this module (or the driver module) explicitly.
124  
125 It describes the user interface for a generic group, hiding
126 (as much as possible) the specifics of the actual cluster that
127 is being used. The driver module that consumes this role will
128 arrange to translate the generic interface into the particular
129 interface conventions of the specific cluster that it accesses.
130  
131 An (internally defined) cluster-specific group object is
132 defined with:
133  
134 package HPCD::$cluster::Group;
135 use Moose;
136  
137 ### required method definitions
138  
139 with 'HPCI::Group' => { StageClass => 'HPCD::$cluster::Stage' },
140 # any other roles required ...
141 ;
142  
143 ### cluster-specific method definition if any ...
144  
145 =head1 DESCRIPTION
146  
147 This role provides the generic interface for a group object
148 which can configure and run a collection of stages (jobs)
149 on machines in a cluster. It is written to be independent
150 of the specifics of any particular cluster interface. The
151 cluster-specific module that consumes this role is not accessed
152 directly by the user program - they are provided with a group
153 driver object of the appropriate cluster-specific type using
154 the "class method" HPCI->group (with an appropriate
155 C<cluster> argument) to request an appropriate to build it.
156  
157 =head1 ATTRIBUTES
158  
159 =head2 cluster
160  
161 The type of cluster that will be used to execute the group of stages.
162 This value is passed on by the HPCI->group method when it
163 creates a new group. Since it also uses that value to select the type
164 of group object that is created, it is somewhat redundant.
165  
166 =cut
167  
168 has 'cluster' => (
169 is => 'ro',
170 isa => 'Str',
171 required => 1,
172 );
173  
174 =head2 name (optional)
175  
176 The name of this group of stages. Defaults to 'default_group_name'.
177  
178 =cut
179  
180 has 'name' => (
181 is => 'ro',
182 isa => 'Str',
183 lazy => 1,
184 default => 'default_group_name',
185 required => 1,
186 );
187  
188 =head2 storage_classes (optional)
189  
190 HPCI has two conceptual storage types that it expects to be available.
191  
192 Long-term storage is storage that is reliably preserved over time.
193 The data in long-term storage is accessible to all nodes on the
194 cluster, but possibly only accessible through special commands.
195  
196 Working storage is storage that is directly-accessible to a node
197 through normal file system access methods. It can be a private disk
198 that is not accessible to other nodes, or it can be a shared file
199 system that is available to other nodes.
200  
201 It is fairly common, and most convenient, if the working storage also
202 qualifies as long-term storage. That is the default expectation if
203 HPCI is not told otherwise.
204  
205 However, some types of cluster can have their nodes rebuilt at intervals,
206 losing the data on their local disks. Some types of cluster have a
207 shared file system that is not strongly persistent, but which can be
208 rebuilt at intervals. Some types of cluster have shared file systems
209 that have size limitations that mean that some or all of the data sets
210 for stage processes cannot be stored there.
211  
212 In such cases, some or all of the files must have a long-term storage
213 location that is different from the more convenient working storage
214 location that will be used when stages are running. Depending upon the
215 environment, the long-term storage will use something like:
216  
217 =over 4
218  
219 =item network accessed storage
220  
221 A storage facility that allows file to be uploeded and downloaded through
222 a netowrk connection (from any node in the cluster).
223  
224 =item parent managed storage
225  
226 The job controlling program may have long-term storage of it own that
227 is not accessible to other nodes in the cluster. If there is a large
228 enough shared file system (that for some reason cannot be used as long-term
229 storage) the parent HPCI program can copy files between that storage and
230 the shared storage as needed to make the files available and to preserve
231 the results.
232  
233 =item bundled storage
234  
235 In a B<cloud> layout there is often no file system shared amongst all of
236 the nodes and the parent process. In this type of cluster, a submitted
237 stage will include some sort of bundle containing a collection of data
238 and control files (possibly even the entire operating system) to be used
239 by the stage, and a similar sort of bundle is recovered to provide the
240 results of running a stage. (This could be, for example, a C<docker>
241 image.)
242  
243 =back
244  
245 The attribute C<storage_classes> defines the available storage classes
246 that can be used for stage files.
247  
248 In most cases, all files for all stages will be of the same storage
249 class, but some cluster configurations will have multiple storage
250 choices and can have, for some stages, the need to use more than one of
251 the storage classes for different files within the same job.
252  
253 To cater to both of these, the C<storage_classes> attribute can either be
254 a single arrayref which will be used for all files, or it can be a hash of
255 named arrayrefs, with the name being used to select the class for each
256 individual file. A file (described in the C<files> attribute of the C<stage>
257 class) can either be a scalar string specifying the pathname of the working
258 storage location that will be used, or it can be a one element hashref, with
259 the key selecting the storage class and the value providing the working
260 storage pathname. If the hash of named arrayrefs is used, one of the
261 elements of the hash should have the key C<default> - that will be used for
262 files which do not provide an explicit storage class key.
263  
264 The default value for this attribute is:
265  
266 [ 'HPCI::File ]
267  
268 The HPCI::File class defines the usage for the common case in which there is
269 no need for a long-term storage area that is different from the working
270 storage area.
271  
272 Classes that provide to separate long-term storage area will usually require
273 additional arguments, for specifying access control information (such as url,
274 username, password) and how to map the working storage pathname into the
275 corresponding location in the long-term storage.
276  
277 See the documentation for HPCI::File for details on writing new classes.
278  
279 =head2 storage_class
280  
281 The default storage class attribute for files that do not
282 have an explicit class given and are not covered by an element in
283 storage_classes. This is a (sub-)class of HPCI::File, the default
284 is HPCI::File.
285  
286 =cut
287  
288 has 'storage_class' => (
289 is => 'ro',
290 isa => 'HPCIFileGen',
291 lazy => 1,
292 default => sub { HPCI::File::Classes::generator('HPCI::File') },
293 );
294  
295 =head2 file_params
296  
297 A hash containing the param list for files that need params.
298 Providing them here means that they do not have to be written
299 out in full every time the file is used through the program.
300  
301 You can use the method add_file_params to augment the hash, so
302 the file info can be provided in the sectio of code that creates
303 the stage(s) that use that file, rather than having to list them
304 all in one place.
305  
306 Defaults to an empty hash.
307  
308 =cut
309  
310 has 'file_params' => (
311 is => 'bare',
312 isa => 'HashRef',
313 trigger => sub {
314 my $self = shift;
315 $self->add_file_params( @_ );
316 },
317 );
318  
319 has '_file_info' => (
320 is => 'ro',
321 isa => 'HashRef',
322 lazy => 1,
323 default => sub { { } },
324 );
325  
326  
327 =head2 _unique_name (internal)
328  
329 The name of this group of stages. Used as the default value for
330 the B<group_dir> attribute.
331  
332 =cut
333  
334 has '_unique_name' => (
335 is => 'ro',
336 isa => 'Str',
337 lazy => 1,
338 init_arg => undef,
339 default => sub {
340 my $self = shift;
341 my $name = $self->name;
342 my $tstamp = DateTime->now->strftime("%Y%m%d-%H%M%S");
343 return "$name-$tstamp";
344 },
345 );
346  
347 =head2 base_dir (optional)
348  
349 The directory that will contain all generated output (unless
350 that output is specifically directed to some other location).
351 The default is the current directory.
352  
353 =cut
354  
355 has 'base_dir' => (
356 is => 'ro',
357 isa => 'Path::Class::Dir',
358 coerce => 1,
359 default => sub {
360 my $self = shift;
361 Dir->new( '.' );
362 },
363 );
364  
365 =head2 group_dir (optional)
366  
367 The directory which will contain all output pertaining to the entire
368 group. By default, this is a new directory under B<base_dir> which
369 is given a name combining the name of the group and the timestamp
370 when the group was created (e.g. EXAMPLEGROUP-YYMMDD-HHMMSS).
371  
372 =cut
373  
374 has 'group_dir' => (
375 is => 'ro',
376 isa => 'Path::Class::Dir',
377 lazy => 1,
378 coerce => 1,
379 default => sub {
380 my $self = shift;
381 my $subdir = $self->_unique_name;
382 my $target = $self->base_dir->subdir($subdir);
383 HPCI::_trigger_mkdir( $self, $target );
384 return $target;
385 },
386 trigger => \&HPCI::_trigger_mkdir,
387 );
388  
389 =head2 connect (optional)
390  
391 This can contain an URL to be used by the driver for types of cluster
392 where it is necessary to connect to the cluster in some way. It can
393 be omitted for local clusters that are directly accessible.
394  
395 =cut
396  
397 has 'connect' => (
398 is => 'ro',
399 isa => 'Str',
400 );
401  
402 =head2 login, password (optional)
403  
404 This can contain an identifier to be used by the driver for types of
405 cluster which require authorization.
406  
407 =cut
408  
409 has [ qw(login password) ] => (
410 is => 'ro',
411 isa => 'Str',
412 );
413  
414 =head2 max_concurrent (optional)
415  
416 The maximum number of stages to be running concurrently. If 0
417 (which is the default), then there is no limit applied directly by
418 HPCI (although the underlying cluster-specific driver might apply
419 limits of its own).
420  
421 =cut
422  
423 has 'max_concurrent' => (
424 is => 'ro',
425 isa => 'Int',
426 default => 0,
427 );
428  
429 =head2 stage_defaults
430  
431 This attribute can be given a hash reference containing values that
432 will be passed to every stage created.
433  
434 =cut
435  
436 has 'stage_defaults' => (
437 is => 'ro',
438 isa => 'HashRef',
439 lazy => 1,
440 default => sub { {} },
441 );
442  
443 =head2 status (provided internally)
444  
445 After the execute method has been called, this attribute contains the
446 return result from the execution. This is a hash (indexed by stage
447 name). The value for each stage is an array of the return status.
448 (Usually, this array has only one element, but there will be more
449 if the stage was retried. The final element of the array is almost
450 always the one that you wish to look at.) The return status is a
451 hash - it will always contain an element key 'exit_status' giving
452 the exit status of the stage. Additional entries will be found in
453 the hash for cluster-specific return reults. Thus, to check the
454 exit status of a particular stage you would code either:
455  
456 $result = $group->execute;
457 if ($result->{SOMESTAGENAME}[-1]{exit_status}) {
458 die "SOMESTAGENAME failed!";
459 }
460  
461 or:
462  
463 $group->execute;
464 # ...
465 if ($group->status->{SOMESTAGENAME}[-1]{exit_status}) {
466 die "SOMESTAGENAME failed!";
467 }
468  
469 =cut
470  
471 has 'status' => (
472 is => 'ro',
473 isa => 'HashRef',
474 lazy => 1,
475 init_arg => undef,
476 default => sub { {} },
477 writer => '_set_status',
478 );
479  
480 =head2 file_system_delay
481  
482 Shared files systems can have a delay period during which an action
483 on the file system is not yet visible to another node sharing that
484 file system. This is common for NFS shared file systems, for
485 example.
486  
487 The file_system_delay attribute can be given a non-zero number of
488 seconds to indicate the amount of time to wait to ensure that
489 actions taken on another node are visible.
490  
491 This is used for internal actions such as validating that required
492 stage output files have been created.
493  
494 =cut
495  
496 has 'file_system_delay' => (
497 is => 'ro',
498 isa => 'Int',
499 lazy => 1,
500 default => 0,
501 );
502  
503 #### Internal attributes
504  
505 has '_stages' => (
506 is => 'ro',
507 isa => "HashRef[$StageClass]",
508 lazy => 1,
509 init_arg => undef,
510 default => sub { {} },
511 );
512  
513 has [qw(_deps _pre_reqs)] => (
514 is => 'ro',
515 isa => 'HashRef[Str]',
516 lazy => 1,
517 init_arg => undef,
518 default => sub { {} },
519 );
520  
521 has [qw(_stage_cnt _running_cnt _finished_cnt)] => (
522 is => 'rw',
523 isa => 'Int',
524 default => 0,
525 );
526  
527 has [qw(_ready _blocked _submitted _completed _failed)] => (
528 is => 'ro',
529 isa => 'HashRef',
530 init_arg => undef,
531 default => sub { {} },
532 );
533  
534 has [qw(_sub_secs _sub_microsecs)] => (
535 is => 'rw',
536 isa => 'Int',
537 init_arg => undef,
538 default => 0,
539 );
540  
541 has '_execution_started' => (
542 is => 'rw',
543 isa => 'Int',
544 init_arg => undef,
545 default => 0,
546 );
547  
548 =head1 METHODS
549  
550 =head2 $group->stage( name=>'stagename', ... )
551  
552 Creates a stage and adds it to the group. See HPCI::Stage
553 for the generic parameters you may provide for a stage; and see
554 HPCD::$cluster::Stage for the cluster-specific parameters for the
555 actual type of cluster you are using.
556  
557 Note: this is the only way to add a stage object to the group.
558 In particular, you cannot create a stage object separately and add
559 it to the group - this is done to ensure that the created stage
560 object is consistant with the actual group object and that you don't
561 have to change code in multiple places if you switch to using a
562 different cluster type for the group. (If you want to mix stages
563 for multiple cluster types within your program, you should either
564 create two groups that execute independently, or else create a
565 stage that itself creates a group and manages the stages for the second
566 type of cluster.)
567  
568 The name parameter is required and must be unique - two stages
569 within the same group may not have the same name.
570  
571 The method returns the stage object that was created, although
572 most code will not need it directly. (Whenever you need to refer
573 to a stage to add dependencies, you can use its name instead of a
574 reference to the object.)
575  
576 =cut
577  
578 requires qw(submit_stage);
579  
580 method stage => sub {
581 my $self = shift;
582 $self->_croak("Cannot define new stages after execution has started!")
583 if $self->_execution_started;
584 my $use_args = { };
585 # $self->debug( "Calling stage. Provided args: " . Dumper( \@_ ));
586 HPCI::_merge_hash( $use_args, $self->stage_defaults );
587 my $args = { @_ };
588 my $cluster = $self->cluster;
589 for my $arg_set ($use_args, $args) {
590 if (my $spec_args = delete $arg_set->{cluster_specific}) {
591 HPCI::_merge_hash( $use_args, $spec_args->{$cluster} // {} );
592 }
593 }
594 HPCI::_merge_hash( $use_args, $args );
595  
596 $self->debug( "Calling stage. Composed args: " . Dumper( \@_ ));
597 my $stage = $self->_stage_class->new(
598 %$use_args,
599 cluster => $self->cluster,
600 group => $self,
601 );
602 my $name = $stage->name;
603 my $stages = $self->_stages;
604 $self->_croak("Duplicate stage name ($name)") if exists $stages->{$name};
605 $self->info( "Created stage($name)" );
606 $stages->{$name} = $stage;
607 $self->_stage_cnt( $self->_stage_cnt + 1 );
608 $self->_ready->{$name} = 1;
609 return $stage;
610 };
611  
612 =head2 $group->add_deps
613  
614 $group->add_deps(
615 dep => 'a_dep', ## one of these two
616 deps => ['dep1', 'dep2', ...],
617 pre_req => 'a_pre_req', ## and one of these two
618 pre_reqs => ['pre_req1', 'pre_req2', ...],
619 );
620  
621 # A scalar value, either provided alone or in a list, can be
622 # any of:
623 # - an existing stage object
624 # - a string - the exact value of some existing stage's name
625 # - a regexp - all of the stages whose name matches the regexp
626  
627 The add_deps method marks the pre_req (or all of the pre_reqs)
628 as being pre-requisites to the dep (or all of the deps). When the
629 group is executed, stages may be run in parallel, but a dependent
630 stage will not be permitted to start executing until all of its
631 prerequisites stages have completed successfully.
632  
633 It is permitted to list the same dependency multiple times. This can
634 be convenient in that you do not need to be careful about providing
635 non-overlapping groups when you specify sets of prerequisites.
636  
637 So, you could write:
638  
639 $group->add_deps( pre_req=>'stage1', deps=>[qw(stage2 stage3)] );
640 $group->add_deps( pre_reqs=>[qw(stage1 stage2)], dep=>'stage3' );
641  
642 instead of:
643  
644 $group->add_deps( pre_req=>'stage1', deps=>qr(^stage[23]$) );
645 $group->add_deps( pre_req=>'stage2', dep=>'stage3' );
646  
647 or:
648  
649 $group->add_deps( pre_req=>'stage1', dep=>'stage2' );
650 $group->add_deps( pre_req=>'stage2', dep=>'stage3' );
651  
652  
653 All three forms will provide the same ordering, the last is
654 clearer for this simple sequence, but when there are many
655 stages that have it may be easier to specify collections of
656 dependencies at once.
657  
658 However, you B<must> be careful to avoid dependency loops.
659 That would be a chain of dependencies stages that include the
660 same stage multiple times (stage1 -> stage2 -> stage1). Since a
661 dependency indicates that the prerequisite stage must be finished
662 executing before the dependent stage can start executing, this loop
663 would mean that the stage1 cannot start until stage2 has completed,
664 but also that stage2 cannot start until stage1 has completed. So,
665 neither one can ever start and they will both never complete.
666  
667 Such a loop will eventually be detected, when the group has reached
668 a point where there are no stages running, and no stages can be
669 started - but there could have been a lot of time wasted executing
670 stages that were not part of the loop before this is noticed and
671 the run aborted.
672  
673 Each stage argument passed can be either a reference to the stage
674 object or the name of the stage, or a regexp that select all of the
675 stages whose name matches the regexp. (If no stage name matches a
676 regexp, then no stages are selected. This allows using a regexp to
677 match against an optional stage without having to check whether that
678 optional stage was actually used in this run. The downside is that
679 a mistyped regexp will give no complaint when it matches nothing,
680 but it is certainly not possibly to give a complaint if a mistyped
681 regexp matches more stages than the user intended so checking the
682 regexp carefully is necessary in any case.)
683  
684 =cut
685  
686 method add_deps => sub {
687 my $self = shift;
688 my %defargs = (
689 dep => undef,
690 deps => [],
691 pre_req => undef,
692 pre_reqs => [],
693 );
694 my %args = ( %defargs, scalar(@_) == 1 ? %{ $_[0] } : @_ );
695 my $badargs = join ' ', grep { ! exists $defargs{$_} } keys %args;
696 $self->_croak( "Unknown arg($badargs) provided to add_deps" ) if $badargs;
697 # for my $arg ( qw(dep pre_req) ) {
698 # my $args = $arg.'s';
699 # $self->_croak( "Arg ($args) must be an array ref" )
700 # unless ref($args{$args}) eq 'ARRAY';
701 # $self->_croak( "Arg ($arg) may not be an array ref" )
702 # if ref($args{$arg}) eq 'ARRAY';
703 # }
704 my @deps = $self->_build_stage_list($args{dep}, $args{deps});
705 my @pre_reqs = $self->_build_stage_list($args{pre_req}, $args{pre_reqs});
706 for my $dep (@deps) {
707 for my $pre_req (@pre_reqs) {
708 $self->_add_dep( $pre_req, $dep );
709 }
710 }
711 };
712  
713 sub _build_stage_list {
714 my $self = shift;
715 my $stages = $self->_stages;
716 return
717 map { $self->_croak( "Unknown stage name ($_) passed to add_deps" )
718 unless exists $stages->{$_};
719 $_
720 }
721 grep { defined }
722 map { ref($_) ? $_->name : $_ }
723 map { ref($_) eq 'Regexp' ? ($self->_match_stages( $_ )) : ($_) }
724 map { ref($_) eq 'ARRAY' ? @{$_} : ($_) }
725 @_
726 }
727  
728 sub _match_stages {
729 my $self = shift;
730 my $pat = shift;
731 return grep { m/$pat/ } keys %{ $self->_stages };
732 }
733  
734 method _add_dep => sub {
735 # little cost/no damage if called again with same dep and pre_req
736 my ( $self, $pre_req, $dep ) = @_;
737 return if $self->_deps->{$pre_req}{$dep};
738 $self->_deps->{$pre_req}{$dep} = 1;
739 $self->_pre_reqs->{$dep}{$pre_req} = 1;
740 $self->_blocked->{$dep} = 1;
741 delete $self->_ready->{$dep};
742 };
743  
744 =head2 $group->add_file_params
745  
746 Augment the file_params list with additioal files.
747 Provide either a hashref or a list of value pairs,
748 in either case, the pairs are filename as the key,
749 and params as the value.
750  
751 =cut
752  
753 method add_file_params => sub {
754 my $self = shift;
755 my $fi = $self->_file_info;
756 my $args = $_[0];
757 $args = { @_ } unless ref $args eq 'HASH';
758 while ( my ($k,$v) = each %$args ) {
759 $self->_croak( "file params value for $k must be a hash ref" )
760 unless (ref($v) eq 'HASH');
761 $k = File::Spec->rel2abs($k);
762 $fi->{$k}{params} = $v;
763 }
764 };
765  
766 =head2 $group->execute
767  
768 Execute the stages in the group. Does not return until all stages
769 are complete (or have been skipped because of a failure of some
770 other stage or the attempt is aborted).
771  
772 =cut
773  
774 method execute => sub {
775 my $self = shift;
776 my $catcher = sub {
777 my $sig = shift;
778 $self->warn( "Killed with signal SIG$sig" );
779 $self->kill_stages;
780 };
781 local $SIG{HUP} = $catcher;
782 local $SIG{USR1} = $catcher;
783 local $SIG{USR2} = $catcher;
784 $self->_execution_started(1);
785 local $SIG{CHLD} = $SIG{CHLD};
786 $self->child_catcher;
787 my $cnt = $self->_stage_cnt;
788 my $s = $cnt == 1 ? '' : 's';
789 $self->info( "Starting execution with $cnt stage$s defined.");
790 while ($self->_finished_cnt < $self->_stage_cnt) {
791 $self->_submit_ready || next;
792 unless (keys %{ $self->_submitted }) {
793 my $blocked = join( ', ', keys %{ $self->_blocked } );
794 $self->_discard_list( "Deadlock" );
795 $self->_croak("Deadlock - cannot submit any more jobs, remaining jobs ($blocked) are blocked, there must be a dependency loop.")
796 }
797 $self->_await_one_job;
798 }
799 # $self->info("All done.\n");
800 my $ret_stat = {};
801 while (my ($name, $stage) = each %{ $self->_stages }) {
802 $ret_stat->{$name} = $stage->get_run_stats;
803 }
804 # $self->info( "All done! Stage status:", Dumper($ret_stat) );
805 $self->info( "All done! Stage status:" );
806 for my $jobname (sort keys %$ret_stat) {
807 my $jobs = $ret_stat->{$jobname};
808 for my $jobnum (0..$#$jobs) {
809 my $job = $jobs->[$jobnum];
810 my $jobnumdesc =
811 $jobnum != $#$jobs ? "Retried run $jobnum"
812 : $jobnum ? "Final run after $jobnum retries"
813 : "Only run - no retries";
814 for my $key (sort keys %$job) {
815 my $val = $job->{$key};
816 if (defined $jobname) {
817 $self->info( " $jobname" );
818 undef $jobname;
819 }
820 if (defined $jobnumdesc) {
821 $self->info( " $jobnumdesc" );
822 undef $jobnumdesc;
823 }
824 $self->info( sprintf " %-20s => %s", $key, $val );
825 }
826 }
827 }
828 $self->_set_status($ret_stat);
829 $self->systemlogger->($self,$ret_stat)
830 if $self->can('systemlogger') && $self->_has_systemlogger;
831 return $ret_stat;
832 };
833  
834 # sub wait_for_all_jobs {
835 # # TODO: Never called, so the html report is never written!
836 # # Merge this code into execute when it is ready to work
837 # my $self = shift;
838 #
839 # # Already done differently in execute
840 # my $runs = [];
841 # while ((scalar (keys %{$self->_runs})) > 0) {
842 # push($runs, $self->next_finished_job);
843 # }
844 #
845 # # modify for the different layout of run status info in execute
846 # if ($self->generate_html_report) {
847 # $self->info("Building html report\n");
848 # $self->render_template_to_file(
849 # template_name => 'report.html.template',
850 # output_file_path => $self->html_report_path,
851 # rendering_variables => {
852 # jobs => $runs,
853 # report_root_url => $self->html_report_url,
854 # }
855 # );
856 # }
857 # else {
858 # $self->info("No html report to build\n");
859 # }
860 #
861 # # execute already returns its different structure
862 # return $runs;
863 # }
864  
865  
866 ### Internal methods
867  
868  
869 # _croak
870 # Kill off any executing stages, issue an error message, and quit.
871 # Make sure that the quit happens even if the rest of the cleanup fails
872  
873 method _croak => sub {
874 my $self = shift;
875 my $msg = shift;
876 my $fatalfailed;
877 try {
878 $self->fatal($msg);
879 }
880 catch {
881 ++$fatalfailed;
882 };
883 try {
884 $self->kill_stages if $self->_finished_cnt < $self->_stage_cnt;
885 }
886 catch {
887 try {
888 $self->fatal("Additional failure during cleanup: $_")
889 unless $fatalfailed;
890 }
891 };
892 confess $msg;
893 };
894  
895 method _croak_extra => sub {
896 return;
897 };
898  
899 # _submit_ready
900 # - submit all stages that are ready to be run
901 # - that will be stages which have no pre_reqs, or for which all pre_reqs
902 # have completed successfully
903  
904 method _submit_ready => sub {
905 my $self = shift;
906 my $min_submit_window = 500_000; # 0.5 second
907 my $min_delay = 1_000; # 1 millisecond is not worth a delay
908 $self->info("Searching for unblocked stages to submit.\n");
909 while ( keys %{ $self->_ready } ) {
910 # tricky loop through all of the keys of the _ready list
911 # cannot just use: for my $name ( keys %{ $self->_ready } )
912 # as the loop because the loop will be not just deleting $name
913 # (which the for loop is guaranteed to survive and still return
914 # all of the keys), but it can also add new keys when a stage
915 # is elegible to be skipped. That could cause the for loop to
916 # terminate while there are still keys in the hash, and might
917 # give the appearance of a dependency loop where there is not
918 # really one present.
919 (my $name) = keys %{ $self->_ready };
920 return 1 if $self->max_concurrent
921 && $self->max_concurrent <= $self->_running_cnt;
922 delete $self->_ready->{$name};
923 my $stage = $self->_stages->{$name};
924 $stage->assert_command_filled;
925 if ($stage->_can_be_skipped) {
926 $self->info("Successful skip of stage ($name).\n");
927 $self->_completed->{$name} = 1;
928 $self->_finished_cnt( $self->_finished_cnt + 1 );
929 $self->_unblock_deps($name);
930 $stage->_set_state('pass');
931 return 0;
932 }
933 if ( ! $stage->_files_ready_to_start_stage) {
934 # required in file not present, abort running the stage
935 $self->fail_stage( $name, $stage );
936 $self->_finished_cnt( $self->_finished_cnt + 1 );
937 $self->_discard_deps($stage);
938 return 0;
939 }
940 $self->_running_cnt( $self->_running_cnt + 1 );
941 $self->_submitted->{$name} = 1;
942 my ( $now_secs, $now_microsecs ) = gettimeofday;
943 if ($stage->_has_command && $now_secs < $self->_sub_secs + 2) {
944 my $delta_microsecs =
945 ( $now_secs - $self->_sub_secs ) * 1_000_000 +
946 ( $now_microsecs - $self->_sub_microsecs );
947 $delta_microsecs = $min_submit_window - $delta_microsecs;
948 if ($delta_microsecs > $min_delay) {
949 $self->info(
950 "Safety delay ($delta_microsecs) microseconds before submit.\n"
951 );
952 usleep($delta_microsecs) if $delta_microsecs;
953 $now_microsecs += $delta_microsecs;
954 # 'while' instead of 'if'
955 # to allow delay bounds to be adjusted in the future
956 while ($now_microsecs > 1_000_000) {
957 $now_microsecs -= 1_000_000;
958 $now_secs++;
959 }
960 }
961 }
962 $self->_sub_secs($now_secs);
963 $self->_sub_microsecs($now_microsecs);
964 $self->info("Submitting stage ($name).\n");
965 $self->submit_stage( $stage );
966 }
967 return 1;
968 };
969  
970 # _unblock_deps
971 # - after a stage has finished successfully, any stages that are
972 # dependent upon it can be (possibly partially) unblocked
973 # - if this is the final block for a dependent, it is marked ready to run
974  
975 method _unblock_deps => sub {
976 my $self = shift;
977 my $pre_req = shift;
978 for my $dep ( keys %{ $self->_deps->{$pre_req} } ) {
979 delete $self->_pre_reqs->{$dep}{$pre_req};
980 $self->debug( "removing dep: $pre_req -> $dep, remaining deps are( "
981 . join( ' ', sort keys %{ $self->_pre_reqs->{$dep} } )
982 . " )" );
983 unless (keys %{ $self->_pre_reqs->{$dep} }) {
984 $self->_ready->{$dep} = 1
985 if delete $self->_blocked->{$dep};
986 }
987 }
988 };
989  
990 # _blocked_deps_list
991 # - get all deps recursively
992  
993 method _blocked_deps_list => sub {
994 my $self = shift;
995 my $target = shift;
996 my $seen = shift || {};
997 for my $dep ( grep { !$seen->{$_} && $self->_blocked->{$_} }
998 keys %{ $self->_deps->{$target} } )
999 {
1000 $seen->{$dep} = 1;
1001 $self->_blocked_deps_list( $dep, $seen );
1002 }
1003 return $seen;
1004 };
1005  
1006 # _discard_deps
1007 # - after a stage has failed. the action to be taken is determined by the
1008 # setting of the failure_action attribute
1009 #
1010 # - abort_group
1011 # - discard all unstarted stages
1012 # - abort_deps
1013 # - discard all stages that are deps of the failed stage
1014 # (and their deps, recursively)
1015 # - ignore
1016 # - continue with all other stages
1017  
1018 method _discard_deps => sub {
1019 my $self = shift;
1020 my $stage = shift;
1021  
1022 my $action = $stage->failure_action;
1023  
1024 return if $action eq 'ignore';
1025  
1026 my $name = $stage->name;
1027 my $reason = "failure of stage $name";
1028 my $list = $action eq 'abort_deps'
1029 ? $self->_blocked_deps_list( $name )
1030 : $self->_blocked; # $action eq 'abort_group'
1031  
1032 $self->_discard_list( $reason, $list );
1033 };
1034  
1035 method _discard_list => sub {
1036 my $self = shift;
1037 my $reason = shift;
1038 my $list = shift // $self->_blocked;
1039 my @discards = sort keys %$list;
1040 for my $stage (@discards) {
1041 $self->error(
1042 "Skipping stage ($stage) because of $reason");
1043 $self->_finished_cnt( $self->_finished_cnt + 1 );
1044 delete $self->_blocked->{$stage};
1045 $self->_failed->{$stage} = 1;
1046 $self->_stages->{$stage}->_set_failure_info(
1047 "Skipped because of $reason");
1048 }
1049 };
1050  
1051 # _await_one_job
1052 # - wait until a running stage completes
1053 # - if it failed: remove any stages that depend upon it
1054 # (or all remaining jobs if abort_group_on_failure was set)
1055  
1056 method _await_one_job => sub {
1057 my $self = shift;
1058 my $stage = $self->wait_for_fully_completed_stage;
1059 my $name = $stage->name;
1060  
1061 delete $self->_submitted->{$name};
1062 $self->_finished_cnt( $self->_finished_cnt + 1 );
1063 $self->_running_cnt( $self->_running_cnt - 1 );
1064 if ($stage->is_pass) {
1065 $self->info("Successful completion of stage ($name).\n");
1066 $self->_completed->{$name} = 1;
1067 }
1068 else {
1069 # job failed and cannot be resubmitted
1070 $self->fail_stage( $name, $stage );
1071 }
1072 $self->_unblock_deps($name);
1073 };
1074  
1075 method fail_stage => sub {
1076 my $self = shift;
1077 my $name = shift;
1078 my $stage = shift;
1079 $self->error( "Failed stage ($name).\n" );
1080 $self->_failed->{$name} = 1;
1081 $self->_discard_deps( $stage );
1082 $stage->_set_state( 'fail' );
1083 };
1084  
1085 # wait for a stage to complete
1086 # - if it failed, determine whether it can be retried
1087 #
1088 # if it can be restarted, it will be marked as such, and any recomputing
1089 # of its internal info required for the retry will have already been done.
1090 # All that is required is to actually resubnit it for execution
1091 #
1092 # return the first completed stage that does not need to be restarted
1093 method wait_for_fully_completed_stage => sub {
1094 my $self = shift;
1095 while (1) {
1096 my $stage = $self->wait_for_completed_stage;
1097 return $stage unless $stage->is_retry;
1098 $self->retry($stage);
1099 }
1100 };
1101  
1102 # this method can be over-ridden if cluster-specific code needs to take
1103 # any action different from the submit done initially that can't be
1104 # handled already in the wait_for_completed_stage method
1105 method retry => sub {
1106 my $self = shift;
1107 my $stage = shift;
1108 $self->warn( "Retrying stage(".$stage->name.")");
1109 $self->submit_stage($stage);
1110 };
1111  
1112 };
1113  
1114 =head1 AUTHOR
1115  
1116 Christopher Lalansingh - Boutros Lab
1117  
1118 John Macdonald - Boutros Lab
1119  
1120 =head1 ACKNOWLEDGEMENTS
1121  
1122 Paul Boutros, Phd, PI - Boutros http://www.omgubuntu.co.uk/2016/03/vineyard-wine-configuration-tool-linuxLab
1123  
1124 The Ontario Institute for Cancer Research
1125  
1126 =cut
1127  
1128 1;
1129