blib/lib/HPCI/File.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/JobGroup.pm ↑ Summary blib/lib/HPCI.pm »
1 package HPCI::File;
2  
3 ### INCLUDES ##################################################################
4  
5 # safe Perl
6 22 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 22 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 22 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 22 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 22 ▶use YAML qw/LoadFile DumpFile/;
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use Digest::MD5::File qw(file_md5_hex);
12  
13 use Moose;
14  
15 use MooseX::Types::Path::Class qw(Dir File);
16 use Moose::Util::TypeConstraints;
17  
18 =head1 NAME
19  
20 HPCI::File;
21  
22 =head1 SYNOPSIS
23  
24 An object that describes a file to be used by a stage. It includes
25 the path to the file, whether the file must be maintained on a
26 separate long-term storage that is different from the access path
27 used by the stage program (and if so, how to copy the file between
28 the long-term storage and the working storage, and whether copying
29 can be done by the parent program or must be done by the stage).
30  
31 The stage attribute C<files> contains descriptive info about file
32 management for the stage - most of it component sections include a
33 file. That file can be either specified as a string, or with an
34 object that is HPCI::File or a sub-class thereof. A bare string
35 will normally be converted to an HPCI::File object, but the C<stage>
36 can contain a C<fileclass> attribute string that over-rides that
37 default, and additionally, the files attribute can contain a
38 C<fileclass> component that over-rides either of those defaults for
39 the one stage.
40  
41 =head1 ATTRIBUTES
42  
43 =head2 file
44  
45 The name of the file.
46  
47 =cut
48  
49 has 'file' => (
50 is => 'ro',
51 isa => File,
52 coerce => 1
53 );
54  
55 =head2 abs_file
56  
57 The absolute pathname of the file. Not fully used yet.
58  
59 =cut
60  
61 has 'abs_file' => (
62 is => 'ro',
63 isa => File,
64 lazy => 1,
65 init_arg => undef,
66 default => sub { $_[0]->file->absolute->cleanup },
67 );
68  
69 use overload '""' => '_stringify';
70  
71 sub _stringify {
72 # "" . (shift->file);
73 "" . (shift->abs_file);
74 }
75  
76  
77 =head2 sum
78  
79 Boolean, indicates whether checksums are used for this file. If they are,
80 the checksum is kept in a YAML file B<file>.sum. This YAML file contains
81 an array of hashes. Each hash has the keys 'type' and 'sum'. For each checksum
82 type requested (default is 'md5' at present, will expand to include 'sha1' in
83 the future) there is an entry in the array containing the checksum computed for
84 the corresponding method.
85  
86 =cut
87  
88 has 'sum' => (
89 is => 'ro',
90 isa => 'Bool',
91 default => '',
92 );
93  
94 has '_sum_file' => (
95 is => 'ro',
96 isa => File,
97 lazy => 1,
98 init_arg => undef,
99 coerce => 1,
100 default => sub {
101 my $self = shift;
102 # return undef unless $self->sum;
103 my $file = $self->file;
104 my $dir = $file->dir;
105 my $base = $file->basename;
106 return "$dir/$base.sum";
107 },
108 );
109  
110 =head2 sum_generate_in
111  
112 A boolean value, default is false.
113  
114 Specifies the action taken if the file is used for input and the
115 B<file>.sum checksum file is either not present or if it is older than B<file>.
116  
117 When B<false> is specified, the stage is failed.
118  
119 When B<TRUE> is specified, the checksum is computed and B<FILE>.sum is saved,
120 and then the stage is allowed to run normally.
121  
122 The default is B<FALSE> to ensure that changes to input data files are
123 done deliberately - an accidental edit should be considered an error.
124  
125 You would set the value to B<TRUE> when first receiving a newly downloaded
126 file from an outside source. When a file is created as an 'out' file, the
127 sum is always created (if the B<sum> attribute is true), so the default of
128 B<FALSE> does not cause problems for later stages.
129  
130 =cut
131  
132 has 'sum_generate_in' => (
133 is => 'ro',
134 isa => 'Bool',
135 default => 0,
136 );
137  
138 =head2 sum_validate_in
139  
140 This can be given a string ('timestamp', 'once', 'always') to indicate how
141 vigourously the checksum is validated.
142  
143 The default is 'once'.
144  
145 The setting 'timestamp' accepts the file as valid if the B<file>.sum files exists
146 and is newer than B<file>. (If it is older, then B<sum_generate_in> controls
147 how it is handled.)
148  
149 The setting 'once' loads the B<file>.sum data, and verifies the checksum(s)
150 explicitly the first time the file is used for input, but accepted as valid
151 after that point of the tiemstamps have not changed. (This avoids recomputing
152 the checksum(s) for every stage that reuses the same file.
153  
154 The setting 'always' validates the checksum(s) for every stage that uses the
155 file.
156  
157 =cut
158  
159 enum 'ValidateIn', [qw(timestamp once always)];
160  
161 has 'sum_validate_in' => (
162 is => 'ro',
163 isa => 'ValidateIn',
164 default => 'once',
165 );
166  
167 has '_sum_info' => (
168 is => 'rw',
169 isa => 'Maybe[ArrayRef[HashRef]]',
170 );
171  
172 has '_sum_status' => (
173 is => 'ro',
174 isa => 'HashRef',
175 default => sub { return {} },
176 init_arg => undef,
177 );
178  
179 =head2 _shared
180  
181 This is an internal attribute that specifies that the file is located
182 on a file system that is shared by all of the nodes in the cluster.
183 This value is over-ridden by subclasses of HPCI::File which provide
184 for files which are not on a shared file system.
185 Such subclasses must provide for get and put methods to copy files
186 between the local filer system and a repository that B<is> accessible
187 from all nodes (although not necessarily on the file system).
188 They will also define their own addition attributes
189 as needed to provide the details of accessing the
190  
191 =cut
192  
193 has '_shared' => (
194 is => 'ro',
195 isa => 'Bool',
196 init_arg => undef,
197 default => 1,
198 );
199  
200 has 'stage' => (
201 is => 'ro',
202 isa => 'Object',
203 required => 1,
204 weak_ref => 1,
205 handles => {
206 debug => 'debug',
207 info => 'info',
208 warn => 'warn',
209 error => 'error',
210 fatal => 'fatal',
211  
212 _file_info => '_file_info',
213 },
214 );
215  
216 =pod
217  
218 =head1 Storage management
219  
220 HPCI has two types of storage that it can deal with.
221  
222 Long-term storage is storage that is reliably preserved over time.
223 The data in long-term storage is accessible to all nodes on the
224 cluster.
225  
226 Working storage is storage that is directly-accessible to a node.
227 It can be a private disk that is not accessible to other nodes,
228 or it can be a shared file system that is available to other nodes.
229  
230 Some types of cluster can have their nodes rebuilt at intervals,
231 losing the data on their local disks.
232  
233 Some types of cluster have no shared file system, or have size
234 limitations on their shared file system.
235  
236 There are three scenarios:
237  
238 =over 4
239  
240 =item fully-shared
241  
242 When there is a reliable, fully-shared file system that has no
243 limitations to prevent it being used for the data, then files
244 can be on that file system. The same path will refer to the
245 long-term and working locations.
246  
247 =item partially-shared
248  
249 When there is a fully-shared file system that is not reliable for
250 long-term storage, it might be used as working storage. That
251 allows the parent process to carry out operations on the files for
252 the stage, and allow skipping the download of files that B<are>
253 still present when the storage has not been cleared.
254  
255 =item node-private
256  
257 When it is necessary to use storage that is only accessible by the
258 individual node for working storage, the the stage program must
259 carry out all upload and download operations, as well as any
260 validation checks that require data access to the file.
261  
262 =back
263  
264 This class has two methods that specify the storage scenario that it
265 provides.
266  
267 =head2 method has_long_term
268  
269 The method C<has_long_term> specifies whether this file uses a separate
270 long-term storage facility that is distinct from the working storage
271 that will be used by the stage for direct reading and/or writing.
272  
273 =head2 method has_shared_storage
274  
275 The method C<has_shared_storage> specifies whether the working storage location
276 used by the stage is also accessible to the parent program and/or other stages.
277  
278 =head2 Settings to indicate storage scenario
279  
280 has_long_term has_shared_storage
281 +---------------+--------------------+
282 fully-shared | false | true |
283 +---------------+--------------------+
284 partially-shared | true | true |
285 +---------------+--------------------+
286 node-private | true | false +
287 +---------------+--------------------+
288  
289 Subclasses of this class will over-ride these methods to specify
290 alternative values appropriate to the particular subclass.
291  
292 Note that setting both methods to return false is not a workable
293 process - that would imply that there is no storage type that
294 allows passing data between stages.
295  
296 =cut
297  
298 sub has_long_term {
299 0; # over-ridden in sub-classes as appropriate
300 }
301  
302 sub has_shared_working_storage {
303 1;
304 }
305  
306 sub exists_base_file {
307 my $self = shift;
308 my $stat = $self->file->stat;
309 return $stat && -e $stat;
310 }
311  
312 sub exists_valid_sum {
313 my $self = shift; # any needed sum file must exist or be creatable
314 $self->sum or return 1; # if sum is turned off, it is valid by default
315 my $file = $self->file;
316 my $fts = file_timestamp( $file );
317 my $sfile = $self->_sum_file;
318 my $sts = file_timestamp( $sfile );
319 my $fi = $self->_file_info->{"".$self->file} //= {};
320 if ($sts && $sts <= $fts) {
321 # sum file is up to date - determie whether we need to validate the value this time
322 my $vi = $self->sum_validate_in;
323 return 1 if $vi eq 'timestamp';
324 return 1 if $vi eq 'once' && exists $fi->{sum_ts} && $fi->{sum_ts} == $sts;
325 my $filesum = $fi->{sum} //= LoadFile($sfile);
326 $fi->{sum_ts} = $sts;
327 $self->_croak( "sum file ($sfile): multiple checksum types not supported yet" )
328 if 1 != scalar @$filesum;
329 my $type = $filesum->[0]{type};
330 my $sum = $filesum->[0]{sum};
331 $self->_croak( "sum file ($sfile): checksum type other than MD5 ($type) not supported yet" )
332 if $type ne 'MD5';
333 my $actsum = file_md5_hex($self->file);
334 if ($sum ne $actsum) {
335 $self->error( "sum file ($sfile): computed checksum does not match" );
336 return 0;
337 }
338 return 1;
339 }
340 else {
341 # sum file missing or old - determine whether to (re)create it or abort
342 if ($self->sum_generate_in) {
343 my $filesum = $fi->{sum} = [];
344 $filesum->[0]{type} = 'MD5';
345 $filesum->[0]{sum} = file_md5_hex($self->file);
346 DumpFile( $sfile, $filesum );
347 $fi->{sum_ts} = file_timestamp( $sfile );
348 $self->warn( "sum file ($sfile): (re-)generated sum for input file" );
349 return 1;
350 }
351 else {
352 $self->error( "sum file ($sfile): missing or out of date" );
353 return 0;
354 }
355 }
356 }
357  
358 sub valid_in_file {
359 my $self = shift;
360 return $self->exists_base_file && $self->exists_valid_sum;
361 }
362  
363 sub exists_out_file {
364 my $self = shift;
365 return $self->exists_base_file;
366 }
367  
368 sub file_timestamp {
369 my $file = shift;
370 my $stat = $file->stat // return undef;
371 -e $stat ? -M $stat : undef;
372 }
373  
374 sub timestamp {
375 file_timestamp( $_[0]->file );
376 }
377  
378 # generate a sum file if desired
379 # but extend to copy when long-term storage is not working storage
380 sub accepted_for_out {
381 my $self = shift;
382 if ($self->sum) {
383 my $info = {};
384 my $sfile = $self->_sum_file;
385 $info->{type} = 'MD5';
386 $info->{sum} = file_md5_hex($self->file);
387 DumpFile( $sfile, [ $info ] );
388 $self->info( "sum file ($sfile): generated sum for output file" );
389 }
390 }
391  
392 sub delete {
393 my $self = shift;
394 $self->file->remove if $self->exists_base_file;
395 $self->_sum_file->remove if $self->sum;
396 }
397  
398 sub rename {
399 my $self = shift;
400 my $target = shift;
401 # clone $from because move_to method modifies the file path of the from file
402 my $clone = Path::Class::File->new( "".$self->file );
403 $clone->move_to( $target )
404 or $self->croak("failed attempt to rename $self to $target");
405 if ($self->sum) {
406 $target .= ".sum";
407 my $clone = Path::Class::File->new( "".$self->_sum_file );
408 $clone->move_to( "$target" )
409 or $self->croak("failed attempt to rename $self to $target");
410 }
411 }
412  
413 around BUILDARGS => sub {
414 my $orig = shift;
415 my $class = shift;
416 my @args = @_;
417  
418 try {
419 return $class->$orig(@args);
420 }
421 catch {
422 my $msg = $_;
423 $msg .= "\nArgs are:\n";
424 my $cnt = 0;
425 my @pref = ( " Key: ", " Val: " );
426  
427 for my $arg (@args) {
428 $msg .= $pref[$cnt] . $arg . "\n";
429 $cnt = 1 - $cnt;
430 }
431 die $msg;
432 };
433 };
434  
435 package HPCI::File::Classes;
436  
437 use MooseX::Role::Parameterized;
438 use MooseX::Types::Path::Class qw(Dir File);
439 use Moose::Util::TypeConstraints;
440  
441 subtype 'HPCIFileGen',
442 as 'CodeRef';
443  
444 coerce 'HPCIFileGen',
445 from 'Str', via { _create_HPCIFileGen( $_ ) },
446 from 'ArrayRef', via { _create_HPCIFileGen( @$_ ) };
447  
448 sub _create_HPCIFileGen {
449 return sub { shift->new( @_ ) };
450 }
451  
452 sub _create_HPCIFileGenHash {
453 my $key = shift;
454 return { $key => _create_HPCIFileGen( @_ ) };
455 }
456  
457 subtype 'HPCIFileList',
458 as 'ArrayRef[HPCIFileGenHash]';
459  
460 coerce 'HPCIFileList',
461 from 'ArrayRef[ArrayRef[Str]]', via { _create_HPCIFileGenHash( @$_ ) for @$_ };
462  
463 has 'storage_classes' => (
464 is => 'ro',
465 isa => 'HPCIFileList',
466 default => sub { [ ] },
467 coerce => 1,
468 );
469  
470  
471 1;
« blib/lib/HPCI/JobGroup.pm ↑ Summary blib/lib/HPCI.pm »