blib/lib/HPC/Runner.pm

filter: Statementstmt 33.3% 1 / 3 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 1 / 1 Podpod n/a totaltotal 50.0% 2 / 4 CC 1 SCAR 2.6
CC
1
Cov
33%
BEGIN
1.3
CRAP 1.3
« Build ↑ Summary
1 package HPC::Runner;
2  
3 #use 5.006;
4  
5 1 ▶use Carp::Always;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use Data::Dumper;
7 use IPC::Open3;
8 use IO::Select;
9 use Symbol;
10 use Log::Log4perl qw(:easy);
11 use DateTime;
12 use DateTime::Format::Duration;
13 use Cwd;
14 use File::Path qw(make_path);
15 use File::Spec;
16 #use String::Escape qw( quote );
17  
18 use Moose;
19 use namespace::autoclean;
20  
21 use Moose::Util::TypeConstraints;
22 #with 'MooseX::Getopt';
23 with 'MooseX::Getopt::Usage';
24 with 'MooseX::Getopt::Usage::Role::Man';
25  
26 # For pretty man pages!
27 $ENV{TERM}='xterm-256color';
28  
29 =head1 NAME
30  
31 HPC::Runner - HPC Runner::Slurm, Runner::MCE and Runner::Threads base class
32  
33 =head1 VERSION
34  
35 Version 0.01
36  
37 =cut
38  
39 our $VERSION = '2.41';
40  
41 =head1 SYNOPSIS
42  
43 This is a base class for HPC::Runner::MCE and HPC::Runner:Threads. You should not need to call this module directly.
44  
45 =head1 EXPORT
46  
47 =cut
48  
49 =head1 VARIABLES
50  
51 =cut
52  
53 =head2 infile
54  
55 File of commands separated by newline. The command 'wait' indicates all previous commands should finish before starting the next one.
56  
57 =cut
58  
59 has 'infile' => (
60 is => 'rw',
61 isa => 'Str',
62 required => 1,
63 documentation => q{File of commands separated by newline. The command 'wait' indicates all previous commands should finish before starting the next one.},
64 trigger => \&_set_infile,
65 );
66  
67 =head2 _set_infile
68  
69 Internal variable
70  
71 =cut
72  
73 sub _set_infile{
74 my($self, $infile) = @_;
75  
76 $infile = File::Spec->rel2abs($infile);
77 $self->{infile} = $infile;
78 }
79  
80 =head2 outdir
81  
82 Directory to write out files and logs.
83  
84 =cut
85  
86 has 'outdir' => (
87 is => 'rw',
88 isa => 'Str',
89 required => 1,
90 default => sub {return getcwd()."/logs" },
91 # default => sub { return "$ENV{HOME}/hpcjobs" },
92 documentation => q{Directory to write out files.},
93 trigger => \&_set_outdir,
94 );
95  
96 =head2 _set_outdir
97  
98 Internal variable
99  
100 =cut
101  
102 sub _set_outdir{
103 my($self, $outdir) = @_;
104  
105 #make_path(quote($outdir)) if ! -d $outdir;
106 make_path($outdir) if -d $outdir;
107 $outdir = File::Spec->rel2abs($outdir);
108 $self->{outdir} = $outdir;
109 }
110  
111 =head2 logdir
112  
113 Pattern to use to write out logs directory. Defaults to outdir/prunner_current_date_time/log1 .. log2 .. log3.
114  
115 =cut
116  
117 has 'logdir' => (
118 is => 'rw',
119 isa => 'Str',
120 lazy => 1,
121 required => 1,
122 default => \&set_logdir,
123 documentation => q{Directory where logfiles are written. Defaults to current_working_directory/prunner_current_date_time/log1 .. log2 .. log3'},
124 );
125  
126 =head2 procs
127  
128 Total number of running children allowed at any time. Defaults to 10. The command 'wait' can be used to have a variable number of children running. It is best to wrap this script in a slurm job to not overuse resources. This isn't used within this module, but passed off to mcerunner/parallelrunner.
129  
130 =cut
131  
132 has 'procs' => (
133 is => 'rw',
134 isa => 'Int',
135 default => 4,
136 required => 0,
137 documentation => q{Total number of running jobs allowed at any time. The command 'wait' can be used to have a variable number of children running.}
138 );
139  
140 =head2 job_scheduler_id
141  
142 Job Scheduler ID running the script. Passed to slurm for mail information
143  
144 =cut
145  
146 has 'job_scheduler_id' => (
147 is => 'rw',
148 isa => 'Str|Undef',
149 default => sub { return $ENV{SLURM_JOB_ID} || $ENV{PBS_JOBID} || undef; },
150 required => 1,
151 documentation => q{This defaults to your current Job Scheduler ID. Ignore this if running on a single node}
152 );
153  
154 has 'show_processid' => (
155 is => 'rw',
156 isa => 'Bool',
157 default => 0,
158 documentation => q{Show the process ID per logging message. This is useful when aggregating logs.}
159 );
160  
161 #has 'verbose' => (
162 #is => 'rw',
163 #isa => enum([qw[0 1]]),
164 #required => 1,
165 #default => 1,
166 #documentation => q{Level of verbosity},
167 #);
168  
169 =head1 Internal VARIABLES
170  
171 You shouldn't be calling these directly.
172  
173 =cut
174  
175 =head2 jobref
176  
177 Array of arrays details slurm/process/scheduler job id. Index -1 is the most recent job submissisions, and there will be an index -2 if there are any job dependencies
178  
179 =cut
180  
181 has 'jobref' => (
182 traits => ['NoGetopt'],
183 is => 'rw',
184 isa => 'ArrayRef',
185 default => sub { [ [] ] },
186 );
187  
188 =head2 wait
189  
190 Boolean value indicates any job dependencies
191  
192 =cut
193  
194 has 'wait' => (
195 traits => ['NoGetopt'],
196 is => 'rw',
197 isa => 'Bool',
198 default => 0,
199 );
200  
201 has 'cmd' => (
202 traits => ['String', 'NoGetopt'],
203 is => 'rw',
204 isa => 'Str',
205 #lazy_build => 1,
206 required => 0,
207 #default => q{},
208 handles => {
209 add_cmd => 'append',
210 match_cmd => 'match',
211 },
212 predicate => 'has_cmd',
213 clearer => 'clear_cmd',
214 );
215  
216 has 'counter' => (
217 traits => ['Counter', 'NoGetopt'],
218 is => 'rw',
219 isa => 'Num',
220 required => 1,
221 default => 1,
222 handles => {
223 inc_counter => 'inc',
224 dec_counter => 'dec',
225 reset_counter => 'reset',
226 },
227 );
228  
229 #this needs to be called in the main app
230 has 'log' => (
231 traits => ['NoGetopt'],
232 is => 'rw',
233 # default => \&init_log,
234 );
235  
236 has 'command_log' => (
237 traits => ['NoGetopt'],
238 is => 'rw',
239 );
240  
241 has 'logfile' => (
242 traits => ['String', 'NoGetopt'],
243 is => 'rw',
244 default => \&set_logfile,
245 handles => {
246 add_logfile => 'append',
247 prepend_logfile => 'prepend',
248 clear_logfile => 'clear',
249 }
250 );
251  
252 has 'logname' => (
253 isa => 'Str',
254 is => 'rw',
255 default => 'hpcrunner_logs',
256 );
257  
258 =head1 Subroutines
259  
260 =head2 set_logdir
261  
262 Set the log directory
263  
264 =cut
265  
266 sub set_logdir{
267 my $self = shift;
268  
269 my $logdir;
270 $logdir = $self->outdir."/".$self->logname."_".$self->set_logfile;
271  
272 $DB::single=2;
273 $logdir =~ s/\.log$//;
274  
275 make_path($logdir) if ! -d $logdir;
276 return $logdir;
277 }
278  
279 =head2 set_logfile
280  
281 Set logfile
282  
283 =cut
284  
285 sub set_logfile{
286 my $self = shift;
287  
288 my $dt = DateTime->now();
289 $dt =~ s/[^\w]/_/g;
290 return "$dt.log";
291 }
292  
293 =head2 init_log
294  
295 Initialize Log4perl log
296  
297 =cut
298  
299 sub init_log {
300 my $self = shift;
301  
302 Log::Log4perl->easy_init(
303 {
304 level => $TRACE,
305 utf8 => 1,
306 mode => 'append',
307 file => ">>".$self->logdir."/".$self->logfile,
308 layout => '%d: %p %m%n '
309 }
310 );
311  
312 my $log = get_logger();
313 return $log;
314 }
315  
316 =head2 run_command_threads
317  
318 Start the thread, run the command, and finish the thread
319  
320 =cut
321  
322 sub run_command_threads{
323 my $self = shift;
324  
325 my $pid = $self->threads->start($self->cmd) and return;
326 push(@{$self->jobref->[-1]}, $pid);
327  
328 my $exitcode = $self->_log_commands($pid);
329  
330 $self->threads->finish($exitcode); # pass an exit code to finish
331  
332 return;
333 }
334  
335 =head2 run_command_mce
336  
337 MCE knows which subcommand to use from Runner/MCE - object mce
338  
339 =cut
340  
341 sub run_command_mce{
342 my $self = shift;
343  
344 my $pid = $$;
345  
346 $DB::single=2;
347  
348 #Mce doesn't take exitcode to end
349 push(@{$self->jobref->[-1]}, $pid);
350 $self->_log_commands($pid);
351  
352 return;
353 }
354  
355 =head2 _log_commands
356  
357 Log the commands run them. Cat stdout/err with IO::Select so we hopefully don't break things.
358  
359 This example was just about 100% from the following perlmonks discussions.
360  
361 http://www.perlmonks.org/?node_id=151886
362  
363 You can use the script at the top to test the runner. Just download it, make it executable, and put it in the infile as
364  
365 perl command.pl 1
366 perl command.pl 2
367 #so on and so forth
368  
369 =cut
370  
371 sub _log_commands {
372 my($self, $pid) = @_;
373  
374 #same here
375 my $dt1 = DateTime->now();
376  
377 #Create logdir
378 $DB::single=2;
379  
380 #Create new log for each job
381 $self->logfile($self->set_logfile);
382 $self->prepend_logfile("CMD".$self->counter."_PID_$pid"."_DT_");
383 $DB::single=2;
384  
385 #my $logger = $self->init_log;
386 $self->command_log($self->init_log);
387  
388 #Start running job
389 my ($infh,$outfh,$errfh);
390 $errfh = gensym(); # if you uncomment this line, $errfh will
391 # never be initialized for you and you
392 # will get a warning in the next print
393 # line.
394 my $cmdpid;
395 eval{
396 $cmdpid = open3($infh, $outfh, $errfh, $self->cmd);
397 };
398 die $@ if $@;
399 if(! $cmdpid) {
400 print "There is no $cmdpid please contact your administrator with the full command given\n";
401 die;
402 }
403 $infh->autoflush();
404  
405 $DB::single=2;
406  
407  
408 $self->log_messages("debug", "Starting Job: ".$self->counter." \nCmd is ".$self->cmd, $cmdpid);
409  
410 $self->command_log->debug("@ is ".$@) if $@;
411  
412 $DB::single=2;
413  
414 # now our child is running, happily printing to
415 # its stdout and stderr (our $outfh and $errfh).
416  
417 my $sel = new IO::Select; # create a select object
418 $sel->add($outfh,$errfh); # and add the fhs
419  
420 while(my @ready = $sel->can_read) {
421 foreach my $fh (@ready) { # loop through them
422 my $line;
423 # read up to 4096 bytes from this fh.
424 my $len = sysread $fh, $line, 4096;
425 if(not defined $len){
426 # There was an error reading
427 $self->log_messages("fatal", "Error from child: $!" , $cmdpid)
428 } elsif ($len == 0){
429 # Finished reading from this FH because we read
430 # 0 bytes. Remove this handle from $sel.
431 $sel->remove($fh);
432 next;
433 } else { # we read data alright
434 if($fh == $outfh) {
435 $self->log_messages("info", $line, $cmdpid)
436 } elsif($fh == $errfh) {
437 $self->log_messages("error", $line, $cmdpid)
438 } else {
439 $self->command_log->fatal("Shouldn't be here!\n");
440 }
441 }
442 }
443 }
444  
445 waitpid($cmdpid, 1);
446 my $exitcode = $?;
447  
448 $DB::single=2;
449  
450 $self->log_messages("debug", "Finishing job ".$self->counter." with ExitCode $exitcode", $cmdpid);
451  
452 my $dt2 = DateTime->now();
453 my $duration = $dt2 - $dt1;
454 my $format = DateTime::Format::Duration->new(
455 pattern => '%Y years, %m months, %e days, %H hours, %M minutes, %S seconds'
456 );
457  
458 $self->log_messages("info", "Total execution time ".$format->format_duration($duration), $cmdpid);
459  
460 return $exitcode;
461 }
462  
463 sub log_messages{
464 my($self, $level, $message, $cmdpid) = @_;
465  
466 if($self->show_processid){
467 $self->command_log->$level("PID: $cmdpid\t$message");
468 }
469 else{
470 $self->command_log->$level($message);
471 }
472 }
473  
474  
475 __PACKAGE__->meta->make_immutable;
476 1;
477  
478 =head1 AUTHOR
479  
480 Jillian Rowe, C<< <jillian.e.rowe at gmail.com> >>
481  
482 =head1 BUGS
483  
484 Please report any bugs or feature requests to C<bug-runner-init at rt.cpan.org>, or through
485 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Runner-Init>. I will be notified, and then you'll
486 automatically be notified of progress on your bug as I make changes.
487  
488  
489  
490  
491 =head1 SUPPORT
492  
493 You can find documentation for this module with the perldoc command.
494  
495 perldoc Runner::Init
496  
497  
498 You can also look for information at:
499  
500 =over 4
501  
502 =item * RT: CPAN's request tracker (report bugs here)
503  
504 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Runner-Init>
505  
506 =item * AnnoCPAN: Annotated CPAN documentation
507  
508 L<http://annocpan.org/dist/Runner-Init>
509  
510 =item * CPAN Ratings
511  
512 L<http://cpanratings.perl.org/d/Runner-Init>
513  
514 =item * Search CPAN
515  
516 L<http://search.cpan.org/dist/Runner-Init/>
517  
518 =back
519  
520 =head1 Acknowledgements
521  
522 This module was originally developed at and for Weill Cornell Medical
523 College in Qatar within ITS Advanced Computing Team. With approval from
524 WCMC-Q, this information was generalized and put on github, for which
525 the authors would like to express their gratitude.
526  
527 =head1 LICENSE AND COPYRIGHT
528  
529 Copyright 2014 Weill Cornell Medical College.
530  
531 This program is free software; you can redistribute it and/or modify it
532 under the terms of the the Artistic License (2.0). You may obtain a
533 copy of the full license at:
534  
535 L<http://www.perlfoundation.org/artistic_license_2_0>
536  
537 Any use, modification, and distribution of the Standard or Modified
538 Versions is governed by this Artistic License. By using, modifying or
539 distributing the Package, you accept this license. Do not use, modify,
540 or distribute the Package, if you do not accept this license.
541  
542 If your Modified Version has been derived from a Modified Version made
543 by someone other than you, you are nevertheless required to ensure that
544 your Modified Version complies with the requirements of this license.
545  
546 This license does not grant you the right to use any trademark, service
547 mark, tradename, or logo of the Copyright Holder.
548  
549 This license includes the non-exclusive, worldwide, free-of-charge
550 patent license to make, have made, use, offer to sell, sell, import and
551 otherwise transfer the Package with respect to any patent claims
552 licensable by the Copyright Holder that are necessarily infringed by the
553 Package. If you institute patent litigation (including a cross-claim or
554 counterclaim) against any party alleging that the Package constitutes
555 direct or contributory patent infringement, then this Artistic License
556 to you shall terminate on the date that such litigation is filed.
557  
558 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
559 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
560 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
561 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
562 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
563 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
564 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
565 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
566  
567  
568 =cut
569  
570 #End of Runner::Init
« Build ↑ Summary