blib/lib/Jobrun.pm

filter: Statementstmt 88.2% 15 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.3% 21 / 23 CC 1 SCAR 0.5
CC
1
Cov
88%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 # Jared Still
2 # 2024-05-21
3 # jkstill@gmail.com
4 #
5 # use to fork a process to run a job
6 # jobrun.pl is the front end
7 ######################################################
8  
9 =head1 Jobrun.pm
10  
11 Jobrun - run an arbitrarily large list of jobs, N jobs in parallel simultaneously
12  
13 =cut
14  
15 =head1 VERSION
16  
17 Version 0.01
18  
19 =cut
20  
21 =head1 NAME
22  
23 Jobrun - A framework for running jobs in parallel
24  
25 =head1 Synopsis
26  
27 The Jobrun module provides a framework for running jobs in a controlled manner.
28  
29 See jobrun.pl --help for usage.
30  
31 Also see README.md for more details.
32  
33 =cut
34  
35 =head1 AUTHOR
36  
37 Jared Still, C<< <jkstill at gmail.com> >>
38  
39 =head1 BUGS
40  
41 Please report any bugs or feature requests to C<bug-jobrun at rt.cpan.org>, or through
42 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Jobrun>. I will be notified, and then you'll
43 automatically be notified of progress on your bug as I make changes.
44  
45  
46 =head1 SUPPORT
47  
48 You can find documentation for this module with the perldoc command.
49  
50 perldoc Jobrun
51 jobrun.pl --help
52 README.md
53  
54 You can also look for information at:
55  
56 =over 4
57  
58 =item * RT: CPAN's request tracker (report bugs here)
59  
60 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Jobrun>
61  
62 =item * CPAN Ratings
63  
64 L<https://cpanratings.perl.org/d/Jobrun>
65  
66 =item * Search CPAN
67  
68 L<https://metacpan.org/release/Jobrun>
69  
70 =back
71  
72  
73 =head1 LICENSE AND COPYRIGHT
74  
75 This software is Copyright (c) 2025 by Jared Still.
76  
77 This is free software, licensed under:
78  
79 The MIT License
80  
81 =cut
82  
83  
84 package Jobrun;
85  
86 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
87 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
88 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
89 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
90 1 ▶use File::Temp qw/ :seekable tmpnam/;
Subroutine BEGIN: called CC=1 SCAR=0.0
91 0 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=2.6
92 use Carp;
93 use IO::File;
94 use POSIX qw(strftime);
95 use Time::HiRes qw(time usleep);
96  
97 use lib '.';
98  
99 require Exporter;
100 our @ISA = qw(Exporter);
101 our @EXPORT_OK = qw(
102 logger childSanityCheck createResumableFile cleanupResumableFile
103 getRunningJobPids microSleep getTimeStamp getTableTimeStamp
104 status getChildrenCount setControlTable getControlTable init
105 );
106 our $VERSION = '0.01';
107  
108 my $tableDir = './tables';
109 mkdir $tableDir unless -d $tableDir;
110 -d $tableDir or croak "table directory $tableDir not created: $!\n";
111  
112 my $controlTable;
113  
114 sub setControlTable {
115 $controlTable = shift;
116 return;
117 }
118  
119 sub getControlTable {
120 return $controlTable;
121 }
122  
123 # call this just once from the driver script jobrun.pl
124 my $utilDBH;
125  
126 sub init {
127 $utilDBH = createDbConnection();
128 createTable();
129 truncateTable();
130 return;
131 }
132  
133 sub createDbConnection {
134 my $dbh = DBI->connect(
135 "dbi:CSV:",
136 undef, undef,
137 {
138 f_ext => ".csv",
139 f_dir => $tableDir,
140 flock => 2,
141 RaiseError => 1,
142 }
143 )
144 or croak "Cannot connect: $DBI::errstr";
145  
146 return $dbh;
147 }
148  
149 # add start,end,elapsed time to table
150  
151 sub createTable {
152  
153 # create table if it does not exist
154 eval {
155 local $utilDBH->{RaiseError} = 1;
156 local $utilDBH->{PrintError} = 0;
157  
158 $utilDBH->do(
159 qq{CREATE TABLE $controlTable (
160 name CHAR(50)
161 , pid CHAR(12)
162 , status CHAR(20)
163 , start_time CHAR(30)
164 , end_time CHAR(30)
165 , elapsed_time CHAR(20)
166 , exit_code CHAR(10)
167 , cmd CHAR(200))
168 }
169 );
170  
171 };
172  
173 #if ($@) {
174 #print "Error: $@\n";
175 #print "Table most likely already exists\n";
176 #}
177  
178 return;
179 }
180  
181 sub truncateTable {
182 $utilDBH = createDbConnection();
183 $utilDBH->do("DELETE FROM $controlTable");
184 return;
185 }
186  
187 sub insertTable {
188 my ( $self, $name, $pid, $status, $startTime, $endTime, $elapsedTime, $exit_code, $cmd ) = @_;
189  
190 #print 'insertTable SELF: ' . Dumper($self);
191 my $dbh = $self->{dbh};
192 my $sth = $dbh->prepare("INSERT INTO $controlTable (name,pid,status,start_time,end_time,elapsed_time,exit_code,cmd) VALUES (?,?,?,?,?,?,?,?)");
193 $sth->execute( $name, $pid, $status, $startTime, $endTime, $elapsedTime, $exit_code, $cmd );
194  
195 # DBD::CSV always autocommits
196 # this is here in the event that we use a different DBD
197 #$dbh->commit();
198 return;
199 }
200  
201 sub deleteTable {
202 my ( $self, $name ) = @_;
203 my $dbh = $self->{dbh};
204 my $sth = $dbh->prepare("DELETE FROM $controlTable WHERE name = ?");
205 $sth->execute($name);
206  
207 #$dbh->commit();
208 return;
209 }
210  
211 sub selectTable {
212 my ( $self, $column, $value ) = @_;
213 my $dbh = $self->{dbh};
214 my $sth = $dbh->prepare("SELECT * FROM $controlTable WHERE ? = ?");
215 $sth->execute( $column, $value );
216 my $hashRef = $sth->fetchall_hashref;
217 return $hashRef;
218 }
219  
220 # only updates status and exit_code
221 sub updateStatus {
222 my ( $self, $name, $status, $exit_code, $startTime, $endTime, $elapsedTime ) = @_;
223 my $dbh = $self->{dbh};
224 my $sth = $dbh->prepare("UPDATE $controlTable SET status = ?, exit_code = ?, start_time = ? , end_time = ?, elapsed_time = ? WHERE name = ?");
225 $sth->execute( $status, $exit_code, $startTime, $endTime, $elapsedTime, $name );
226  
227 #$dbh->commit();
228 return;
229 }
230  
231 # this is a sanity check for the child processes
232 # validate that the child process is running
233 # if not then update status as failed and -1 in exit_code
234 sub childSanityCheck {
235 my ( $logFileFH, $verbose ) = @_;
236 logger( $logFileFH, $verbose, "childSanityCheck()\n" );
237 my $sth = $utilDBH->prepare("SELECT pid FROM $controlTable WHERE status = ?");
238 $sth->execute('running');
239 while ( my $row = $sth->fetchrow_hashref ) {
240  
241 my $pid = $row->{pid};
242 logger( $logFileFH, $verbose, " pid: $pid\n" );
243  
244 my $rc = kill 0, $pid;
245 logger( $logFileFH, $verbose, " rc: $rc\n" );
246  
247 if ( $rc == 0 ) {
248 my $dbh = createDbConnection();
249 my $sth = $dbh->prepare("UPDATE $controlTable SET status = ?, exit_code = ? WHERE pid = ?");
250 $sth->execute( 'failed', -1, $pid );
251 }
252 }
253 return;
254 }
255  
256 sub logger {
257 my ( $fh, $verbose, @msg ) = @_;
258 while (@msg) {
259 my $line = shift @msg;
260 $fh->print($line);
261 print "$line" if $verbose;
262 }
263 return;
264 }
265  
266 sub new {
267 my ( $pkg, %args ) = @_;
268 my $class = ref($pkg) || $pkg;
269  
270 #print "Class: $class\n";
271  
272 $args{dbh} = createDbConnection();
273  
274 $args{insert} = \&insertTable;
275 $args{updateStatus} = \&updateStatus;
276 $args{delete} = \&deleteTable;
277 $args{select} = \&selectTable;
278  
279 # name,pid,status,start_time,end_time,elapsed_time,exit_code,cmd) VALUES (?,?,?,?,?)");
280  
281 $args{columnNamesByName} = { name => 0, pid => 1, cmd => 2, status => 3, exit_code => 4 };
282 $args{columnNamesByIndex} = { 0 => 'name', 1 => 'pid', 2 => 'cmd', 3 => 'status', 4 => 'exit_code' };
283 $args{columnValues} = [qw/undef undef undef undef undef/];
284  
285 my ( $user, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, $shell, $expire ) = getpwuid($<) or croak "getpwuid: $!";
286 print "User: $user, UID: $uid\n";
287  
288 my $retval = bless \%args, $class;
289  
290 $retval->{insert}(
291 $retval,
292 $retval->{JOBNAME}, #job name
293 $$, #pid
294 , 'running' #status
295 , 'NA' #exit code
296 , '' #start time
297 , '' #end time
298 , '' #elapsed time
299 , $retval->{CMD}, #command
300  
301 );
302 return $retval;
303 }
304  
305 sub getChildrenCount {
306  
307 # Return current child count
308 my $sth = $utilDBH->prepare("SELECT count(*) child_count FROM $controlTable WHERE status = 'running'");
309 $sth->execute();
310 my $row = $sth->fetchrow_hashref;
311 return $row->{child_count} ? $row->{child_count} : 0;
312 }
313  
314 # status is called as a separate process
315 # and will have not knowledge of the Jobrun object
316 # so we need to pass the controlTable name
317 sub status {
318 my ( $controlTable, $statusType, %config ) = @_;
319 my $dbh = createDbConnection();
320 my $sql;
321 -r "$tableDir/${controlTable}.csv" or croak "table $tableDir/$controlTable.csv does not exist: $!\n";
322 if ( $statusType eq 'all' ) {
323 $sql = "SELECT * FROM $controlTable order by start_time asc";
324 }
325 else {
326 $sql = "SELECT * FROM $controlTable WHERE status = '$statusType' order by start_time asc";
327 }
328  
329 print "table: $controlTable\n";
330  
331 my $sth = $dbh->prepare($sql);
332 $sth->execute();
333  
334 # %-$config{colLenSTART_TIME}s %-$config{colLenEND_TIME}s %-$config{colLenELAPSED_TIME}s
335 printf "%-$config{colLenNAME}s %-$config{colLenPID}s %-$config{colLenSTATUS}s %-$config{colLenEXIT_CODE}s %-$config{colLenSTART_TIME}s %-$config{colLenEND_TIME}s %-$config{colLenELAPSED_TIME}s %-$config{colLenCMD}s\n", 'name', 'pid', 'status', 'exit_code', 'start_time', 'end_time', 'elapsed', 'cmd';
336  
337 printf "%-$config{colLenNAME}s %-$config{colLenPID}s %-$config{colLenSTATUS}s %-$config{colLenEXIT_CODE}s %-$config{colLenSTART_TIME}s %-$config{colLenEND_TIME}s %-$config{colLenELAPSED_TIME}s %-$config{colLenCMD}s\n", '-' x $config{colLenNAME}, '-' x $config{colLenPID}, '-' x $config{colLenSTATUS}, '-' x $config{colLenEXIT_CODE}, '-' x $config{colLenSTART_TIME}, '-' x $config{colLenEND_TIME}, '-' x $config{colLenELAPSED_TIME}, '-' x $config{colLenCMD};
338 while ( my $row = $sth->fetchrow_hashref ) {
339 my $rowlen = length( $row->{cmd} ) + 0;
340  
341 #warn "rowlen: $rowlen\n";
342 printf "%-$config{colLenNAME}s %-$config{colLenPID}s %-$config{colLenSTATUS}s %-$config{colLenEXIT_CODE}s %-$config{colLenSTART_TIME}s %-$config{colLenEND_TIME}s %$config{colLenELAPSED_TIME}s %-$config{colLenCMD}s\n", $row->{name}, $row->{pid}, $row->{status}, $row->{exit_code}, $row->{start_time}, $row->{end_time}, sprintf( '%6.6f', $row->{elapsed_time} ? $row->{elapsed_time} : 0 ),
343 substr(
344 $row->{cmd}, defined( $config{colCmdStartPos} ) ? $config{colCmdStartPos} : 0, defined( $config{colCmdEndPos} )
345 ? $config{colCmdEndPos}
346 : ( $rowlen - 1 ),
347 );
348 }
349 return;
350 }
351  
352 sub createResumableFile {
353 my ( $resumableFileName, $jobsHashRef ) = @_;
354  
355 my $fh = IO::File->new();
356 $fh->open( $resumableFileName, '>' ) or croak "could not create resumable file - $resumableFileName: $!\n";
357  
358 my $dbh = createDbConnection();
359  
360 # cannot figure out use to get '!=' or 'not in' to work with DBD::CSV
361 # in DBD::CSV :
362 # '!=' is not supported
363 # '<>' is not supported
364 # 'NOT IN' must be capitalized - not sure if this is a bug or by design
365 my $sql = "SELECT name,status FROM $controlTable WHERE status NOT IN ('complete')";
366 my $sth = $dbh->prepare($sql);
367 $sth->execute();
368 while ( my @row = $sth->fetchrow_array ) {
369 $fh->print( "$row[0]" . ':' . "$jobsHashRef->{$row[0]}\n" );
370 }
371 return;
372 }
373  
374 # remove the file if empty
375 sub cleanupResumableFile {
376 my ($resumableFileName) = @_;
377 -z $resumableFileName && unlink $resumableFileName;
378 return;
379 }
380  
381 # this may be called with --kill, so we need to create a connection
382 sub getRunningJobPids {
383 my $dbh = createDbConnection();
384 my $sth = $dbh->prepare("SELECT pid FROM $controlTable WHERE status = 'running'");
385 $sth->execute();
386 my @jobPids;
387 while ( my $row = $sth->fetchrow_hashref ) {
388 push @jobPids, $row->{pid};
389 }
390 return @jobPids;
391 }
392  
393 sub microSleep {
394 my $microseconds = shift;
395 usleep( ( $microseconds / 1000000 ) * 1000000 );
396 return;
397 }
398  
399 sub getTimeStamp {
400 my @t = [Time::HiRes::gettimeofday]->@*;
401 return strftime( "%Y-%m-%d %H:%M:%S", localtime $t[0] ) . "." . $t[1];
402 }
403  
404 sub getTableTimeStamp {
405 my @t = [Time::HiRes::gettimeofday]->@*;
406 return strftime( "%Y_%m_%d_%H_%M_%S", localtime $t[0] );
407 }
408  
409 sub child {
410 my ( $self, $jobName, $cmd ) = @_;
411  
412 #print 'SELF: ' . Dumper($self);
413 my $grantParentPID = $$;
414  
415 my $child = fork();
416  
417 #croak("Can't fork: $!") unless defined ($child = fork());
418 croak("Can't fork #1: $!") unless defined($child);
419  
420 if ($child) {
421 logger( $self->{LOGFH}, $self->{VERBOSE}, "child:$$ cmd:$self->{CMD}\n" );
422  
423 }
424 else {
425 my $parentPID = $$;
426 my $grandChild = fork();
427 croak("Can't fork #2: $!") unless defined($grandChild);
428  
429 if ( $grandChild == 0 ) {
430  
431 # use system() here
432 #qx/$cmd/;
433 my $pid = $$;
434 logger( $self->{LOGFH}, $self->{VERBOSE}, "#######################################\n" );
435 logger( $self->{LOGFH}, $self->{VERBOSE}, "## job name: $self->{JOBNAME} child pid: $pid\n" );
436 logger( $self->{LOGFH}, $self->{VERBOSE}, "#######################################\n" );
437 my $dbh = $self->{dbh};
438 my $sth = $dbh->prepare("UPDATE $controlTable SET pid = ? WHERE name = ?");
439 $sth->execute( $pid, $self->{JOBNAME} );
440  
441 #$dbh->commit();
442  
443 #$jobPids{$self->{JOBNAME}} = "$pid:running";
444  
445 #logger($self->{LOGFH},$self->{VERBOSE}, "grandChild:$pid:running\n");
446 ##
447 #logger($self->{LOGFH} ,$self->{VERBOSE}, "grancChild:$pid running job $self->{JOBNAME}\n");
448 # run the command here
449 my $startTime = getTimeStamp();
450 my @t0 = [Time::HiRes::gettimeofday]->@*;
451 $self->{updateStatus}( $self, $self->{JOBNAME}, 'running', '', $startTime, '', '' );
452 system( $self->{CMD} );
453 my $rc = $? >> 8;
454 my @t1 = [Time::HiRes::gettimeofday]->@*;
455 my $endTime = getTimeStamp();
456  
457 my $elapsedTime = sprintf( "%.6f", Time::HiRes::tv_interval( \@t0, \@t1 ) );
458  
459 if ( $rc != 0 ) {
460 logger( $self->{LOGFH}, $self->{VERBOSE}, "#######################################\n" );
461 logger( $self->{LOGFH}, $self->{VERBOSE}, "## error with $self->{JOBNAME}\n" );
462 logger( $self->{LOGFH}, $self->{VERBOSE}, "## CMD: $self->{CMD}\n" );
463 logger( $self->{LOGFH}, $self->{VERBOSE}, "#######################################\n" );
464 }
465  
466 my $jobStatus = 'complete';
467 if ( $rc == -1 ) {
468 $jobStatus = 'failed';
469 logger( $self->{LOGFH}, $self->{VERBOSE}, "!!failed to execute: $!\n" );
470 }
471 elsif ( $rc & 127 ) {
472 $jobStatus = 'error';
473 logger( $self->{LOGFH}, $self->{VERBOSE}, sprintf "!!child $pid died with signal %d, %s coredump\n", ( $rc & 127 ), ( $rc & 128 ) ? 'with' : 'without' );
474 }
475 else {
476 logger( $self->{LOGFH}, $self->{VERBOSE}, sprintf "!!child $pid exited with value %d\n", $? >> 8 );
477 }
478  
479 # it should not be necessary to pass $self here, not sure yet why it is necessary
480 $self->{updateStatus}( $self, $self->{JOBNAME}, $jobStatus, $rc, $startTime, $endTime, $elapsedTime );
481 exit $rc;
482  
483 }
484 else {
485 exit 0;
486 }
487  
488 }
489  
490 waitpid( $child, 0 );
491 return;
492 }
493  
494 1;
495  
↑ Summary