blib/lib/HPCI/Stage.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« blib/lib/HPCI/File.pm ↑ Summary blib/lib/HPCD/uni/Group.pm »
1 package HPCI::Stage;
2  
3 ### INCLUDES ##################################################################
4  
5 # safe Perl
6 20 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 20 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 20 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 20 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 20 ▶use HPCI::File;
Subroutine BEGIN: called CC=1 SCAR=2.6
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 =head2 cluster (internally provided)
109  
110 The type of cluster that will be used to execute the group
111 of stages. This value is passed on by the $group->stage
112 method when it creates a new stage. Since it also uses that
113 value to select the type of stage object that is created,
114 it is somewhat redundant.
115  
116 =cut
117  
118 sub _build_valid_resources {
119 my $self = shift;
120 return {
121 $self->can('_build_cluster_specific_valid_resources')
122 ? $self->_build_cluster_specific_valid_resources
123 : ()
124 };
125 }
126  
127 class_has '_valid_resources' => (
128 is => 'ro',
129 isa => 'HashRef',
130 lazy => 1,
131 builder => '_build_valid_resources',
132 );
133  
134 sub _build_default_resources {
135 my $self = shift;
136 my $res = {
137 $self->can('_build_cluster_specific_default_resources')
138 ? $self->_build_cluster_specific_default_resources
139 : ( )
140 };
141 $res->{_default_subs_}{h_time} = '_default_h_time';
142 $res->{_default_subs_}{s_time} = '_default_s_time';
143  
144 return $res;
145 }
146  
147 class_has '_default_resources' => (
148 is => 'ro',
149 isa => 'HashRef',
150 lazy => 1,
151 builder => '_build_default_resources',
152 );
153  
154 sub _default_h_time {
155 my $self = shift;
156 my $vals = shift;
157 my $soft = $vals->{s_time};
158 return unless defined $soft;
159 # if soft time was provided, but no hard time, give an hour extra for hard
160 return $self->_secs_to_time( $self->_time_to_secs($soft) + 60*60 );
161 }
162  
163 sub _secs_to_time {
164 my $self = shift;
165 my $base = my $origbase = shift;
166 my $res = '';
167 return '0' unless $base;
168 my @units = ( [ 60, '' ], [ 60, 'm' ], [ 24, 'h' ], [ 99, 'd' ], );
169 for my $unitpair (@units) {
170 my ( $size, $name ) = @$unitpair;
171 return "$base$name$res" if $base < $size;
172 my $rem = $base % $size;
173 $base = int( $base / $size );
174 $res = "$rem$name$res";
175 }
176 $self->_croak("Run time of more than 100 days seems insane ($origbase)");
177 }
178  
179 sub _time_to_secs {
180 my $self = shift;
181 my $time = shift;
182 my $res = 0;
183 my %name2secs = (
184 d => 24 * 60 * 60,
185 h => 60 * 60,
186 m => 60,
187 s => 1,
188 );
189 while ($time =~ m/\G\s*(\d+)\s*(\w?)/g) {
190 my ($num, $let) = ($1, $2);
191 my $mult = 1;
192 if ($let) {
193 $mult = $name2secs{ lc($let) }
194 // $self->_croak("Unknown code ($let) in time string ($time)");
195 }
196 $res += $num * $mult;
197 }
198 return $res;
199 }
200  
201 sub _default_s_time {
202 my $self = shift;
203 my $vals = shift;
204 # return $vals->{h_time}; # same as h_time or undef if no h_time provided
205 return undef;
206 }
207  
208 sub _build_default_retry_resources {
209 my $self = shift;
210 return $self->can("_build_cluster_specific_default_retry_resources")
211 ? { $self->_build_cluster_specific_default_retry_resources }
212 : { };
213 }
214  
215 class_has '_default_retry_resources' => (
216 is => 'ro',
217 isa => 'HashRef',
218 lazy => 1,
219 builder => '_build_default_retry_resources',
220 );
221  
222 has 'cluster' => (
223 is => 'ro',
224 isa => 'Str',
225 );
226  
227 =head2 name
228  
229 The name of this stage within the group. The name must be unique
230 within the group, most group interactions use the name rather than
231 a reference to the stage object to refer to the stage.
232  
233 =cut
234  
235 has 'name' => (
236 is => 'ro',
237 isa => 'Str',
238 required => 1,
239 );
240  
241 =head2 command
242  
243 The command to be executed on the cluster. This command will quite
244 possibly be wrapped in a cluster-specific manner to pass the command
245 and environment info to the target cluster node.
246  
247 The command can either be provided as an explicit parameter when
248 the stage is created, or by using one of the B<set_*_cmd> methods
249 described below after the stage object is created.
250  
251 This is the only time that you need the stage object itself rather
252 than just referring to it by its name. However, even here, unless
253 you need to separate the creation of the stage object from the
254 point where you specify the command you can do something like:
255  
256 my $group = HPCI->group( ...);
257  
258 ...
259  
260 $group->stage( name => 'thisstage', ... )
261 ->set_perl_cmd(
262 $program,
263 f => undef, # a flag argument: -f
264 flag => undef, # another flag argument: --flag
265 v => $value, # a value argument: -v $value
266 val => $value, # another value argument: --val $value
267 l => [ qw(a b c}] # a list argment: -l a -l b -l c
268 list => [ qw(a b c}] # another list argment: --list a --list b --list c
269 '--' => [ f1 f2 ] # non-keyed argument(s): f1 f2
270 );
271 # set the command to: perl $program -f --flag -v $value --val $value \
272 # -l a -l b -l c --list a --list b --list c f1 f2
273  
274 As an alternative to the command attribute, you can specify the code
275 attribute described below.
276 It is required that one of these be provided before the group tries to
277 execute this stage.-, and only one of them can be provided (no9t both)
278  
279 =cut
280  
281 has 'command' => (
282 is => 'rw',
283 isa => 'Str',
284 predicate => '_has_command',
285 trigger => sub { shift->_only_one( '_has_code' ) },
286 );
287  
288 =head2 code
289  
290 The code attribute is an alternate to the command attribute described
291 above. Its value is a code reference, which will be called directly
292 to carry out the activity of the Stage. You can use this for a stage
293 activity that is simple enough to code as a perl routine that it does
294 not make sense to go through the overhead of creating a new job on a
295 cluster node to do this activity. You may not specify B<both> B<code>
296 and B<command> for the same stage; but you must specify one of them
297 before the stage is ready to execute.
298  
299 The code in the reference is called with no arguments when the stage
300 is ready to be executed. The return value is treated as a boolean to
301 indicate whether the stage succeeded: a false value for success, or a
302 true value for failure (with the value usually being a text message
303 describing the cause of the failure). This mimics the exit_status
304 that is returned from a separately executed program (except for being
305 able to provide a more easily understood failure code than a simple
306 integer) - however, it does mean that some common purposes for this
307 attribute will need some wrapping code. For example, any B<code> that
308 is just providing a system call (e.g. unlink, link, rename) will need to
309 invert the boolean result, and expand the failure result to provide the
310 errno value, such as:
311  
312 stage(
313 ...
314 code => sub {
315 unlink $tmpfile ? 0 : $!
316 },
317 ...
318 )
319  
320 =cut
321  
322 has 'code' => (
323 is => 'ro',
324 isa => 'CodeRef',
325 predicate => '_has_code',
326 trigger => sub { shift->_only_one( '_has_command' ) },
327 );
328  
329 sub _only_one {
330 my $self = shift;
331 my $has_other = shift;
332 $self->_croak( "Exactly one of 'code' or 'command' attributes must be specified, not both" )
333 if $self->$has_other;
334 }
335  
336 sub assert_command_filled {
337 my $self = shift;
338 $self->_croak(
339 "Trying to submit stage ("
340 . $self->name
341 . "), but neither command nor code have been set"
342 )
343 unless $self->_has_command || $self->_has_code;
344 }
345  
346 has 'stage_dir_name' => (
347 is => 'ro',
348 isa => 'Str',
349 lazy => 1,
350 default => sub {
351 my $self = shift;
352 return $self->name;
353 },
354 );
355  
356 has 'stage_dir' => (
357 is => 'ro',
358 isa => Dir,
359 coerce => 1,
360 lazy => 1,
361 default => sub {
362 my $self = shift;
363 my $target;
364 if ($self->_has_dir) {
365 $target = $self->dir;
366 }
367 else {
368 $target = $self->group->group_dir->subdir( $self->stage_dir_name );
369 }
370 HPCI::_trigger_mkdir($self,$target);
371 return $target;
372 },
373 trigger => \&HPCI::_trigger_mkdir,
374 );
375  
376 has 'dir' => (
377 is => 'ro',
378 isa => Dir,
379 coerce => 1,
380 predicate => '_has_dir'
381 );
382  
383 =head2 resources_required
384  
385 A hash that maps resource names to the amount of that resource
386 that is needed.
387  
388 TODO: Describe the generic resource names, the value types that can
389 be used, and the non-default cluster-specific names that can be
390 used instead.
391  
392 =cut
393  
394 has 'resources_required' => (
395 is => 'ro',
396 isa => 'HashRef[Str]',
397 default => sub { return {} },
398 );
399  
400 has '_use_resources_required' => (
401 is => 'ro',
402 isa => 'HashRef[Str]',
403 lazy => 1,
404 builder => '_init_use_resources_required',
405 );
406  
407 sub _init_use_resources_required {
408 my $self = shift;
409 $self->res_hash_map( $self->resources_required,
410 $self->_default_resources,
411 );
412 }
413  
414 =head2 retry_resources_required
415  
416 A hash that maps resource names to a list of amounts of that resource
417 that might be required.
418  
419 If the cluster-specific interface detects that a runs fails because
420 not enough of a particular resource was requested, then the next
421 larger amount in the retry_resources_required list for that resource
422 type is used and the stage is retried.
423  
424 At present, this is only used for SGE clusters, and only for the
425 B<mem> (or SGE-specific B<h_vmem>) resource. SGE provides a
426 default value of:
427  
428 retry_resources_required => { h_vmem => [qw(2G 4G 8G 16G 32G)] }
429  
430 When you are first running a job and don't know how much memory
431 it will require, you can specify a low value. When it completes,
432 you can check the log to see how much memory it ended up needing,
433 and use that as the starting parameter for future runs. That initial
434 run will have possible had to run part way through, fail, and then
435 retry a number of times. The alternative of providing a large
436 memory allocation the first time takes resources from your cluster
437 (and especially if you never get around to changing the initial
438 setting - people are more likely to remember to make such a change
439 when it will save them time by avoiding retries than when it just
440 happens to reserve more space than is actually used).
441  
442 =cut
443  
444 has 'retry_resources_required' => (
445 is => 'ro',
446 isa => 'HashRef[ArrayRef[Str]]',
447 default => sub { return {} },
448 );
449  
450 has '_use_retry_resources_required' => (
451 is => 'ro',
452 isa => 'HashRef[ArrayRef[Str]]',
453 lazy => 1,
454 default => sub {
455 my $self = shift;
456 $self->res_hash_map( $self->retry_resources_required,
457 $self->_default_retry_resources,
458 );
459 # need to provide converter support here
460 # e.g. turn a time from '2d3h' to (2*24+3)*60*60 (seconds)
461 },
462 );
463  
464 sub res_hash_map {
465 my $self = shift;
466 my $provided = shift;
467 my $default = shift;
468 my $determined = {};
469 my $map = $self->_valid_resources;
470 for my $cluster_res (keys %$map) {
471 my $common_res = $map->{$cluster_res} || $cluster_res;
472 if (my $use_res = $provided->{$cluster_res}
473 // $provided->{$common_res}
474 // $default->{$cluster_res}
475 // $default->{$common_res})
476 {
477 $determined->{$cluster_res} = $use_res;
478 }
479 }
480 my $initters = $default->{_default_subs_} // {};
481 for my $key (keys %$initters) {
482 unless (defined $determined->{$key}) {
483 my $func = $initters->{$key};
484 my $res = $self->$func($determined);
485 $determined->{$key} = $res if defined $res;
486 }
487 }
488 return $determined;
489 }
490  
491 =head2 native_args_string
492  
493 The native program mechanism used by the driver to submit a stage
494 for execution can have many arguments. Some of those will be provided
495 automatically from the generic HPCI attributes, but there may be extra
496 capabilities that do not match the standard HPCI definition.
497  
498 Using these extra capabilities can lead to non-portable programs, unless
499 you are careful. HPCI provides two ways to be careful but also
500 allows you to be careless.
501  
502 If you (carelessly) provide this attribute directly, then it will be used
503 for any type of cluster that your program is run on - using such
504 cluster-specific parameters can have dangerous or obscure effects when
505 applied to a different cluster type.
506  
507 You can be careful, by providing this attribute only within an
508 attribute set included in the cluster_specific attribute.
509 The alternate way to be careful is to provide this attribute indirectly,
510 using the cluster-specific name which the driver specifies as the
511 native_args_string_name attribute.
512  
513 The value provided to native_args_string will be passed to the native
514 submissions mechanism when-ever that makes sense. A driver that uses a
515 submission mechanism that does not provide for any non-standard HPCI
516 capabilities may choose to ignore this attribute.
517  
518 So, for example, if you wished to provide extra args for the qsub command
519 when running on an SGE cluster you could code that as either:
520  
521 $group->stage(
522 name => 'stage_name',
523 ...
524 cluster_specific => {
525 SGE => { native_args_string => '-q myqueue -m beas' },
526 ... # put args strings for other cluster types here
527 },
528 ...
529 );
530  
531 or as:
532  
533 $group->stage(
534 name => 'stage_name',
535 ...
536 extra_sge_args_string => '-q myqueue -m beas',
537 ... # put args strings for other cluster types here
538 # using the appropriate cluster-specific attribute name
539 ...
540 );
541  
542 =head2 native_args_string_name
543  
544 This attribute is one way in which a driver can help you to use native
545 arguments in a portable way. Drivers that actually use the native_args_string
546 attribute will specify a value for this attribute internally - it is never
547 provided directly as a Stage attribute. If this attribute is provided by the
548 driver, then only the value of the attribute it names will be used for the
549 source text of native_args_string.
550  
551 =head2 _native_args_string_parsing_info
552  
553 This internal attribute is provided by the driver. It specifies how the
554 native_args_string is parsed, controlling how it is separated into
555 parameters and values, which parameters are normally provided by altenate
556 HPCI mechanisms, how the parameters and values are displayed in the log
557 (if it is different from how they are inserted into the command line for
558 execution), etc.
559  
560 Only people writing drivers need to worry about this attribute.
561  
562 =head2 native_args* support not implemented yet
563  
564 The attributes related to native_args_string processing are not yet ready for
565 use; they are being implemented by copying and generalizing the code from the
566 SGE and Slurm drivers, that is still in progress.
567  
568 =cut
569  
570 has 'native_args_string' => (
571 is => 'ro',
572 isa => 'Str',
573 default => ''
574 );
575  
576 has 'native_args_string_name' => (
577 is => 'ro',
578 isa => 'Maybe[Str]',
579 init_arg => undef,
580 default => undef # driver can over-ride this setting
581 );
582  
583 has 'native_args_string_parsing_info' => (
584 is => 'ro',
585 isa => 'HashRef',
586 init_arg => undef,
587 builder => 'default_args_string_parsing_info'
588 );
589  
590 # driver can over-ride this method to provide a non-empty list
591 # of parsing info
592 sub default_args_string_parsing_info {
593 return {}
594 }
595  
596  
597 =head2 group
598  
599 The group that this stage belongs to is automatically provided to
600 the stage creation. You don't need to initialize it, and since
601 you usually will not be working with Stage objects directly, you
602 won't have much need to use it either.
603  
604 =cut
605  
606 has 'group' => (
607 is => 'ro',
608 isa => 'Object',
609 weak_ref => 1,
610 required => 1,
611 handles => {
612 debug => 'debug',
613 info => 'info',
614 warn => 'warn',
615 error => 'error',
616 fatal => 'fatal',
617  
618 file_params => 'file_params',
619 _file_info => '_file_info',
620 },
621 );
622  
623 sub _croak {
624 my $self = shift;
625 my $msg = shift;
626 $msg = "Stage(" . $self->name . "): $msg";
627 $self->fatal($msg);
628 confess $msg;
629 }
630  
631 =head2 storage_class (internal)
632  
633 The name of key to use to select a storage class from the storage_classes
634 attribute for files that do no have an explicit class given.
635  
636 Defaults to the value of the group's C<storage_class> attribute, (which
637 defaults to C<'default'>) - this value is provided automatically by the
638 group's stage method if no explicit storage_class value is provided for
639 the stage.
640  
641 =cut
642  
643 has 'storage_class' => (
644 is => 'ro',
645 isa => 'HPCIFileGen',
646 lazy => 1,
647 default => sub {
648 $_[0]->group->storage_class
649 },
650 required => 1,
651 );
652  
653 # has 'storage_classes' => (
654 # is => 'ro',
655 # isa => 'HPCIListList',
656 # lazy => 1,
657 # default => sub { $_[0]->group->storage_classes },
658 # init_arg => undef,
659 # );
660  
661 =head2 files
662  
663 A hash that can contain lists of files.
664  
665 Throughout this hash, there are filenames contained within hash elements
666 that describe the processing required for that file. Whenever a filename
667 is needed, it can either be a string containing a pathname, or it can be
668 an HPCI::File object (or subclass), or ot can be a HashRef. Often, it
669 will be the string form, which will be converted to an object internally.
670  
671 The top level of the hash has keys 'in' (for input), 'out' (for output),
672 'skipstage', 'rename', and 'delete'.
673 (The same file might be listed under multiple keys.)
674  
675 The values for these keys are:
676  
677 =over 4
678  
679 =item 'in'
680  
681 a hashref with possible keys:
682  
683 'req' (for required input files)
684 'opt' (for required output files)
685  
686 The value for either of these can be either a filename or a list of filenames.
687  
688 =item 'out'
689  
690 a hashref with possible keys:
691  
692 'req' (for required output files)
693 'opt' (for required output files)
694  
695 The value for either of these can be either a filename or a list of filenames.
696  
697 =item 'skipstage'
698  
699 either:
700  
701 =over 4
702  
703 =item
704  
705 an arrayref
706  
707 =item
708  
709 a hashref with the keys 'pre' (for pre-requisites) and 'lists'
710  
711 =back
712  
713 The arrayref (either the arrayref value of 'skipstage' or the arrayref value
714 for the 'lists' hash element) can contain either a list of files, or a hashref
715 with keys 'pre' and 'files'.
716  
717 The 'pre' value (if present) at the top level is a list of files which are
718 pre-requisites for all of the lists. If a list has its own 'pre' list, those
719 files are only pre-requities for the files in that list.
720  
721 =item 'rename'
722  
723 a list of pairs of filenames
724  
725 The file named as the first element in each pair (if it exists) is renamed to
726 the second filename in the pair. It is not considered an error for the first
727 file in a pair does not exist - if you want to ensure that a file exists,
728 include it as an 'out'->'req' file as well.
729  
730 =item 'delete'
731  
732 can be either:
733  
734 a scalar filename
735 a list of filenames
736  
737 These will be removed if the stage completes successfully. It is not
738 considered an error if any of these files does not exist - include them
739 in the 'out'->'req' files list if you wish to ensure that they do.
740  
741 =back
742  
743 The contents are used at various times:
744  
745 =over 4
746  
747 =item the stage is ready to be executed
748  
749 =over
750  
751 =item
752  
753 if a 'skipstage' key is present then checking is done to decide whether the
754 stage needs to be executed or can be skipped (treating it as a successful
755 completion)
756  
757 the main content of this key is a list of lists of filenames (the target
758 files) - if any of these lists has all of its files existing, then the stage
759 can be skipped
760  
761 if there is a top level and/or a list level 'pre' list, then all of the files
762 in the pre list(s) must also exist and be older than the target files (the
763 files in the top level 'pre' list are checked against all of the target lists,
764 the files in a target level 'pre' list are only checked against that target).
765  
766 C<skipstage> checking is always done by the parent process, in hopes of
767 avoiding the need to create the stage.
768  
769 =item
770  
771 all 'in'->'req' files must exist, if any is missing, the stage is aborted.
772 If the files exist, then the child stage will be set up (if needed) to
773 download those files from the long-term storage.
774  
775 =item
776  
777 all 'in'->'opt' are checked by the parent. If any exists, then the child stage
778 will be set up (if needed) to download them from the long-term storage.
779  
780 =back
781  
782 =item the stage has completed execution
783  
784 =over
785  
786 =item
787  
788 all 'out'->'req' files must exists and they must have been updated during the
789 execution of the stage (otherwise the stage is treated as failing)
790  
791 =item
792  
793 any 'out'->'opt' files which exist must have been updated during the execution
794 of the stage (otherwise the stage is treated as failing)
795  
796 =item
797  
798 clusters that require special treatment of files can take copying actions to
799 collect any 'out' files that have been updated
800  
801 =item
802  
803 if the stage completed successfully, any files lists as 'delete' are removed
804  
805 =back
806  
807 =back
808  
809 =cut
810  
811 has 'files' => (
812 is => 'ro',
813 isa => 'Maybe[HashRef]',
814 default => undef,
815 );
816  
817 has '_use_files' => (
818 is => 'ro',
819 isa => 'Maybe[HashRef]',
820 lazy => 1,
821 init_arg => undef,
822 builder => '_use_files_builder',
823 );
824  
825 sub _use_files_builder {
826 my $self = shift;
827 my $file = $self->files // return undef;
828 my $use_files = {};
829 SIMPLE_FILES:
830 for my $keys ( [qw(in req)],
831 [qw(in opt)],
832 [qw(out req)],
833 [qw(out opt)],
834 ['delete']
835 ) {
836 my $source = $file;
837 $source = $source->{$_} or next SIMPLE_FILES for @$keys;
838 my $prev_dest;
839 my $dest = $use_files;
840 for my $key (@$keys) {
841 $prev_dest = $dest;
842 $dest = $dest->{$key} //= {};
843 }
844 $prev_dest->{$keys->[-1]} = $self->_get_file_list($source);
845 }
846 if ( my $skipinfo = $file->{skipstage} ) {
847 $use_files->{skipstage} = {};
848 if (ref($skipinfo) eq 'HASH') {
849 $self->_croak('skipstage hash element must be have keys "pre" and "lists"')
850 unless exists $skipinfo->{pre} && exists $skipinfo->{lists};
851 $use_files->{skipstage}{pre} = $self->_get_file_list( $skipinfo->{pre} );
852 $skipinfo = $skipinfo->{lists};
853 $self->_croak('skipstage->{lists} element must be an array')
854 unless ref($skipinfo) eq 'ARRAY';
855 }
856 else {
857 $self->_croak('skipstage files element must be either a hash or an array')
858 unless ref($skipinfo) eq 'ARRAY';
859 $use_files->{skipstage}{pre} = [];
860 }
861 my $dest_list = $use_files->{skipstage}{lists} = [ ];
862 for my $l (@$skipinfo) {
863 my $dest_hash = { };
864 $self->_croak('skipstage list element must be either a hash or an array')
865 unless ref($l) eq 'ARRAY' || ref($l) eq 'HASH';
866 if (ref($l) eq 'HASH') {
867 $dest_hash->{pre} = $self->_get_file_list( $l->{pre} );
868 $l = $l->{post};
869 $self->_croak('skipstage post element must be an array')
870 unless ref($l) eq 'ARRAY';
871 }
872 else {
873 $dest_hash->{pre} = [];
874 }
875 $dest_hash->{post} = $self->_get_file_list( $l );
876 push @$dest_list, $dest_hash;
877 }
878 }
879 if ( my $renamelist = $file->{rename} ) {
880 $self->_croak('rename files element an array')
881 unless ref($renamelist) eq 'ARRAY';
882 my $use_pairs = $use_files->{rename} = [];
883 for my $pair (@$renamelist) {
884 $self->_croak('rename files array element must be an array with two values')
885 unless ref($pair) eq 'ARRAY' && scalar(@$pair) == 2;
886 my ($from, $to) = @$pair;
887 push @$use_pairs, [ $self->_get_file_obj($from), $to ];
888 }
889 }
890 return $use_files;
891 };
892  
893 sub _get_file_list {
894 my $self = shift;
895 my $source = shift;
896 $source = [ $source ] unless ref($source);
897 $source = [ $source ] if blessed $source && $source->isa("HPCI::File");
898 my $ref = ref($source);
899 $self->_croak( "Element in files attribute is not an array, a pathname or HPCI::File class. Type is $ref, value is $source")
900 unless $ref eq 'ARRAY';
901 return [ map { $self->_get_file_obj($_) } @$source ];
902 }
903  
904 sub _get_file_obj {
905 my $self = shift;
906 my $file = shift;
907 return $self->_generate_file( ref($file) eq 'ARRAY' ? @$file : $file );
908 }
909  
910 sub _generate_file {
911 my $self = shift;
912 my $file = shift;
913 if (blessed $file && $file->isa("HPCI::File")) {
914 return $file;
915 }
916 my $path = File::Spec->rel2abs("$file");
917 # TODO: add search through storage_classes list here
918 my $known = $self->_file_info->{$path} //= {};
919 return $known->{file} //= $self->storage_class->(
920 $path,
921 stage => $self,
922 %{ $known->{params} // {} },
923 @_
924 );
925 }
926  
927 =head2 state, is_ready, is_blocked, is_pass, is_fail
928  
929 These states are mostly for internal use during execution. (There
930 are actually more states than are listed here but they are only
931 meaningful during execution when the calling program doesn't have
932 access to the state, and they are subject to change without notice.)
933  
934 However, before execute is called, a stage can be either B<ready>
935 or B<blocked> (depending upon whether any other stage has been
936 noted as a pre-requisite).
937  
938 After execution completes, a stage will be in either B<pass> or B<fail> state
939 (and the B<is_complete> attribute will always be true). This is probably
940 the only significant setting to check from user code.
941  
942 The state attribute is a string value, but it can be tested using
943 the is_STATE methods, each of which returns true if the stage is
944 in the specified state.
945  
946 =cut
947  
948 enum 'StageState', [qw(ready blocked running retry pass fail)];
949  
950 has 'state' => (
951 is => 'ro',
952 isa => 'StageState',
953 writer => '_set_state',
954 default => 'ready',
955 init_arg => undef,
956 );
957  
958 sub is_ready {
959 my $self = shift;
960 return $self->state eq 'ready';
961 }
962  
963 sub is_blocked {
964 my $self = shift;
965 return $self->state eq 'blocked';
966 }
967  
968 sub is_running {
969 my $self = shift;
970 return $self->state eq 'running';
971 }
972  
973 sub is_retry {
974 my $self = shift;
975 return $self->state eq 'retry';
976 }
977  
978 sub is_pass {
979 my $self = shift;
980 return $self->state eq 'pass';
981 }
982  
983 sub is_fail {
984 my $self = shift;
985 return $self->state eq 'fail';
986 }
987  
988 sub is_complete {
989 my $self = shift;
990 return $self->is_pass || $self->is_fail;
991 }
992  
993 =head2 verify_completion_state
994  
995 If the user wishes to verify whether a stage completed successfully,
996 failed, or should be retried, this attribute can be given a coderef
997 to code that checks the result.
998  
999 The code will be called with the arguments:
1000  
1001 $coderef->( $stats, $stdout, $stderr, $state )
1002 $stats is a hashref containing the accounting info and status of the job
1003 $stdout is the pathname of the stdout file
1004 $stderr is the pathname of the stderr file
1005 $state is the state determined by HPCI
1006 (only pass/fail - retry has not been decided yet)
1007  
1008 The code can use these (and knowledge provided by the user about the stage
1009 operation) to test whether the stage succeeded.
1010  
1011 To select a specific state, the return value from the code should be a string, one of:
1012  
1013 pass
1014 fail
1015 retry
1016  
1017 If your function does not wish to select a state, it can return undef, and the
1018 same state that would be been chosen without the call to this function will be
1019 used unchanged.
1020  
1021 If the value returned is 'fail', other standard HPCI mechanisms may still apply
1022 that might change the choice to 'retry'.
1023  
1024 If the value returned is 'retry', it will either retry the stage or be
1025 changed to fail state, depending upon whether the limit for the choose_retries
1026 attribute has been reached.
1027  
1028 This code attribute could be used for:
1029  
1030 - running a program that always gives an error status, but you might wish to
1031 treat it as successful
1032  
1033 - running a program that can give a zero status but not actually succeed (but
1034 perhaps a retry will succeed)
1035  
1036 An example might look like:
1037  
1038 $group->stage(
1039 ....
1040 verify_completion_status => sub {
1041 my( $stats, $stdout, $stderr, $state ) = @_;
1042 # retry if output file is zero length
1043 return 'retry' if $state eq 'pass' && ! -s $my_output_file;
1044 # otherwise, normal processing
1045 return;
1046 },
1047 ...
1048 );
1049  
1050 =cut
1051  
1052 has 'verify_completion_state' => (
1053 is => 'ro',
1054 isa => 'CodeRef',
1055 predicate => '_has_verify_completion_state',
1056 );
1057  
1058 after '_analyse_completion_state' => sub {
1059 my $self = shift;
1060 my $run = shift;
1061  
1062 if ($self->is_pass && (my $files = $self->_use_files) ) {
1063 my $script_time = $self->_file_timestamp_for_out( $self->script_file );
1064 if ( my $outfiles = $files->{out}) {
1065 my $fs_delay = $self->group->file_system_delay;
1066 FILE:
1067 while ( my ($type, $fileval) = each %$outfiles ) {
1068 for my $file ( @$fileval ) {
1069 while ($fs_delay && ! $file->exists_out_file) {
1070 my $sleep_time = ($fs_delay > 5) ? 5 : $fs_delay;
1071 $fs_delay -= $sleep_time;
1072 sleep $sleep_time;
1073 }
1074 my $timestamp;
1075 if ($file->exists_out_file) {
1076 if ( ($timestamp = $file->timestamp)
1077 <= $script_time) {
1078 $file->accepted_for_out;
1079 next FILE;
1080 }
1081 }
1082 else {
1083 next FILE if $type eq 'opt';
1084 }
1085 # a req file was not found
1086 $self->_set_state('fail');
1087 $run->stats->{failure_detected} = "required output file ($file) not updated";
1088 $self->error(
1089 "Stage (",
1090 $self->name,
1091 ") status changed to failed because required output file ",
1092 $file,
1093 " was not updated"
1094 );
1095 if ($timestamp) {
1096 $self->error(
1097 "mod time: (",
1098 $timestamp,
1099 ") for file($file) should be more recent (less) than script time (",
1100 $script_time,
1101 ")"
1102 );
1103 # my $script_file = $self->script_file;
1104 # $self->error(
1105 # "ls:\n",
1106 # `ls --full-time $script_file $file`
1107 # );
1108 # $self->error(
1109 # "-M:\n\t\t",
1110 # -M "$script_file", "\t$script_file", "\n\t\t",
1111 # -M "$file","\t$file",
1112 # );
1113 }
1114 else {
1115 $self->error( "file ($file) does not exist" );
1116 }
1117 }
1118 }
1119 }
1120 }
1121 if ($self->_has_verify_completion_state) {
1122 my $code = $self->verify_completion_state->(
1123 $run->stats,
1124 $run->_stdout,
1125 $run->_stderr,
1126 $self->state
1127 );
1128 if ($code eq 'retry') {
1129 $code = 'fail';
1130 $run->_analysis_chose_retry(1);
1131 }
1132 $self->_set_state( $code ) if $code eq 'pass' || $code eq 'fail';
1133 }
1134 };
1135  
1136 sub lof {
1137 my $lof = shift;
1138 my $res = '[';
1139 $res .= " $_" for @$lof;
1140 $res .= ' ]';
1141 return $res;
1142 }
1143  
1144 # check whether criteria are satisfied to skip executing the stage
1145 sub _can_be_skipped {
1146 my $self = shift;
1147 my $skipinfo = $self->_use_files // return 0;
1148 $skipinfo = $skipinfo->{skipstage} // return 0;
1149 my $pre = $skipinfo->{pre};;
1150 my $lol = $skipinfo->{lists};
1151 LIST:
1152 for my $l (@$lol) {
1153 my $thispre = [@$pre, @{$l->{pre}}];
1154 $l = $l->{post};
1155 $self->debug( "Considering skipstage, pre: ", lof($thispre), ", list: ", lof( $l ) );
1156 unless (@$l) { # an empty list does not qualify for skipping
1157 $self->debug( "no skip: empty list element" );
1158 next LIST;
1159 }
1160 my $newest_pre;
1161 for my $f (@$thispre) {
1162 # if there is a pre list
1163 # check that they all exist and
1164 # get latest pre timestamp
1165 my $ts = $f->timestamp;
1166 unless (defined $ts) {
1167 $self->debug( "no skip: missing pre element: $f" );
1168 next LIST;
1169 }
1170 $newest_pre ||= $ts;
1171 $newest_pre = $ts if $ts < $newest_pre;
1172 }
1173 if ($self->_file_list_acceptable_for_skip( $newest_pre, $l )) {
1174 $self->debug( "skipping: file list acceptable" );
1175 return 1;
1176 }
1177 $self->debug( "no skip: file list not acceptable" );
1178 }
1179 return 0;
1180 }
1181  
1182 sub _files_ready_to_start_stage {
1183 my $self = shift;
1184 return 1 unless my $files = $self->_use_files;
1185 my $retval = 1; # success unless missing file(s) found
1186 if (my $in = $files->{in}) {
1187 while ( my ($type, $fileval) = each %$in ) {
1188 for my $file (@$fileval) {
1189 unless ($file->valid_in_file || $type ne 'req') {
1190 # need to check exist on opt files in case
1191 # the driver needs to take special action to
1192 # make it available to the stage when it runs
1193 #
1194 # go through the entire list of files to give user
1195 # a full list of missing files rather than just the
1196 # first one we notice - let them fix everything for
1197 # the next run instead of needing separate extra
1198 # funs to be notified of each successive issue
1199 $self->error("Required input file ($file) not present");
1200 $self->_set_failure_info(
1201 "Failed stage ("
1202 . $self->name
1203 . ") without execution because one or more required input files were not present"
1204 );
1205 $retval = 0;
1206 }
1207 }
1208 }
1209 }
1210 if ($retval and my $unshared = $files->{unshared}) {
1211 # our @HPCI::ScriptSource::pre_commands;
1212 # our @HPCI::ScriptSource::post_success_commands;
1213 if (my $in = $unshared->{in}) {
1214 while ( my ($type, $fileval) = each %$in ) {
1215 for my $file (@$fileval) {
1216 my $exists = $self->_unshared_file_exists_for_in($file);
1217 my $get = $self->_unshared_file_download_for_in($file);
1218 push @HPCI::ScriptSource::pre_commands, "if $exists\n";
1219 push @HPCI::ScriptSource::pre_commands, "then\n";
1220 push @HPCI::ScriptSource::pre_commands, " $get\n";
1221 if ($type eq 'req') {
1222 push @HPCI::ScriptSource::pre_commands, "else\n";
1223 push @HPCI::ScriptSource::pre_commands, " echo required in file not present: $file 1>&2\n";
1224 push @HPCI::ScriptSource::pre_commands, " exit 126\n";
1225 }
1226 push @HPCI::ScriptSource::pre_commands, "fi\n";
1227 }
1228 }
1229 }
1230 if (my $out = $unshared->{out}) {
1231 while ( my ($type, $fileval) = each %$out ) {
1232 # for my $file ($self->_scalar_list($fileval)) {
1233 for my $file (@$fileval) {
1234 my $exists = $self->_unshared_file_exists_for_out($file);
1235 my $put = $self->_unshared_file_upload_for_out($file);
1236 push @HPCI::ScriptSource::post_success_commands, "if $exists\n";
1237 push @HPCI::ScriptSource::post_success_commands, "then\n";
1238 push @HPCI::ScriptSource::post_success_commands, " $put\n";
1239 if ($type eq 'req') {
1240 push @HPCI::ScriptSource::post_success_commands, "else\n";
1241 push @HPCI::ScriptSource::post_success_commands, " echo required out file not present: $file 1>&2\n";
1242 push @HPCI::ScriptSource::post_success_commands, " exit 126\n";
1243 }
1244 push @HPCI::ScriptSource::post_success_commands, "fi\n";
1245 }
1246 }
1247 }
1248 }
1249 return $retval;
1250 }
1251  
1252 # sub _files_acceptable_for_completed_stage {
1253 # my $self = shift;
1254 # my $run = shift;
1255 # return 1 unless $self->_use_files;
1256 # my $out = $self->files->{out} or return 1;
1257 # my $retval = 1; # success unless non-updated file found
1258 # my $before = $self->_file_timestamp_for_out( $run->dir );
1259 # while ( my ($type, $fileval) = each %$out ) {
1260 # for my $file ($self->_scalar_list($fileval)) {
1261 # # need to check exist on opt files in case
1262 # # the driver needs to take special action to
1263 # # collect the result from the completed stage
1264 # #
1265 # # go through the entire list of files to give user
1266 # # a full list of invalid files rather than just the
1267 # # first one we notice - let them fix everything for
1268 # # the next run instead of needing separate extra
1269 # # runs to be notified of each successive issue
1270 # my $error_text;
1271 # if ( ! $self->_file_exists_for_out($file)
1272 # && $type eq 'req') {
1273 # ++$error_text;
1274 # $self->error( "Required output file ($file) is not present" );
1275 # }
1276 # elsif ($self->_file_timestamp_for_out($file) < $before) {
1277 # # file was not updated
1278 # my $msg = "output file ($file) was not changed";
1279 # if ($type eq 'req') {
1280 # ++$error_text;
1281 # $self->error( "Required $msg" );
1282 # }
1283 # else {
1284 # $self->warn( "Optional $msg" );
1285 # }
1286 # }
1287 # if ($error_text) {
1288 # $self->_set_failure_info(
1289 # "Failed stage (",
1290 # $self->name,
1291 # ") after 'successful' execution because one or more required output files were not updated"
1292 # );
1293 # $retval = 0;
1294 # }
1295 # }
1296 # }
1297 # return $retval;
1298 # }
1299  
1300 sub _files_actions_after_success {
1301 my $self = shift;
1302 my $run = shift;
1303 return 1 unless $self->_use_files;
1304 if (my $pairs = $self->_use_files->{rename}) {
1305 for my $pair (@$pairs) {
1306 my ($from, $to) = @$pair;
1307 $from->rename($to);
1308 }
1309 }
1310 $_->delete for @{ $self->_use_files->{delete} };
1311 }
1312  
1313 sub _file_exists {
1314 return -e $_[1];
1315 }
1316  
1317 sub _file_timestamp {
1318 return -e $_[1] ? -M _ : undef;
1319 }
1320  
1321 # allow drivers to over-ride the definition of various file routines
1322 # in various contexts
1323 sub _file_exists_for_skip {
1324 shift->_file_exists(@_);
1325 }
1326  
1327 sub _file_exists_for_in {
1328 shift->_file_exists(@_);
1329 }
1330  
1331 sub _file_exists_for_out {
1332 shift->_file_exists(@_);
1333 }
1334  
1335 sub _file_exists_for_delete {
1336 shift->_file_exists(@_);
1337 }
1338  
1339 sub _file_accepted_for_out {
1340 ; # no action in normal case
1341 }
1342  
1343 sub _file_timestamp_for_skip {
1344 shift->_file_timestamp(@_);
1345 }
1346  
1347 sub _file_timestamp_for_out {
1348 shift->_file_timestamp(@_);
1349 }
1350  
1351 sub _delete_file {
1352 unlink $_[1];
1353 }
1354  
1355 sub _unshared_file_exists_for_in {
1356 }
1357  
1358 sub _unshared_file_download_for_in {
1359 }
1360  
1361 sub _unshared_file_exists_for_out {
1362 }
1363  
1364 sub _unshared_file_upload_for_out {
1365 }
1366  
1367 sub _rename_file {
1368 my $self = shift;
1369 my $src = shift;
1370 my $dst = shift;
1371 if ($self->_file_exists($src)) {
1372 link $src, $dst;
1373 unlink $src;
1374 }
1375 }
1376  
1377 sub _file_list_acceptable_for_skip {
1378 my $self = shift;
1379 my $newest_pre = shift;
1380 my $list = shift;
1381 for my $file (@$list) {
1382 my $ts = $file->timestamp;
1383 if (not defined $ts) {
1384 $self->debug( "target file does not exist: $file" );
1385 return undef;
1386 }
1387 if ($newest_pre) {
1388 unless ($ts <= $newest_pre) {
1389 $self->debug( "target too old: timestamp of $file($ts) should be newer (less) than newest prerequisite ($newest_pre)" );
1390 return undef;
1391 }
1392 }
1393 }
1394 return 1;
1395 }
1396  
1397 =head2 should_choose_retry, choose_retries
1398  
1399 If a cluster has a tendency to fail randomly, it may be desired to
1400 retry a stage that fails rather than simply treating it as an unrecoverable
1401 failure.
1402  
1403 This pair of attributes specifies two aspects of making such a choice.
1404  
1405 First, the should_choose_retry attribute can be given a code reference to code
1406 that returns true if a retry should be made. This code is only called if the
1407 stage run has failed.
1408  
1409 The sub is called with two arguments:
1410 the status hash containing the known status results from the most recent try to
1411 run the stage, and a string with the name of the stderr output file. This code
1412 returns a true value to indicate that a retry should be attempted. If this
1413 attribute is not explicitly provided, it defaults to code that always returns 0
1414 to not cause a retry attempt.
1415  
1416 Second, the choose_retries attribute specifies number of times that the stage
1417 should be retried at the request of the should_choose_retry code (or at the
1418 request of the verify_completion_status code).
1419 The default is 1.
1420  
1421 =cut
1422  
1423 has 'should_choose_retry' => (
1424 is => 'ro',
1425 isa => 'CodeRef',
1426 predicate => '_has_should_choose_retry'
1427 );
1428  
1429 has 'choose_retries' => (
1430 is => 'ro',
1431 isa => 'Int',
1432 lazy => 1,
1433 default => 1,
1434 );
1435  
1436 has '_chosen_retries' => (
1437 is => 'rw',
1438 isa => 'Int',
1439 init_arg => undef,
1440 default => 0
1441 );
1442  
1443 =head2 force_retries
1444  
1445 If a cluster has a tendency to fail randomly, it may be desired to
1446 retry a stage that fails rather than simply treating it as an unrecoverable
1447 failure.
1448  
1449 This attribute specifies the number of times that the stage should be retried
1450 until it passes. The default is to not retry (unless the underlying driver
1451 retries for a specific reason).
1452  
1453 There are three types of retry selections. First, the devide driver can provide
1454 automatic retries for considitions appropriate to that cluster type. Second,
1455 the retries selected by the should_choose_retry attribute can cause a retry if
1456 the user-provided code chooses. Finally, the force_retries attribute can cause
1457 a retry. Each of these three is independent - any of them can cause a retry
1458 regardless of what the others would select. A stage only is deemed to have
1459 failed completely if none of the methods selects a retry. The counters for each
1460 type of retry test is only adjusted if that test was the one that caused a retry
1461 so there can be as amny retries as the total of the number allowed by each type.
1462  
1463 =cut
1464  
1465 has 'force_retries' => (
1466 is => 'ro',
1467 isa => 'Int',
1468 default => 0
1469 );
1470  
1471 has '_forced_retries' => (
1472 is => 'rw',
1473 isa => 'Int',
1474 init_arg => undef,
1475 default => 0
1476 );
1477  
1478 has '_failure_info' => (
1479 is => 'ro',
1480 isa => 'Str',
1481 writer => '_set_failure_info',
1482 predicate => '_has_failure_info',
1483 init_arg => undef,
1484 );
1485  
1486 has 'runs' => (
1487 is => 'ro',
1488 isa => 'ArrayRef',
1489 init_arg => undef,
1490 default => sub { [] },
1491 );
1492  
1493 sub _run {
1494 my $self = shift;
1495 my $runclass = $self->_run_class;
1496 my $run = $runclass->new(
1497 $self->_run_args,
1498 );
1499 push @{ $self->runs }, $run;
1500 return $run;
1501 }
1502  
1503 sub _run_args {
1504 my $self = shift;
1505 return (
1506 stage => $self,
1507 index => scalar( @{ $self->runs } ),
1508 )
1509 }
1510  
1511 sub get_run_stats {
1512 my $self = shift;
1513 return [
1514 $self->_has_failure_info ? { exit_status => $self->_failure_info }
1515 : scalar( @{ $self->runs } ) == 0 ? { exit_status => 'Stage skipped, skipstage determined it was complete',
1516 final_job_state => 'pass'
1517 }
1518 : map { $_->stats } @{ $self->runs }
1519 ];
1520 }
1521  
1522 =head2 failure_action ('abort_group', 'abort_deps'*, or 'ignore')
1523  
1524 Specifies the action to take if (the final retry of) this stage fails
1525 (terminates with non-zero status).
1526  
1527 There are three string values that it can have:
1528  
1529 =over
1530  
1531 =item - abort_deps (default)
1532  
1533 If the stage fails, then any stages which depend upon it
1534 (recursively) are not run. The group continues executing stages
1535 which are not dependent upon this stage.
1536  
1537 =item - abort_group
1538  
1539 If the stage fails, then no other stages are started. The group
1540 simply waits until previously started stages complete and then
1541 returns.
1542  
1543 =item - ignore
1544  
1545 Execution continues unchanged, any dependent stages will be run
1546 when they are no longer blocked.
1547  
1548 =back
1549  
1550 =cut
1551  
1552 enum 'FailureAction', [qw(abort_group ignore abort_deps)];
1553  
1554 has 'failure_action' => (
1555 is => 'ro',
1556 isa => 'FailureAction',
1557 default => 'abort_deps',
1558 );
1559  
1560 with qw(HPCI::Env HPCI::CommandScript HPCI::ScriptSource);
1561  
1562 =head1 METHODS
1563  
1564 =head2 command setting methods
1565  
1566 The following command setting methods can be used as an alternative to
1567 providing the command as a string.
1568  
1569 They each have the same parameter list:
1570  
1571 $stage->set_FOO_cmd( $command,
1572 $key1, $value1,
1573 $key2, $value2,
1574 ...
1575 );
1576  
1577 There are three types of keys - keys with a single letter, longer
1578 keys, and '--'. Single letter keys will be prefixed with a single
1579 dash; longer keys will be prefixed with a double dash. The special
1580 key '--' (two dashes) contains the non-option command line arguments.
1581  
1582 The values can either be a scalar or an arrayref. The way array
1583 values are expanded depends upon the choice of command setting
1584 method used.
1585  
1586 The argparse method (used for python and R) sets lists by putting
1587 all the list variables after a single option word:
1588  
1589 --infiles file1 file2 file3
1590  
1591 The gnuparse method (used for Perl) uses the standard Unix and gnu
1592 command way of setting lists by repeating the option word:
1593  
1594 --infiles file1 --infiles file2 --infiles file3
1595  
1596 In the case of the interpreter methods (set_python_cmd, set_perl_cmd,
1597 set_R_cmd), they simply prepend the appropriate interpreter to the
1598 provided script name, and invoke the right parsing method.
1599  
1600 =head2 set_argparse_cmd
1601  
1602 Set the command attribute to execute a command taking Python's
1603 argparse-style arguments.
1604  
1605 =cut
1606  
1607 sub set_argparse_cmd {
1608 my $self = shift;
1609 my $prog = shift;
1610 my %args = @_;
1611 my @args = ();
1612 my @tail = ();
1613 foreach my $key (sort keys %args) {
1614 if ($key eq '--') {
1615 push @tail, '--',
1616 (ref($args{$key}) eq 'ARRAY') ? (@{$args{$key}})
1617 : $args{$key};
1618 next;
1619 }
1620 push @args,
1621 (length $key > 1) ? "--$key"
1622 : "-$key";
1623 if (defined($args{$key})) {
1624 push @args,
1625 (ref($args{$key}) eq 'ARRAY') ? (@{$args{$key}})
1626 : $args{$key};
1627 }
1628 # else Assume this is a bool ean switch
1629 }
1630 $self->command( join ' ', $prog, @args, @tail );
1631 }
1632  
1633 =head2 set_gnu_cmd
1634  
1635 Set the command line arguments for a command taking GNU's getlongopt-style
1636 arguments.
1637  
1638 =cut
1639  
1640 sub set_gnu_cmd {
1641 my $self = shift;
1642 my $prog = shift;
1643 my %args = @_;
1644 my @args = ();
1645 my @tail = ();
1646 foreach my $key ( sort keys %args ) {
1647 if ($key eq '--') {
1648 push @tail, "--", ( ref( $args{$key} ) eq 'ARRAY' )
1649 ? @{ $args{$key} }
1650 : $args{$key};
1651 next;
1652 }
1653 else {
1654 my $key_prefix = length $key > 1 ? "--$key" : "-$key";
1655 push @args,
1656 ( !defined $args{$key}
1657 ? ($key_prefix)
1658 : map
1659 { ( $key_prefix, $_ ) }
1660 ( ref( $args{$key} ) eq 'ARRAY'
1661 ? @{ $args{$key} }
1662 : $args{$key}
1663 )
1664 );
1665 }
1666 }
1667 $self->command( join ' ', $prog, @args, @tail );
1668 }
1669  
1670 =head2 set_perl_cmd
1671  
1672 Wrapper around set_gnu_cmd that prefixes the Perl interpreter.
1673  
1674 =cut
1675  
1676 sub set_perl_cmd {
1677 my $self = shift;
1678 my $script = shift;
1679 $self->set_gnu_cmd( "perl $script", @_ );
1680 }
1681  
1682 =head2 set_python_cmd
1683  
1684 Wrapper around set_argparse_cmd that prefixes the Python interpreter.
1685  
1686 =cut
1687  
1688 sub set_python_cmd {
1689 my $self = shift;
1690 my $script = shift;
1691 $self->set_argparse_cmd( "python $script", @_ );
1692 }
1693  
1694 =head2 set_r_cmd
1695  
1696 Wrapper around set_argparse_cmd that prefixes the R interpreter.
1697  
1698 =cut
1699  
1700 sub set_r_cmd {
1701 my $self = shift;
1702 my $script = shift;
1703 $self->set_argparse_cmd( "Rscript $script", @_ );
1704 }
1705  
1706 =head1 AUTHOR
1707  
1708 Christopher Lalansingh - Boutros Lab
1709  
1710 Andre Masella - Boutros Lab
1711  
1712 John Macdonald - Boutros Lab
1713  
1714 =head1 ACKNOWLEDGEMENTS
1715  
1716 Paul Boutros, Phd, PI - Boutros Lab
1717  
1718 The Ontario Institute for Cancer Research
1719  
1720 =cut
1721  
1722 1;
« blib/lib/HPCI/File.pm ↑ Summary blib/lib/HPCD/uni/Group.pm »