blib/lib/HPCI/Stage.pm untested

filter: Statementstmt 0.0% 0 / 307 Branchbran 0.0% 0 / 90 Conditioncond 0.0% 0 / 32 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 57 Podpod 0.0% 0 / 45 totaltotal 0.0% 0 / 531 CC 32 SCAR 23.9
CC
32
Cov
0%
set_argparse_cmd
42.0
set_gnu_cmd
42.0
res_hash_map
20.0
CRAP 10.9
1 package HPCI::Stage;
2  
3 ### INCLUDES ##################################################################
4  
5 # safe Perl
6 use warnings;
7 use strict;
8 use Carp;
9 use Data::Dumper;
10 use HPCI::File;
11 use File::Spec;
12  
13 use List::Util qw(first);
14 use Scalar::Util 'blessed';
15  
16 use Moose::Role;
17 use Moose::Util::TypeConstraints;
18 use MooseX::ClassAttribute;
19 use MooseX::Types::Path::Class qw(Dir File);
20  
21 # available for roles to wrap around, does nothing by default
22 sub BUILD {
23 }
24  
25 around BUILDARGS => sub {
26 my $orig = shift;
27 my $class = shift;
28 my %parms = ( @_ );
29  
30 # support historical boolean parms for a while
31 if (delete $parms{abort_group_on_failure}) {
32 $parms{failure_action} = 'abort_group';
33 }
34  
35 if (delete $parms{abort_deps_on_failure}) {
36 $parms{failure_action} = 'abort_deps';
37 }
38  
39 if (delete $parms{ignore_failure}) {
40 $parms{failure_action} = 'ignore';
41 }
42  
43 return $class->$orig(%parms);
44 };
45  
46  
47 =head1 NAME
48  
49 HPCI::Stage;
50  
51 =head1 SYNOPSIS
52  
53 Role for building a cluster-specific driver for a stage.
54 A stage is the object that describes a single job to be executed
55 within the context of a group. It will be a member of a group
56 object, which will be responsible for ensuring that the stage is
57 executed after any prerequisite stages, and before any dependent
58 stages. Most of the activity of a stage will be cluster-specific.
59  
60 This role defines the generic, cluster-agnostic interface for a
61 stage, hiding the details of the specific cluster implementation.
62 A driver which consumes this role must provide methods for this
63 interface, translating it into the specific implementation that
64 best fits the specific type of cluster that it supports. The driver
65 can also provide method for accessing facilities provided by its
66 cluster type that don't fit into the generic interface (but, of
67 course, any program that uses these methods will be less able to
68 move to using a different type of cluster)
69  
70 A (internally defined) cluster stage is defined with:
71  
72  
73 package HPCD::$cluster::Stage;
74 use Moose;
75  
76 # define the required attributes/methods here
77  
78 with 'HPCI::Stage';
79  
80 # define the additional attributes/methods here
81  
82  
83 =head1 DESCRIPTION
84  
85 This role provides the generic interface for a stage object,
86 which can be used to control a single stage. A stage is the
87 unit of job execution that a grroup can schedule and assigne
88 to a node within a cluster.
89  
90 A cluster-specific stage object definition can consume this
91 role to ensure that it provides the interface needed by a
92 HPCI using that type of cluster to run a group of stages.
93  
94 New objects of the cluster-specific type are not created by
95 the user code - instead the user works through a HPCI
96 group object to ensure that any stage objects that it includes
97 within the group are of a cluster-specific compatible form to
98 the cluster-specific group object, and to allow the group to
99 register the stage so that it can be managed.
100  
101 In fact, user code will generally not need to access the
102 stage object itself at all. References to it will usually
103 be made by passing its name to methods of the group object,
104 rather than handled directly.
105  
106 =head1 ATTRIBUTES
107  
108 =cut
109  
110 sub _build_valid_resources {
111 my $self = shift;
112 return {
113 $self->can('_build_cluster_specific_valid_resources')
114 ? $self->_build_cluster_specific_valid_resources
115 : ()
116 };
117 }
118  
119 class_has '_valid_resources' => (
120 is => 'ro',
121 isa => 'HashRef',
122 lazy => 1,
123 builder => '_build_valid_resources',
124 );
125  
126 sub _build_default_resources {
127 my $self = shift;
128 my $res = {
129 $self->can('_build_cluster_specific_default_resources')
130 ? $self->_build_cluster_specific_default_resources
131 : ( )
132 };
133 $res->{_default_subs_}{h_time} = '_default_h_time';
134 $res->{_default_subs_}{s_time} = '_default_s_time';
135  
136 return $res;
137 }
138  
139 class_has '_default_resources' => (
140 is => 'ro',
141 isa => 'HashRef',
142 lazy => 1,
143 builder => '_build_default_resources',
144 );
145  
146 sub _default_h_time {
147 my $self = shift;
148 my $vals = shift;
149 my $soft = $vals->{s_time};
150 return unless defined $soft;
151 # if soft time was provided, but no hard time, give an hour extra for hard
152 return $self->_secs_to_time( $self->_time_to_secs($soft) + 60*60 );
153 }
154  
155 sub _secs_to_time {
156 my $self = shift;
157 my $base = my $origbase = shift;
158 my $res = '';
159 return '0' unless $base;
160 my @units = ( [ 60, '' ], [ 60, 'm' ], [ 24, 'h' ], [ 99, 'd' ], );
161 for my $unitpair (@units) {
162 my ( $size, $name ) = @$unitpair;
163 return "$base$name$res" if $base < $size;
164 my $rem = $base % $size;
165 $base = int( $base / $size );
166 $res = "$rem$name$res";
167 }
168 $self->_croak("Run time of more than 100 days seems insane ($origbase)");
169 }
170  
171 sub _time_to_secs {
172 my $self = shift;
173 my $time = shift;
174 my $res = 0;
175 my %name2secs = (
176 d => 24 * 60 * 60,
177 h => 60 * 60,
178 m => 60,
179 s => 1,
180 );
181 while ($time =~ m/\G\s*(\d+)\s*(\w?)/g) {
182 my ($num, $let) = ($1, $2);
183 my $mult = 1;
184 if ($let) {
185 $mult = $name2secs{ lc($let) }
186 // $self->_croak("Unknown code ($let) in time string ($time)");
187 }
188 $res += $num * $mult;
189 }
190 return $res;
191 }
192  
193 sub _default_s_time {
194 my $self = shift;
195 my $vals = shift;
196 # return $vals->{h_time}; # same as h_time or undef if no h_time provided
197 return undef;
198 }
199  
200 sub _build_default_retry_resources {
201 my $self = shift;
202 return $self->can("_build_cluster_specific_default_retry_resources")
203 ? { $self->_build_cluster_specific_default_retry_resources }
204 : { };
205 }
206  
207 class_has '_default_retry_resources' => (
208 is => 'ro',
209 isa => 'HashRef',
210 lazy => 1,
211 builder => '_build_default_retry_resources',
212 );
213  
214 =head2 command
215  
216 The command to be executed on the cluster. This command will quite
217 possibly be wrapped in a cluster-specific manner to pass the command
218 and environment info to the target cluster node.
219  
220 The command can either be provided as an explicit parameter when
221 the stage is created, or by using one of the B<set_*_cmd> methods
222 described below after the stage object is created.
223  
224 This is the only time that you need the stage object itself rather
225 than just referring to it by its name. However, even here, unless
226 you need to separate the creation of the stage object from the
227 point where you specify the command you can do something like:
228  
229 my $group = HPCI->group( ...);
230  
231 ...
232  
233 $group->stage( name => 'thisstage', ... )
234 ->set_perl_cmd(
235 $program,
236 f => undef, # a flag argument: -f
237 flag => undef, # another flag argument: --flag
238 v => $value, # a value argument: -v $value
239 val => $value, # another value argument: --val $value
240 l => [ qw(a b c}] # a list argment: -l a -l b -l c
241 list => [ qw(a b c}] # another list argment: --list a --list b --list c
242 '--' => [ f1 f2 ] # non-keyed argument(s): f1 f2
243 );
244 # set the command to: perl $program -f --flag -v $value --val $value \
245 # -l a -l b -l c --list a --list b --list c f1 f2
246  
247 As an alternative to the command attribute, you can specify the code
248 attribute described below.
249 It is required that one of these be provided before the group tries to
250 execute this stage.-, and only one of them can be provided (no9t both)
251  
252 =cut
253  
254 has 'command' => (
255 is => 'rw',
256 isa => 'Str',
257 predicate => '_has_command',
258 trigger => sub { shift->_only_one( '_has_code' ) },
259 );
260  
261 =head2 code
262  
263 The code attribute is an alternate to the command attribute described
264 above. Its value is a code reference, which will be called directly
265 to carry out the activity of the Stage. You can use this for a stage
266 activity that is simple enough to code as a perl routine that it does
267 not make sense to go through the overhead of creating a new job on a
268 cluster node to do this activity. You may not specify B<both> B<code>
269 and B<command> for the same stage; but you must specify one of them
270 before the stage is ready to execute.
271  
272 The code in the reference is called with no arguments when the stage
273 is ready to be executed. The return value is treated as a boolean to
274 indicate whether the stage succeeded: a false value for success, or a
275 true value for failure (with the value usually being a text message
276 describing the cause of the failure). This mimics the exit_status
277 that is returned from a separately executed program (except for being
278 able to provide a more easily understood failure code than a simple
279 integer) - however, it does mean that some common purposes for this
280 attribute will need some wrapping code. For example, any B<code> that
281 is just providing a system call (e.g. unlink, link, rename) will need to
282 invert the boolean result, and expand the failure result to provide the
283 errno value, such as:
284  
285 stage(
286 ...
287 code => sub {
288 unlink $tmpfile ? 0 : $!
289 },
290 ...
291 )
292  
293 =cut
294  
295 has 'code' => (
296 is => 'ro',
297 isa => 'CodeRef',
298 predicate => '_has_code',
299 trigger => sub { shift->_only_one( '_has_command' ) },
300 );
301  
302 sub _only_one {
303 my $self = shift;
304 my $has_other = shift;
305 $self->_croak( "Exactly one of 'code' or 'command' attributes must be specified, not both" )
306 if $self->$has_other;
307 }
308  
309 sub assert_command_filled {
310 my $self = shift;
311 $self->_croak(
312 "Trying to submit stage ("
313 . $self->name
314 . "), but neither command nor code have been set"
315 )
316 unless $self->_has_command || $self->_has_code;
317 }
318  
319 has 'stage_dir_name' => (
320 is => 'ro',
321 isa => 'Str',
322 lazy => 1,
323 default => sub {
324 my $self = shift;
325 return $self->name;
326 },
327 );
328  
329 has 'stage_dir' => (
330 is => 'ro',
331 isa => Dir,
332 coerce => 1,
333 lazy => 1,
334 default => sub {
335 my $self = shift;
336 my $target;
337 if ($self->_has_dir) {
338 $target = $self->dir;
339 }
340 else {
341 $target = $self->group->group_dir->subdir( $self->stage_dir_name );
342 }
343 HPCI::_trigger_mkdir($self,$target);
344 return $target;
345 },
346 trigger => \&HPCI::_trigger_mkdir,
347 );
348  
349 has 'dir' => (
350 is => 'ro',
351 isa => Dir,
352 coerce => 1,
353 predicate => '_has_dir'
354 );
355  
356 =head2 resources_required
357  
358 A hash that maps resource names to the amount of that resource
359 that is needed.
360  
361 TODO: Describe the generic resource names, the value types that can
362 be used, and the non-default cluster-specific names that can be
363 used instead.
364  
365 =cut
366  
367 has 'resources_required' => (
368 is => 'ro',
369 isa => 'HashRef[Str]',
370 default => sub { return {} },
371 );
372  
373 has '_use_resources_required' => (
374 is => 'ro',
375 isa => 'HashRef[Str]',
376 lazy => 1,
377 builder => '_init_use_resources_required',
378 );
379  
380 sub _init_use_resources_required {
381 my $self = shift;
382 $self->res_hash_map( $self->resources_required,
383 $self->_default_resources,
384 );
385 }
386  
387 =head2 retry_resources_required
388  
389 A hash that maps resource names to a list of amounts of that resource
390 that might be required.
391  
392 If the cluster-specific interface detects that a runs fails because
393 not enough of a particular resource was requested, then the next
394 larger amount in the retry_resources_required list for that resource
395 type is used and the stage is retried.
396  
397 At present, this is only used for SGE clusters, and only for the
398 B<mem> (or SGE-specific B<h_vmem>) resource. SGE provides a
399 default value of:
400  
401 retry_resources_required => { h_vmem => [qw(2G 4G 8G 16G 32G)] }
402  
403 When you are first running a job and don't know how much memory
404 it will require, you can specify a low value. When it completes,
405 you can check the log to see how much memory it ended up needing,
406 and use that as the starting parameter for future runs. That initial
407 run will have possible had to run part way through, fail, and then
408 retry a number of times. The alternative of providing a large
409 memory allocation the first time takes resources from your cluster
410 (and especially if you never get around to changing the initial
411 setting - people are more likely to remember to make such a change
412 when it will save them time by avoiding retries than when it just
413 happens to reserve more space than is actually used).
414  
415 =cut
416  
417 has 'retry_resources_required' => (
418 is => 'ro',
419 isa => 'HashRef[ArrayRef[Str]]',
420 default => sub { return {} },
421 );
422  
423 has '_use_retry_resources_required' => (
424 is => 'ro',
425 isa => 'HashRef[ArrayRef[Str]]',
426 lazy => 1,
427 default => sub {
428 my $self = shift;
429 $self->res_hash_map( $self->retry_resources_required,
430 $self->_default_retry_resources,
431 );
432 # need to provide converter support here
433 # e.g. turn a time from '2d3h' to (2*24+3)*60*60 (seconds)
434 },
435 );
436  
437 sub res_hash_map {
438 my $self = shift;
439 my $provided = shift;
440 my $default = shift;
441 my $determined = {};
442 my $map = $self->_valid_resources;
443 for my $cluster_res (keys %$map) {
444 my $common_res = $map->{$cluster_res} || $cluster_res;
445 if (my $use_res = $provided->{$cluster_res}
446 // $provided->{$common_res}
447 // $default->{$cluster_res}
448 // $default->{$common_res})
449 {
450 $determined->{$cluster_res} = $use_res;
451 }
452 }
453 my $initters = $default->{_default_subs_} // {};
454 for my $key (keys %$initters) {
455 unless (defined $determined->{$key}) {
456 my $func = $initters->{$key};
457 my $res = $self->$func($determined);
458 $determined->{$key} = $res if defined $res;
459 }
460 }
461 return $determined;
462 }
463  
464 =head2 native_args_string
465  
466 The native program mechanism used by the driver to submit a stage
467 for execution can have many arguments. Some of those will be provided
468 automatically from the generic HPCI attributes, but there may be extra
469 capabilities that do not match the standard HPCI definition.
470  
471 Using these extra capabilities can lead to non-portable programs, unless
472 you are careful. HPCI provides two ways to be careful but also
473 allows you to be careless.
474  
475 If you (carelessly) provide this attribute directly, then it will be used
476 for any type of cluster that your program is run on - using such
477 cluster-specific parameters can have dangerous or obscure effects when
478 applied to a different cluster type.
479  
480 You can be careful, by providing this attribute only within an
481 attribute set included in the cluster_specific attribute.
482 The alternate way to be careful is to provide this attribute indirectly,
483 using the cluster-specific name which the driver specifies as the
484 native_args_string_name attribute.
485  
486 The value provided to native_args_string will be passed to the native
487 submissions mechanism when-ever that makes sense. A driver that uses a
488 submission mechanism that does not provide for any non-standard HPCI
489 capabilities may choose to ignore this attribute.
490  
491 So, for example, if you wished to provide extra args for the qsub command
492 when running on an SGE cluster you could code that as either:
493  
494 $group->stage(
495 name => 'stage_name',
496 ...
497 cluster_specific => {
498 SGE => { native_args_string => '-q myqueue -m beas' },
499 ... # put args strings for other cluster types here
500 },
501 ...
502 );
503  
504 or as:
505  
506 $group->stage(
507 name => 'stage_name',
508 ...
509 extra_sge_args_string => '-q myqueue -m beas',
510 ... # put args strings for other cluster types here
511 # using the appropriate cluster-specific attribute name
512 ...
513 );
514  
515 =head2 native_args_string_name
516  
517 This attribute is one way in which a driver can help you to use native
518 arguments in a portable way. Drivers that actually use the native_args_string
519 attribute will specify a value for this attribute internally - it is never
520 provided directly as a Stage attribute. If this attribute is provided by the
521 driver, then only the value of the attribute it names will be used for the
522 source text of native_args_string.
523  
524 =head2 _native_args_string_parsing_info
525  
526 This internal attribute is provided by the driver. It specifies how the
527 native_args_string is parsed, controlling how it is separated into
528 parameters and values, which parameters are normally provided by altenate
529 HPCI mechanisms, how the parameters and values are displayed in the log
530 (if it is different from how they are inserted into the command line for
531 execution), etc.
532  
533 Only people writing drivers need to worry about this attribute.
534  
535 =head2 native_args* support not implemented yet
536  
537 The attributes related to native_args_string processing are not yet ready for
538 use; they are being implemented by copying and generalizing the code from the
539 SGE and Slurm drivers, that is still in progress.
540  
541 =cut
542  
543 has 'native_args_string' => (
544 is => 'ro',
545 isa => 'Str',
546 default => ''
547 );
548  
549 has 'native_args_string_name' => (
550 is => 'ro',
551 isa => 'Maybe[Str]',
552 init_arg => undef,
553 default => undef # driver can over-ride this setting
554 );
555  
556 has 'native_args_string_parsing_info' => (
557 is => 'ro',
558 isa => 'HashRef',
559 init_arg => undef,
560 builder => 'default_args_string_parsing_info'
561 );
562  
563 # driver can over-ride this method to provide a non-empty list
564 # of parsing info
565 sub default_args_string_parsing_info {
566 return {}
567 }
568  
569  
570 =head2 state, is_ready, is_blocked, is_pass, is_fail
571  
572 These states are mostly for internal use during execution. (There
573 are actually more states than are listed here but they are only
574 meaningful during execution when the calling program doesn't have
575 access to the state, and they are subject to change without notice.)
576  
577 However, before execute is called, a stage can be either B<ready>
578 or B<blocked> (depending upon whether any other stage has been
579 noted as a pre-requisite).
580  
581 After execution completes, a stage will be in either B<pass> or B<fail> state
582 (and the B<is_complete> attribute will always be true). This is probably
583 the only significant setting to check from user code.
584  
585 The state attribute is a string value, but it can be tested using
586 the is_STATE methods, each of which returns true if the stage is
587 in the specified state.
588  
589 =cut
590  
591 enum 'StageState', [qw(ready blocked running retry pass fail)];
592  
593 has 'state' => (
594 is => 'ro',
595 isa => 'StageState',
596 writer => '_set_state',
597 default => 'ready',
598 init_arg => undef,
599 );
600  
601 sub is_ready {
602 my $self = shift;
603 return $self->state eq 'ready';
604 }
605  
606 sub is_blocked {
607 my $self = shift;
608 return $self->state eq 'blocked';
609 }
610  
611 sub is_running {
612 my $self = shift;
613 return $self->state eq 'running';
614 }
615  
616 sub is_retry {
617 my $self = shift;
618 return $self->state eq 'retry';
619 }
620  
621 sub is_pass {
622 my $self = shift;
623 return $self->state eq 'pass';
624 }
625  
626 sub is_fail {
627 my $self = shift;
628 return $self->state eq 'fail';
629 }
630  
631 sub is_complete {
632 my $self = shift;
633 return $self->is_pass || $self->is_fail;
634 }
635  
636 =head2 verify_completion_state
637  
638 If the user wishes to verify whether a stage completed successfully,
639 failed, or should be retried, this attribute can be given a coderef
640 to code that checks the result.
641  
642 The code will be called with the arguments:
643  
644 $coderef->( $stats, $stdout, $stderr, $state )
645 $stats is a hashref containing the accounting info and status of the job
646 $stdout is the pathname of the stdout file
647 $stderr is the pathname of the stderr file
648 $state is the state determined by HPCI
649 (only pass/fail - retry has not been decided yet)
650  
651 The code can use these (and knowledge provided by the user about the stage
652 operation) to test whether the stage succeeded.
653  
654 To select a specific state, the return value from the code should be a string, one of:
655  
656 pass
657 fail
658 retry
659  
660 If your function does not wish to select a state, it can return undef, and the
661 same state that would be been chosen without the call to this function will be
662 used unchanged.
663  
664 If the value returned is 'fail', other standard HPCI mechanisms may still apply
665 that might change the choice to 'retry'.
666  
667 If the value returned is 'retry', it will either retry the stage or be
668 changed to fail state, depending upon whether the limit for the choose_retries
669 attribute has been reached.
670  
671 This code attribute could be used for:
672  
673 - running a program that always gives an error status, but you might wish to
674 treat it as successful
675  
676 - running a program that can give a zero status but not actually succeed (but
677 perhaps a retry will succeed)
678  
679 An example might look like:
680  
681 $group->stage(
682 ....
683 verify_completion_status => sub {
684 my( $stats, $stdout, $stderr, $state ) = @_;
685 # retry if output file is zero length
686 return 'retry' if $state eq 'pass' && ! -s $my_output_file;
687 # otherwise, normal processing
688 return;
689 },
690 ...
691 );
692  
693 =cut
694  
695 has 'verify_completion_state' => (
696 is => 'ro',
697 isa => 'CodeRef',
698 predicate => '_has_verify_completion_state',
699 );
700  
701 after '_analyse_completion_state' => sub {
702 my $self = shift;
703 my $run = shift;
704  
705 if ($self->is_pass && (my $files = $self->_use_files) ) {
706 my $script_time = $self->_file_timestamp_for_out( $self->script_file );
707 if ( my $outfiles = $files->{out}) {
708 my $fs_delay = $self->group->file_system_delay;
709 while ( my ($type, $fileval) = each %$outfiles ) {
710 FILE:
711 for my $file ( @$fileval ) {
712 while ($fs_delay && ! $file->exists_out_file) {
713 my $sleep_time = ($fs_delay > 5) ? 5 : $fs_delay;
714 $fs_delay -= $sleep_time;
715 sleep $sleep_time;
716 }
717 my $timestamp;
718 if ($file->exists_out_file) {
719 if ( ($timestamp = $file->timestamp)
720 <= $script_time) {
721 $file->accepted_for_out;
722 next FILE;
723 }
724 }
725 else {
726 next FILE if $type eq 'opt';
727 }
728 # a req file was not found
729 $self->_set_state('fail');
730 $run->stats->{failure_detected} = "required output file ($file) not updated";
731 $self->error(
732 "Stage (",
733 $self->name,
734 ") status changed to failed because required output file ",
735 $file,
736 " was not updated"
737 );
738 if ($timestamp) {
739 $self->error(
740 "mod time: (",
741 $timestamp,
742 ") for file($file) should be more recent (less) than script time (",
743 $script_time,
744 ")"
745 );
746 # my $script_file = $self->script_file;
747 # $self->error(
748 # "ls:\n",
749 # `ls --full-time $script_file $file`
750 # );
751 # $self->error(
752 # "-M:\n\t\t",
753 # -M "$script_file", "\t$script_file", "\n\t\t",
754 # -M "$file","\t$file",
755 # );
756 }
757 else {
758 $self->error( "file ($file) does not exist" );
759 }
760 }
761 }
762 }
763 }
764 if ($self->_has_verify_completion_state) {
765 my $code = $self->verify_completion_state->(
766 $run->stats,
767 $run->_stdout,
768 $run->_stderr,
769 $self->state
770 );
771 if ($code eq 'retry') {
772 $code = 'fail';
773 $run->_analysis_chose_retry(1);
774 }
775 $self->_set_state( $code ) if $code eq 'pass' || $code eq 'fail';
776 }
777 };
778  
779 # sub _files_acceptable_for_completed_stage {
780 # my $self = shift;
781 # my $run = shift;
782 # return 1 unless $self->_use_files;
783 # my $out = $self->files->{out} or return 1;
784 # my $retval = 1; # success unless non-updated file found
785 # my $before = $self->_file_timestamp_for_out( $run->dir );
786 # while ( my ($type, $fileval) = each %$out ) {
787 # for my $file ($self->_scalar_list($fileval)) {
788 # # need to check exist on opt files in case
789 # # the driver needs to take special action to
790 # # collect the result from the completed stage
791 # #
792 # # go through the entire list of files to give user
793 # # a full list of invalid files rather than just the
794 # # first one we notice - let them fix everything for
795 # # the next run instead of needing separate extra
796 # # runs to be notified of each successive issue
797 # my $error_text;
798 # if ( ! $self->_file_exists_for_out($file)
799 # && $type eq 'req') {
800 # ++$error_text;
801 # $self->error( "Required output file ($file) is not present" );
802 # }
803 # elsif ($self->_file_timestamp_for_out($file) < $before) {
804 # # file was not updated
805 # my $msg = "output file ($file) was not changed";
806 # if ($type eq 'req') {
807 # ++$error_text;
808 # $self->error( "Required $msg" );
809 # }
810 # else {
811 # $self->warn( "Optional $msg" );
812 # }
813 # }
814 # if ($error_text) {
815 # $self->_set_failure_info(
816 # "Failed stage (",
817 # $self->name,
818 # ") after 'successful' execution because one or more required output files were not updated"
819 # );
820 # $retval = 0;
821 # }
822 # }
823 # }
824 # return $retval;
825 # }
826  
827 sub _files_actions_after_success {
828 my $self = shift;
829 my $run = shift;
830 return 1 unless $self->_use_files;
831 if (my $pairs = $self->_use_files->{rename}) {
832 for my $pair (@$pairs) {
833 my ($from, $to) = @$pair;
834 $from->rename($to);
835 }
836 }
837 $_->delete for @{ $self->_use_files->{delete} };
838 }
839  
840 sub _file_exists {
841 return -e $_[1];
842 }
843  
844 sub _file_timestamp {
845 return -e $_[1] ? -M _ : undef;
846 }
847  
848 # allow drivers to over-ride the definition of various file routines
849 # in various contexts
850 sub _file_exists_for_skip {
851 shift->_file_exists(@_);
852 }
853  
854 sub _file_exists_for_in {
855 shift->_file_exists(@_);
856 }
857  
858 sub _file_exists_for_out {
859 shift->_file_exists(@_);
860 }
861  
862 sub _file_exists_for_delete {
863 shift->_file_exists(@_);
864 }
865  
866 sub _file_accepted_for_out {
867 ; # no action in normal case
868 }
869  
870 sub _file_timestamp_for_skip {
871 shift->_file_timestamp(@_);
872 }
873  
874 sub _file_timestamp_for_out {
875 shift->_file_timestamp(@_);
876 }
877  
878 sub _delete_file {
879 unlink $_[1];
880 }
881  
882 sub _unshared_file_exists_for_in {
883 }
884  
885 sub _unshared_file_download_for_in {
886 }
887  
888 sub _unshared_file_exists_for_out {
889 }
890  
891 sub _unshared_file_upload_for_out {
892 }
893  
894 sub _rename_file {
895 my $self = shift;
896 my $src = shift;
897 my $dst = shift;
898 if ($self->_file_exists($src)) {
899 link $src, $dst;
900 unlink $src;
901 }
902 }
903  
904 sub _file_list_acceptable_for_skip {
905 my $self = shift;
906 my $newest_pre = shift;
907 my $list = shift;
908 for my $file (@$list) {
909 my $ts = $file->timestamp;
910 if (not defined $ts) {
911 $self->debug( "target file does not exist: $file" );
912 return undef;
913 }
914 if ($newest_pre) {
915 unless ($ts <= $newest_pre) {
916 $self->debug( "target too old: timestamp of $file($ts) should be newer (less) than newest prerequisite ($newest_pre)" );
917 return undef;
918 }
919 }
920 }
921 return 1;
922 }
923  
924 =head2 should_choose_retry, choose_retries
925  
926 If a cluster has a tendency to fail randomly, it may be desired to
927 retry a stage that fails rather than simply treating it as an unrecoverable
928 failure.
929  
930 This pair of attributes specifies two aspects of making such a choice.
931  
932 First, the should_choose_retry attribute can be given a code reference to code
933 that returns true if a retry should be made. This code is only called if the
934 stage run has failed.
935  
936 The sub is called with two arguments:
937 the status hash containing the known status results from the most recent try to
938 run the stage, and a string with the name of the stderr output file. This code
939 returns a true value to indicate that a retry should be attempted. If this
940 attribute is not explicitly provided, it defaults to code that always returns 0
941 to not cause a retry attempt.
942  
943 Second, the choose_retries attribute specifies number of times that the stage
944 should be retried at the request of the should_choose_retry code (or at the
945 request of the verify_completion_status code).
946 The default is 1.
947  
948 =cut
949  
950 has 'should_choose_retry' => (
951 is => 'ro',
952 isa => 'CodeRef',
953 predicate => '_has_should_choose_retry'
954 );
955  
956 has 'choose_retries' => (
957 is => 'ro',
958 isa => 'Int',
959 lazy => 1,
960 default => 1,
961 );
962  
963 has '_chosen_retries' => (
964 is => 'rw',
965 isa => 'Int',
966 init_arg => undef,
967 default => 0
968 );
969  
970 =head2 force_retries
971  
972 If a cluster has a tendency to fail randomly, it may be desired to
973 retry a stage that fails rather than simply treating it as an unrecoverable
974 failure.
975  
976 This attribute specifies the number of times that the stage should be retried
977 until it passes. The default is to not retry (unless the underlying driver
978 retries for a specific reason).
979  
980 There are three types of retry selections. First, the devide driver can provide
981 automatic retries for considitions appropriate to that cluster type. Second,
982 the retries selected by the should_choose_retry attribute can cause a retry if
983 the user-provided code chooses. Finally, the force_retries attribute can cause
984 a retry. Each of these three is independent - any of them can cause a retry
985 regardless of what the others would select. A stage only is deemed to have
986 failed completely if none of the methods selects a retry. The counters for each
987 type of retry test is only adjusted if that test was the one that caused a retry
988 so there can be as amny retries as the total of the number allowed by each type.
989  
990 =cut
991  
992 has 'force_retries' => (
993 is => 'ro',
994 isa => 'Int',
995 default => 0
996 );
997  
998 has '_forced_retries' => (
999 is => 'rw',
1000 isa => 'Int',
1001 init_arg => undef,
1002 default => 0
1003 );
1004  
1005 has '_failure_info' => (
1006 is => 'ro',
1007 isa => 'Str',
1008 writer => '_set_failure_info',
1009 predicate => '_has_failure_info',
1010 init_arg => undef,
1011 );
1012  
1013 has 'runs' => (
1014 is => 'ro',
1015 isa => 'ArrayRef',
1016 init_arg => undef,
1017 default => sub { [] },
1018 );
1019  
1020 sub _run {
1021 my $self = shift;
1022 my $runclass = $self->_run_class;
1023 my $run = $runclass->new(
1024 $self->_run_args,
1025 );
1026 push @{ $self->runs }, $run;
1027 return $run;
1028 }
1029  
1030 sub _run_args {
1031 my $self = shift;
1032 return (
1033 stage => $self,
1034 index => scalar( @{ $self->runs } ),
1035 )
1036 }
1037  
1038 sub get_run_stats {
1039 my $self = shift;
1040 return [
1041 $self->_has_failure_info ? { exit_status => $self->_failure_info }
1042 : scalar( @{ $self->runs } ) == 0 ? { exit_status => 'Stage skipped, skip determined it was complete',
1043 final_job_state => 'pass'
1044 }
1045 : map { $_->stats } @{ $self->runs }
1046 ];
1047 }
1048  
1049 =head2 failure_action ('abort_group', 'abort_deps'*, or 'ignore')
1050  
1051 Specifies the action to take if (the final retry of) this stage fails
1052 (terminates with non-zero status).
1053  
1054 There are three string values that it can have:
1055  
1056 =over
1057  
1058 =item - abort_deps (default)
1059  
1060 If the stage fails, then any stages which depend upon it
1061 (recursively) are not run. The group continues executing stages
1062 which are not dependent upon this stage.
1063  
1064 =item - abort_group
1065  
1066 If the stage fails, then no other stages are started. The group
1067 simply waits until previously started stages complete and then
1068 completes execution.
1069  
1070 =item - ignore
1071  
1072 Execution continues unchanged, any dependent stages will be run
1073 when they are no longer blocked.
1074  
1075 =back
1076  
1077 =cut
1078  
1079 enum 'FailureAction', [qw(abort_group ignore abort_deps)];
1080  
1081 has 'failure_action' => (
1082 is => 'ro',
1083 isa => 'FailureAction',
1084 default => 'abort_deps',
1085 );
1086  
1087 with qw(HPCI::Sub HPCI::SuperSub HPCI::Env HPCI::CommandScript HPCI::ScriptSource);
1088  
1089 =head1 METHODS
1090  
1091 =head2 command setting methods
1092  
1093 The following command setting methods can be used as an alternative to
1094 providing the command as a string.
1095  
1096 They each have the same parameter list:
1097  
1098 $stage->set_FOO_cmd( $command,
1099 $key1, $value1,
1100 $key2, $value2,
1101 ...
1102 );
1103  
1104 There are three types of keys - keys with a single letter, longer
1105 keys, and '--'. Single letter keys will be prefixed with a single
1106 dash; longer keys will be prefixed with a double dash. The special
1107 key '--' (two dashes) contains the non-option command line arguments.
1108  
1109 The values can either be a scalar or an arrayref. The way array
1110 values are expanded depends upon the choice of command setting
1111 method used.
1112  
1113 The argparse method (used for python and R) sets lists by putting
1114 all the list variables after a single option word:
1115  
1116 --infiles file1 file2 file3
1117  
1118 The gnuparse method (used for Perl) uses the standard Unix and gnu
1119 command way of setting lists by repeating the option word:
1120  
1121 --infiles file1 --infiles file2 --infiles file3
1122  
1123 In the case of the interpreter methods (set_python_cmd, set_perl_cmd,
1124 set_R_cmd), they simply prepend the appropriate interpreter to the
1125 provided script name, and invoke the right parsing method.
1126  
1127 =head2 set_argparse_cmd
1128  
1129 Set the command attribute to execute a command taking Python's
1130 argparse-style arguments.
1131  
1132 =cut
1133  
1134 sub set_argparse_cmd {
1135 my $self = shift;
1136 my $prog = shift;
1137 my %args = @_;
1138 my @args = ();
1139 my @tail = ();
1140 foreach my $key (sort keys %args) {
1141 if ($key eq '--') {
1142 push @tail, '--',
1143 (ref($args{$key}) eq 'ARRAY') ? (@{$args{$key}})
1144 : $args{$key};
1145 next;
1146 }
1147 push @args,
1148 (length $key > 1) ? "--$key"
1149 : "-$key";
1150 if (defined($args{$key})) {
1151 push @args,
1152 (ref($args{$key}) eq 'ARRAY') ? (@{$args{$key}})
1153 : $args{$key};
1154 }
1155 # else Assume this is a bool ean switch
1156 }
1157 $self->command( join ' ', $prog, @args, @tail );
1158 }
1159  
1160 =head2 set_gnu_cmd
1161  
1162 Set the command line arguments for a command taking GNU's getlongopt-style
1163 arguments.
1164  
1165 =cut
1166  
1167 sub set_gnu_cmd {
1168 my $self = shift;
1169 my $prog = shift;
1170 my %args = @_;
1171 my @args = ();
1172 my @tail = ();
1173 foreach my $key ( sort keys %args ) {
1174 if ($key eq '--') {
1175 push @tail, "--", ( ref( $args{$key} ) eq 'ARRAY' )
1176 ? @{ $args{$key} }
1177 : $args{$key};
1178 next;
1179 }
1180 else {
1181 my $key_prefix = length $key > 1 ? "--$key" : "-$key";
1182 push @args,
1183 ( !defined $args{$key}
1184 ? ($key_prefix)
1185 : map
1186 { ( $key_prefix, $_ ) }
1187 ( ref( $args{$key} ) eq 'ARRAY'
1188 ? @{ $args{$key} }
1189 : $args{$key}
1190 )
1191 );
1192 }
1193 }
1194 $self->command( join ' ', $prog, @args, @tail );
1195 }
1196  
1197 =head2 set_perl_cmd
1198  
1199 Wrapper around set_gnu_cmd that prefixes the Perl interpreter.
1200  
1201 =cut
1202  
1203 sub set_perl_cmd {
1204 my $self = shift;
1205 my $script = shift;
1206 $self->set_gnu_cmd( "perl $script", @_ );
1207 }
1208  
1209 =head2 set_python_cmd
1210  
1211 Wrapper around set_argparse_cmd that prefixes the Python interpreter.
1212  
1213 =cut
1214  
1215 sub set_python_cmd {
1216 my $self = shift;
1217 my $script = shift;
1218 $self->set_argparse_cmd( "python $script", @_ );
1219 }
1220  
1221 =head2 set_r_cmd
1222  
1223 Wrapper around set_argparse_cmd that prefixes the R interpreter.
1224  
1225 =cut
1226  
1227 sub set_r_cmd {
1228 my $self = shift;
1229 my $script = shift;
1230 $self->set_argparse_cmd( "Rscript $script", @_ );
1231 }
1232  
1233 =head1 AUTHOR
1234  
1235 Christopher Lalansingh - Boutros Lab
1236  
1237 Andre Masella - Boutros Lab
1238  
1239 John Macdonald - Boutros Lab
1240  
1241 =head1 ACKNOWLEDGEMENTS
1242  
1243 Paul Boutros, Phd, PI - Boutros Lab
1244  
1245 The Ontario Institute for Cancer Research
1246  
1247 =cut
1248  
1249 1;