-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgridx
executable file
·1908 lines (1771 loc) · 66 KB
/
gridx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
require 5.8.0;
use strict;
use Getopt::Std;
use File::Basename; #for basename, dirname
use POSIX "sys_wait_h"; # mostly for the handy uname() function
use Cwd qw(abs_path cwd);
use Fcntl qw(:DEFAULT :seek); #mostly for the SEEK constants
use FindBin; use lib "$FindBin::Bin";
my $NORMAL_ENDING=1; #set to 0 while working, to 1 upon normal ending of script (i.e. no die())
my $USER=$ENV{USER} || POSIX::cuserid(); #it may not be there for condor workers
my $PWD=cwd(); #from Cwd module
my $PERL_BIN='/usr/bin/perl';
my $MAX_RETRIES=3; #-- how many times to try a failed task
my $F_WRKCOUNT='.wrkCount'; # count of currently running workers
my $F_ALLDONE='.all.Done.';
my $F_WRKSTART='.wrkStarted'; #count of (ever) started workers
my $F_LASTTASK='.lastTask'; # maximum task# ever started
my $F_TASKSDONE='tasksDone'; # number of tasks successfully finished
my $F_ERRTASKS='err.tasks'; #LIST of task#s which returned non-zero status
# even after MAX_RETRIES
my $F_RETRYTASKS='retry.tasks'; #stack of task#s which returned non-zero status
#less then MAX_RETRIES times
my $F_WRKRUNNING='.running-worker'; #semaphore file in each worker directory
my $F_ENDCMD='epilogue';
my $F_WRKDIR='workdir';
my $F_NOTIFY='notify';
my $F_TASKDB='taskDb';
my $GRID_DEBUG;
my $starting_dir; #the initial working directory (where gridx was launched)
my $STARTED_GRID_TASK;
my $SMPChildren=0; #SMP case: number of children running
my %SMPChildren=(); #set of child PIDs
my %Locks = (); # filehandle -> [lockfilelink, hostlockfile]
my $HOSTNAME = (&POSIX::uname)[1]; # can't trust HOST envvar under condor, because
# it will either inherit HOST and HOSTNAME from submitter env for getenv=TRUE,
# OR it will not set anything for getenv=FALSE
chomp($HOSTNAME);
$HOSTNAME=lc($HOSTNAME);
my $HOST=$HOSTNAME;
my ($DOMAIN)=($HOST=~m/^[\w\-]+\.(.+)/);
$DOMAIN='jhu.edu' unless ($DOMAIN);
($HOST)=($HOST=~m/^([\w\-]+)/);
$ENV{HOST}=$HOST;
$ENV{MACHINE}=$HOST;
$ENV{HOSTNAME}=$HOSTNAME;
$ENV{USER}=$USER;
# ===== PATH management ====
# default: assume architecture/PATH/LIB uniformity across nodes
# you can change this by adding your own worker/server paths here
my $binpath=$ENV{PATH};
my $libpath=$ENV{LD_LIBRARY_PATH};
my $perllib=$ENV{PERLLIB};
my $perl5lib=$ENV{PERL5LIB};
my $pythonpath=$ENV{PYTHONPATH};
# use home directory for symbolic links to working directories
my $homebase=$ENV{HOME};
$homebase=~s/(\/[^\/]+$)//;
#$homebase='/fs/wrenhomes' unless $homebase; #this is just valid for UMIACS here
# sometimes the HOME path is not defined within the condor job,
# please use your own globally mounted path instead
# default grid engine used:
#my $GRID_ENGINE='sge'; # can also be: 'condor' and 'smp'
#my ($GRID_MONHOME, $GRID_ENGINE) = ($DOMAIN=~/dfci/) ? ('/home', 'sge')
# : ($homebase, 'condor');
my ($GRID_ENGINE, $GRID_MONHOME) = ('smp', $homebase);
my $sysopen_mode = O_RDWR|O_CREAT|O_SYNC;
#$sysopen_mode |= O_DIRECT if $DOMAIN!~/umiacs/;
#print STDERR "|$GRID_MONHOME|\n";
#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&! -
#
my $morehints=qq{
The following entries will be created by gridx:
<GRID_JOBDIR>/epilogue - only if -e option was given, a file containing the
<end_cmd> parameter
<GRID_JOBDIR>/notify - a file containing the e-mail address to notify
if -m was given
<GRID_JOBDIR>/.lastTask - a file keeping track of the last task# scheduled
<GRID_JOBDIR>/.wrkStarted - a file keeping track of the number of
<GRID_JOBDIR>/.wrkCount - a file keeping track of the number of
currenly running workers
<GRID_JOBDIR>/err.tasks - list of all error-terminated tasks, after retry
(should be zero or empty if all tasks
finished successfully)
<GRID_JOBDIR>/retry.tasks - list of all error-terminated tasks that will
still be retried
<GRID_JOBDIR>/taskDb - pseudo-fasta db with the info & status
of each task
<GRID_JOBDIR>/taskDb.cidx - the cdbfasta index of the above db file
<GRID_JOBDIR>/locks/ - lockfiles/links are placed here
<GRID_JOBDIR>/running/ - while a task is processed, a file entry
called task_<GRID_TASK> will be created in
here for locking purposes; such file will have
a line with processing info for the current
task: <hostname> <pid> <CPU#>
<GRID_JOBDIR>/wrk_<CPU#>/ - working directory exclusive to each worker
process, one per CPU (1 <= CPU <= maxCPUs);
also contains stderr and stdout log files
for each worker process (wrk_stderr.log and
wrk_stdout.log)
* if -i option is used, a slice db file is created for <fastadb> with the
positions of all slices of <numseqs> fasta records in the <fastadb> file.
This file is called <GRID_JOBDIR>/taskDb
* if -b option was given: executes the <begin_script> in the current submit
directory (the one above <GRID_JOBDIR>)
* if all tasks completed successfully and if -e option was given
the <end_script> is executed in the <GRID_JOBDIR> subdirectory
};
my $usage=qq{
Submit a list of commands to the grid. Can also automatically
slice a multi-fasta file into chunks and pass the slice file names as
parameters to a <cmd>:
Usage:
gridx \{-f <cmds_file> | -i <fastadb> | -r <numtasks> \} -p <numprocs>
\{-U|-u <slot#>\} [-n <numseqs>] [-s <skipseqs>] [-t <totalseqs>]
[-g <engine>] [-d <dir_prefix>] [-a] [-M <monitoring_basedir>]
[-L <local_wrk_dir>] [-O <log_files_dir>] [-S] [-T] [-v]
[-x <node_exclude_list>] [-y <node_targets_list>]
[-b <begin_script>] [-e <end_script>] [-q] [-m <e-mail>]
[-c] <cmd> [-C] [<cmd_args>..]
Unless -J option is given, gridx will submit the job to the grid,
creating a <GRID_JOBDIR> subdirectory (which on Condor has the format:
gridx-<hostname>_<job_id>). A file called 'cmdline-<numtasks>.cmd'
will also be created there containing the current gridx commmand line.
Options:
-g grid engine to use, can be 'smp', 'condor' or 'sge' (default: $GRID_ENGINE)
-p maximum number of grid CPUs to allocate for this job
-f provide a file with a list of commands to be run on the grid (one
command per line per CPU)
-i grid processing of slices of the given multi-fasta file <fastadb>;
the total number of tasks/iterations is given by the number of slices
in <fastadb> (and the -n <numseqs> option); the script will
automatically create the slice file in the worker directory before
<cmd> is run with these parameters:
<fastaslice> <numseqs> <slice#> <is_last> <skipped> <total> <cmd_args>
-n slice size: for -i option, how many fasta records from <fastadb>
should be placed into a slice file for each iteration (default: 2000)
-C legacy option for psx-like usage (to pass <cmd_args>)
-r submit an array job with <numtasks> iterations/tasks (default: 1)
-S switch to (stay in) the current directory (where gridx was launched from)
before each task execution (especially useful for -f option)
-a (psx legacy): inherit the submitter environment (default)
-b prologue script to be executed BEFORE the grid job is submitted
-e epilogue script to be executed AFTER all the grid tasks were completed,
and only if ALL the tasks terminated successfully.
-m send an e-mail to the given address when all tasks are finished
-v do not try to validate <cmd> (assume it is going to be valid on the grid
nodes)
-x provide a list of machines (host names) that should be excluded
from the condor pool for this submitted job ('condor' engine only)
-y the submitted job is only allowed to run on the machines on this list
('condor' engine only)
-d create <dir_prefix> prefixed symbolic links to worker directories
in the current directory
-O place all Condor log files (condor stderr/stdout redirects)
into <log_files_dir>
-M parent directory for creating a "monitoring" symlink; a symbolic link to
the current <GRID_JOBDIR> will be created there, under
<monitoring_basedir>/$USER/ (default: home directory)
-T do not exit after the job is submitted, wait around instead
until the last worker terminates and prints some job completion stats
-U force one worker per machine (only for 'condor' engine)
-u force each worker to run only on CPU <slot#> (between 1 and 12) of each
machine (only for 'condor' engine)
For -r option, the provided <cmd> could make use of the environment variables
GRID_TASK, GRID_TASKLAST to determine the current iteration being executed.
Unless -S option was used, each <cmd> iteration will be executed in its own
worker subdirectory <GRID_JOBDIR>/wrk_<CPU#>
Job monitoring/resuming/stopping (-J mode):
gridx [-m e-mail] [-e <end_script>] [-K|-R] -J <jobID>
If -J option is provided, gridx will report the status of the job <jobID>
which must have been submitted by a previous, "regular" use of gridx; it relies
on the the symbolic link <monitor_basedir>/$USER/gridx-<jobID> which must
be valid (<monitor_basedir> can be set by -M).
Additional/alternate actions for -J mode:
-e update the <end_script> for the *running* <jobID> or for the <jobID>
rerun (if -R option is also given); does not work with -K option
-m update the e-mail notification option for job <jobID>
-K kill/abandon/terminate ALL pending tasks for grid job jobID
(trying to remove all running/pending tasks on the grid)
-R rerun/resubmit all the unfinished/unprocessed or unsuccessful tasks
for <GRID_JOB>; this assumes -K -J <JOB_ID> was given first (so there
are no pending tasks) and then will submit a new job in the same working
directory, renaming the GRID_JOBDIR accordingly while workers
will now *skip* all the tasks found with a "Done" status ('.') in the
<GRID_JOBDIR>/taskDb file
}; #'
RESUME_JOBID:
my @ar=@ARGV;
while ($ar[0] eq '-Z') { shift(@ar); shift(@ar); }
my $CMDLINE="$FindBin::Script\t".join("\t",@ar);
# parse script options
#print STDERR "Running on $HOST (domain: $DOMAIN): $0 ".join(' ',@ARGV)."\n";
getopts('USWHM:O:NKRDTqvaJZ:L:u:r:x:y:i:Ff:n:t:d:s:p:m:g:b:e:c:C:') || die($usage."\n");
umask 0002;
if ($Getopt::Std::opt_H) {
print STDERR $usage;
die($morehints."\n");
}
my $SwitchDir=$Getopt::Std::opt_S;
$NORMAL_ENDING=0;
$GRID_DEBUG=$Getopt::Std::opt_D;
#print STDERR "Host=$HOST, Domain=$DOMAIN\n" if $GRID_DEBUG;
my $GRID_DIRPREFIX=$Getopt::Std::opt_d;
my ($submitJob, $removeJob);
$GRID_ENGINE=lc($Getopt::Std::opt_g) if $Getopt::Std::opt_g;
if ($GRID_ENGINE eq 'sge') {
($submitJob, $removeJob)=(\&submitJob_sge, \&removeJob_sge);
}
elsif ($GRID_ENGINE eq 'condor') {
($submitJob, $removeJob)=(\&submitJob_condor, \&removeJob_condor);
}
elsif ($GRID_ENGINE eq 'smp') {
($submitJob, $removeJob)=(\&submitJob_smp, \&removeJob_smp);
}
else {
die("Error: invalid grid engine given (only 'sge', 'condor' or 'smp' are accepted)!\n");
}
my $UniqueVM=$Getopt::Std::opt_U;
my $UniqVMreq=$Getopt::Std::opt_u;
$UniqVMreq=int($UniqVMreq) if $UniqVMreq;
die("Error: use either -U or -u option, not both!\n") if $UniqueVM && $UniqVMreq>0;
# - exclude the following machines
my @xmachinelist=split(/\,/,$Getopt::Std::opt_x); #do NOT allow jobs to run on these machines
my @ymachinelist=split(/\,/,$Getopt::Std::opt_y); #only allow jobs to run on these machines, not others
#submitJob MUST use the globals:
# GRID_CMD, GRID_TASKLAST, GRID_MONHOME and update GRID_JOB
$GRID_MONHOME=$Getopt::Std::opt_M if $Getopt::Std::opt_M;
#$GRID_MONHOME=$ENV{HOME} unless $GRID_MONHOME;
$GRID_MONHOME.='/'.$USER unless $GRID_MONHOME=~m/$USER$/;
#
die("Error: directory $GRID_MONHOME should already be created! Aborting..\n")
unless (-d $GRID_MONHOME);
my $mailnotify=$Getopt::Std::opt_m;
#-------- GLOBALs ---------------------------
my $GRID_JOBDIR;
my $GRID_JOB;
my $GRID_LOCKDIR;
my $GRID_TASKLAST;
my $GRID_CMD; # user's command and arguments
my $GRID_CMDFILE=$Getopt::Std::opt_f; # one line per run.. with arguments for command <cmd>
my $GRID_USECMDLIST=1 if $GRID_CMDFILE || $Getopt::Std::opt_F;
my $GRID_PSXFASTA; #if -i was used
my $GRID_PSXSTEP; #if -i was used (-n value)
my $GRID_PSXSKIP=0; # -s option
my $GRID_PSXTOTAL=0; # -t option
my $GRID_NUMPROCS=0; # -p option
my $GRID_RESUME=$Getopt::Std::opt_R || $Getopt::Std::opt_Z;
my $GRID_LOCAL_JOBDIR=$Getopt::Std::opt_L;
#---------- worker side global vars:
my $GRID_ENVSET=0; #was the environment set?
my $GRID_WORKER=0; # worker#
#my $GRID_NOWRKLINKS=1;
my $GRID_LOGDIR=$Getopt::Std::opt_O;
my $GRID_TASK; # dynamic -- task iteration#
my $TASK_ERRCOUNT; # dynamic -- current task error (retry) counter
my $TASK_DATA; # current task's user data as stored in taskDb
my $TASK_LOCKH; #file handle for the current task lock file
my $TASK_LOCKF; #file name for the current task lock file
my $GRID_WRKDIR; #only for the worker case, it's the current worker's subdirectory
if ($Getopt::Std::opt_J) {
#################################################################
# gridx job monitoring use:
#---------------------------------------------------
# gridx -J [-m <e-mail>] [-M <mondir>] [-R | -K] <jobid>
#vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
my ($jobid)=shift(@ARGV);
$jobid=~tr/ //d;
unless ($jobid) { # list mode
my $fmask="$GRID_MONHOME/gridx-*";
my @jdirs=<${fmask}>;
if (@jdirs>0) {
print STDOUT "The following jobs were found (in $GRID_MONHOME):\n";
foreach (@jdirs) {
my ($jobid)=(m/gridx\-(\w[\w\-]+)$/);
print " $jobid\n";
}
}
else {
print STDOUT "No jobs were found (in $GRID_MONHOME).\n";
}
$NORMAL_ENDING=1;
exit(0);
}
#a valid $jobid was given, hopefully
$jobid=lc($jobid);
my $subdir='gridx-smp_'.$jobid;
my $jobdir="$GRID_MONHOME/gridx-smp_$jobid";
unless (-d $jobdir) { #try current directory..
if (-d $subdir) {
$jobdir=$subdir;
}
else {
die "No such job found($jobid) - neither $jobdir nor $subdir exist!\n";
}
}
#print STDERR "..found jobdir='$jobdir'\n";
chdir($jobdir) || die("Error at chdir($jobdir)!\n");
#my $msg=jobSummary($mailnotify);
my $msg=jobSummary();
print STDOUT $msg."\n";
if ($Getopt::Std::opt_K) {
&$removeJob($jobid);
}
elsif ($Getopt::Std::opt_R) { #resume/rerun!
#chdir($jobdir) || die("Error at chdir($jobdir)!\n");
my @cmdfile=<cmdline-*.cmd>;
die "Error getting the cmdline-*.cmd from current directory!\n"
unless @cmdfile;
my ($numtasks)=($cmdfile[0]=~m/cmdline\-(\d+)/);
die "Error parsing the number of tasks from $cmdfile[0]!\n" unless $numtasks>0;
my $cmdline=readFile($cmdfile[0]);
chomp($cmdline);
my @args=split(/\t/,$cmdline);
die("$jobdir/$F_TASKDB and/or index not valid - cannot resume!\n")
unless -s $F_TASKDB && -s "$F_TASKDB.cidx";
shift(@args); #discard gridx command itself
chdir('..'); #go in the original working dir
$PWD=cwd(); #from Cwd module
$CMDLINE="$FindBin::Script\t".join("\t",@args);
@ARGV=('-Z',$jobid, @args);
undef($Getopt::Std::opt_J);
undef($Getopt::Std::opt_R);
goto RESUME_JOBID;
}
$NORMAL_ENDING=1;
exit(0);
}
elsif ($Getopt::Std::opt_W) {
##########################################################
# gridx Worker use:
#---------------------------------------------------------
# This is the actual job that gets submitted
# gridx -W <cmd> <cmd_args>
# At runtime the environment should be set accordingly
#vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
beginWorker(); #set up environment and worker directory
#(wrk_NNNNN) and chdir() to it
$GRID_USECMDLIST=$Getopt::Std::opt_F;
my @cmd=@ARGV; # cmd and cmdargs
while (my $taskId = getNextTask()) {
runTask($taskId, @cmd);
}
my $runningworkers=endWorker();
my $exitcode=0;
if ($runningworkers==0) { #this was the last worker!
#run any JOB finishing/clean up code
chdir($GRID_JOBDIR);
my $epilogue=readFile($F_ENDCMD) if -s $F_ENDCMD;
if ($epilogue) {
chomp($epilogue);
#only run it if ALL tasks succeeded
my $tasksdone=readFile($F_TASKSDONE);chomp($tasksdone);
if ($tasksdone==$GRID_TASKLAST && !(-s $F_ERRTASKS)) {
runCmd($epilogue);
}
}
my $notify=readFile($F_NOTIFY) if -s $F_NOTIFY;
chomp($notify);
jobSummary($notify);
local *FDONE;
open(FDONE, '>'.$GRID_JOBDIR.'/'.$F_ALLDONE) || die("Error creating $GRID_JOBDIR/$F_ALLDONE\n");
print FDONE "done.\n";
close(FDONE);
} #last worker ending
$NORMAL_ENDING=1;
exit(0);
}# -- worker use case
##########################################################
#
# gridx Submit use:
#
##########################################################
my $gridBeginCmd=$Getopt::Std::opt_b;
my $gridEndCmd=$Getopt::Std::opt_e;
$GRID_RESUME=$Getopt::Std::opt_Z; #caused by an initial -J -R request
$GRID_TASKLAST=$Getopt::Std::opt_r;
#--submit specific globals -- temporary
my $TASKDB;
my $JOBID;
#--
unless ($GRID_CMDFILE) {
$GRID_CMD=$Getopt::Std::opt_c || shift(@ARGV);
die "$usage\nError: no command given!\n" unless $GRID_CMD;
unless ($Getopt::Std::opt_v) {
$GRID_CMD = getCmdPath($GRID_CMD) ||
die "Error: command $GRID_CMD not found in PATH!\n";
}
$GRID_CMD.=' '.$Getopt::Std::opt_C if $Getopt::Std::opt_C;
$GRID_CMD.=' '.join(' ',@ARGV) if @ARGV;
}
else {
$GRID_CMD='.';
}
$GRID_NUMPROCS=$Getopt::Std::opt_p || 1; #numer of workers submitted
if ($GRID_PSXFASTA=$Getopt::Std::opt_i) { #psx emulation case
die "Error: -r and -i are mutually exclusive options!\n" if $GRID_TASKLAST;
$GRID_PSXSTEP=$Getopt::Std::opt_n || 1;
#it will be moved into GRID_JOBDIR right after submit
$GRID_PSXSKIP=$Getopt::Std::opt_s || 0;
$GRID_PSXTOTAL=$Getopt::Std::opt_t || 0;
#$GRID_NOWRKLINKS=$Getopt::Std::opt_N;
}
else { $GRID_TASKLAST=1 unless $GRID_TASKLAST; } #one shot run
prepareTaskDb(); #builds a taskDb in the current directory for now
#checks global $GRID_PSXFASTA and $GRID_PSXSTEP
#sets TASKDB to the file name, and GRID_TASKLAST is updated as needed
if ($gridBeginCmd) {
system($gridBeginCmd) && die("Error: exit status $? returned by prologue command: '$gridBeginCmd'\n");
}
$JOBID = &$submitJob({PATH=> $binpath, PYTHONPATH=> $pythonpath,
LD_LIBRARY_PATH=>$libpath, PERLLIB=>$perllib, PERL5LIB=>$perl5lib} );
#-- submitJob should also call setupJobDir() to create the gridx-<JOBID> subdirectory
#-- and move/rename the taskDb in there.
die("Error: no job ID has been obtained!\n") unless $JOBID;
if ($Getopt::Std::opt_T) { #wait for all children to finish
my $wstat;
chdir($GRID_JOBDIR);
do {
sleep(5);
} until (-e $F_ALLDONE);
#my $msg=jobSummary($mailnotify);
my $msg=jobSummary();
my $exitcode = (-s $F_ERRTASKS) ? `wc -l $F_ERRTASKS` : 0;
chomp($exitcode);
print STDOUT $msg."\n";
chdir($PWD); #this should be the original working directory
$NORMAL_ENDING=1;
exit($exitcode);
}
$NORMAL_ENDING=1;
exit(0);
# if ($notify) {
# #qsub -o /dev/null -N "$cmd-$jobid-($numtasks)-watcher" -hold_jid $jobid -b y -j y $notify sleep 0
# my $sgecmd=`which sgepl`;
# qsub -o $GRID_MONHOME/.gridjob_$jobid/watcher.log -N "$cmdname-$jobid-($numtasks)-watcher" \
# -hold_jid $jobid -b y -j y -V /bin/tcsh -f $sgecmd -Done $cmdname $jobid $numtasks
# echo "Submitted watchdog job $cmdname-$jobid-($numtasks)-watcher:"
# echo " $sgecmd -Done $cmdname $jobid $numtasks"
# }
#**********************************************************
#******************* SUBROUTINES **************************
#******************** SUBMIT SIDE *************************
=head2 ----------- taskDbRec -----------
taskDbRec($fhdb, $jobId, $command_line..)
Creates (writes) a record into the taskDb file open for writing
with the file handle $fhdb. This subroutine takes care of
formatting the fixed length defline (header) of the job record.
This subroutine should only be used by the program which
creates the taskDb. After all the records are added to the taskDb;
the taskDb should be eventually indexed with cdbfasta.
=cut
sub taskDbRec {
my ($fh, $taskId, @userdata)=@_;
my $rec='>'.$taskId."\t{-|-|----|----|--------}\t{".('-' x 25).'}';
$rec.="\t".join(' ',@userdata) if @userdata;
print($fh $rec."\n");
}
sub prepareTaskDb {
if ($GRID_PSXFASTA) { #-i given, psx mode
$GRID_PSXFASTA=getFullPath($GRID_PSXFASTA, 1);
die ("Error: prepareTaskDb() called with PSXFASTA but no PSXSTEP!\n")
unless $GRID_PSXSTEP;
my $basename=getFName($GRID_PSXFASTA);
$TASKDB='gridx-psx-'.$basename.
".n$GRID_PSXSTEP.s$GRID_PSXSKIP.t$GRID_PSXTOTAL".'.taskDb';
if ($GRID_RESUME) {
#taskDb must already be there!
my $r=`cdbyank -s gridx-$GRID_RESUME/taskDb.cidx`;
($GRID_TASKLAST)=($r=~m/\nNumber of records:\s+(\d+)\n/s);
die "Error: couldn't determine number of records in gridx-$GRID_RESUME/taskDb\n"
unless $GRID_TASKLAST>0;
return;
}
#-- iterate through the fasta file, create slice index
# and the index for the slice index..
local *TASKDB;
local *PSXFASTA;
open(PSXFASTA, $GRID_PSXFASTA) || die "Error opening file $GRID_PSXFASTA\n";
binmode(PSXFASTA);
open(TASKDB, '>'.$TASKDB) || die "Error creating file $TASKDB ($!)\n";
my $foffset=0;
my $rcount=0;
my $numrecs=0;
$GRID_TASKLAST=0;
while (<PSXFASTA>) {
my $linelen=length($_);
if (/^>/) {
$rcount++;
if ($rcount>$GRID_PSXSKIP) {
$numrecs++;
if (($numrecs-1) % $GRID_PSXSTEP == 0) {
$GRID_TASKLAST++;
taskDbRec(\*TASKDB, $GRID_TASKLAST, $foffset);
}
}
last if ($GRID_PSXTOTAL>0 && $numrecs>$GRID_PSXTOTAL);
}
$foffset+=$linelen;
}
close(PSXFASTA);
#&taskdbRec(\*TASKDB, $GRID_TASKLAST, $foffset)
# unless ($numrecs-1) % $GRID_PSXSTEP == 0;
close(TASKDB);
}
elsif ($GRID_CMDFILE) { # -f option given
return if ($GRID_RESUME); #taskDb must already be there!
my ($cmdname)=($GRID_CMDFILE=~m/([^\/+]+)$/);
$cmdname=~s/\.\w+$//;
$TASKDB="gridx.$cmdname.taskDb";
local *TASKDB;
open(CMDFILE, $GRID_CMDFILE) || die "Error opening file $GRID_CMDFILE\n";
open(TASKDB, '>'.$TASKDB) || die "Error creating file $TASKDB ($!)\n";
my $i=1;
while(<CMDFILE>) {
next if m/^\s*#/;
chomp;
taskDbRec(\*TASKDB, $i, $_);
$i++;
}
close(TASKDB);
close(CMDFILE);
$GRID_TASKLAST=$i-1;
}
elsif ($GRID_TASKLAST) { # -r option given
return if ($GRID_RESUME); #taskDb must already be there!
$TASKDB="gridx.r$GRID_TASKLAST.taskDb";
local *TASKDB;
open(TASKDB, '>'.$TASKDB) || die "Error creating file $TASKDB ($!)\n";
for (my $i=1;$i<=$GRID_TASKLAST;$i++) {
taskDbRec(\*TASKDB, $i, $GRID_CMD);
}
close(TASKDB);
}
else { return; }
runCmd("cdbfasta $TASKDB");
}
sub getFName {
return basename($_[0]);
}
sub getFDir {
return dirname($_[0]);
}
sub getFullPath {
my ($fname, $check)=@_;
die("Error: file $fname does not exist!\n") if $check && !-r $fname;
return abs_path($fname); #Cwd module
}
#== getCmdPath -- checks for executable in the PATH if no full path given
# tests if the executable is a text file and interpreter was requested
sub getCmdPath {
my $cmd=$_[0];
my $fullpath;
my $checkBinary=wantarray();
if ($cmd =~ m/^\//) {
$fullpath = (-x $cmd) ? $cmd : '';
}
elsif ($cmd =~ m/^\.+\//) { #relative path given
$fullpath= (-x $cmd) ? abs_path($cmd) : '';
}
else { #we search in the path..
my @paths=split(/:/, $ENV{'PATH'});
foreach my $p (@paths) {
if (-x $p.'/'.$cmd) {
$fullpath=$p.'/'.$cmd;
last;
}
}
}#path searching
if ($checkBinary) { #asked for interpreter, if any
if ($fullpath) {
my $interpreter='';
if (-r $fullpath && -T $fullpath) {#readable text file, look for bang line
open(TFILE, $fullpath);
my $linesread=1;
while ($linesread<10) {#read only the first 10 lines..
$_=<TFILE>;
chomp;
if (m/^\s*#\!\s*(\S.+)/) {
$interpreter=$1;
last;
}
$linesread++;
}
$interpreter=~s/\s+$//;
}
return ($fullpath, $interpreter);
}
else { return (); } #cmd not found;
}
else { return $fullpath; }
}
sub runCmd {
my ($cmd, $jobid)=@_;
my $exitstatus=system($cmd);
if ($exitstatus != 0) {
if ($jobid) {
&$removeJob($jobid);
}
die("Error at running system command: $cmd\n");
}
}
sub removeJob_sge {
my $jobid=shift(@_);
runCmd("qdel -f $jobid");
}
sub removeJob_condor {
my $jobid=shift(@_); #machine+'_'+job#
#must be on the same machine that submit was issuedlh
my ($hostname, $job)=($jobid=~m/([\w\-]+)_(\d+)$/);
die("Error parsing hostname, job# from $jobid!\n")
unless $hostname && ($job>0);
#print STDERR "$hostname, $HOST, $jobid, $job\n";
if (lc($hostname) eq lc($HOST)) { #local host
runCmd("condor_rm $job");
}
else {
runCmd("condor_rm -name $hostname $job");
}
}
sub smpTaskReaper {
# takes care of dead children $SIG{CHLD} = \&taskReaper;
my $childpid;
while (($childpid = waitpid(-1, WNOHANG)) > 0) {
$SMPChildren --;
delete $SMPChildren{$childpid};
}
$SIG{CHLD}=\&smpTaskReaper;
}
sub smpTaskKiller { # signal handler for SIGINT
local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
print STDERR timeStamp()." ($$) received TERM kill, send kill INT all children\n";
kill 'INT' => keys %SMPChildren;
}
sub smpTaskKillerINT { # signal handler for SIGINT
local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
print STDERR timeStamp()." ($$) received INT kill, send kill INT all children\n";
kill 'INT' => keys %SMPChildren;
}
sub removeJob_smp {
smpTaskKiller();
}
sub submitJob_sge {
my ($envhash)=@_;
# submit and array job, SGE style
my $array='';
if ($GRID_NUMPROCS > 1) {
$array="-t 1-$GRID_NUMPROCS";
}
#append our GRID_ environment
my $envparam="-v 'GRID_ENGINE=sge,".
"GRID_JOBDIR=$PWD,".
"GRID_TASKLAST=$GRID_TASKLAST,".
"GRID_MONHOME=$GRID_MONHOME,".
"GRID_CMD=$GRID_CMD,".
"GRID_DIRPREFIX=$GRID_DIRPREFIX";
$envparam.=",GRID_RESUME=$GRID_RESUME" if $GRID_RESUME;
$envparam.=",GRID_PSXFASTA=$GRID_PSXFASTA".
",GRID_PSXSTEP=$GRID_PSXSTEP" if $GRID_PSXFASTA;
$envparam.= ",GRID_PSXSKIP=$GRID_PSXSKIP" if $GRID_PSXSKIP;
$envparam.= ",GRID_PSXTOTAL=$GRID_PSXTOTAL" if $GRID_PSXTOTAL;
$envparam.= ",GRID_LOCAL_JOBDIR=$GRID_LOCAL_JOBDIR" if $GRID_LOCAL_JOBDIR;
if (keys(%$envhash)>0) {
$envparam.=',';
my @envars;
while (my ($env, $val)= each(%$envhash)) {
push(@envars, $env.'='.$val);
}
#$envparam.=" '".join(',',@envars)."'";
$envparam.=join(',',@envars);
}
$envparam.="'";
#--
my $sub="qsub -cwd -b y $envparam";
#$sub.="-e $errout" if $errout;
#$sub.="-o $stdout" if $stdout;
my $logdir='';
if ($GRID_LOGDIR) {
#separate log dir given
$logdir=$GRID_LOGDIR;
if (-d $GRID_LOGDIR) {
print STDERR "Warning: log dir $GRID_LOGDIR exists; existing files will be overwritten!\n";
}
else {
mkdir($logdir) || die("Error creating log dir '$logdir'!\n");
}
$logdir.='/' unless $logdir=~m/\/$/;
}
my $otherflags='';
$otherflags.=' -D' if $GRID_DEBUG;
#$otherflags.=' -N' if $GRID_NOWRKLINKS;
$otherflags.=' -F' if $GRID_USECMDLIST;
$otherflags.=' -S' if $SwitchDir;
my $subcmd= "$sub $array $PERL_BIN $0 $otherflags -W $GRID_CMD";
print STDERR "$subcmd\n" if $GRID_DEBUG;
my $subout = `$subcmd`;
#print STDOUT $subout;
#my ($jobid)=($subout=~/Your\s+job\S*\s+(\d+)/s);
my ($jobid)=($subout=~/Your\s+job\S*\s+(\d+)/s);
die "Error: No Job ID# could be parsed!\n($subout)" unless ($jobid);
setupJobDir($jobid);
return $jobid;
}
sub submitJob_smp {
my ($envhash)=@_;
my $jobid='smp_'.$$;
$ENV{GRID_ENGINE}='smp';
@ENV{'GRID_JOBDIR', 'GRID_TASKLAST', 'GRID_MONHOME', 'GRID_CMD','GRID_DIRPREFIX'}=
($PWD."/gridx-$jobid", $GRID_TASKLAST, $GRID_MONHOME, $GRID_CMD,$GRID_DIRPREFIX);
$ENV{GRID_RESUME}=$GRID_RESUME;
$ENV{GRID_JOB}=$jobid;
@ENV{'GRID_PSXFASTA','GRID_PSXSTEP'}=($GRID_PSXFASTA, $GRID_PSXSTEP) if $GRID_PSXFASTA;
$ENV{GRID_PSXSKIP}=$GRID_PSXSKIP if $GRID_PSXSKIP;
$ENV{GRID_PSXTOTAL}=$GRID_PSXTOTAL if $GRID_PSXTOTAL;
$ENV{GRID_LOCAL_JOBDIR}=$GRID_LOCAL_JOBDIR."/gridx-$jobid" if $GRID_LOCAL_JOBDIR;
if (keys(%$envhash)>0) {
while (my ($env, $val)= each(%$envhash)) {
$ENV{$env}=$val;
}
}
# Fork off the children
my $pid;
setupJobDir($jobid); #we do this one in advance..
$SIG{CHLD}=\&smpTaskReaper;
print STDERR "..forking $GRID_NUMPROCS workers..\n" if $GRID_DEBUG;
my $logdir='';
if ($GRID_LOGDIR) {
#separate log dir given
$logdir=$GRID_LOGDIR;
if (-d $GRID_LOGDIR) {
print STDERR "Warning: log dir $GRID_LOGDIR exists; existing files will be overwritten!\n";
}
else {
mkdir($logdir) || die("Error creating log dir '$logdir'!\n");
}
$logdir.='/' unless $logdir=~m/\/$/;
}
my $otherflags;
$otherflags=' -D' if $GRID_DEBUG;
#$otherflags.=' -N' if $GRID_NOWRKLINKS;
$otherflags.=' -F' if $GRID_USECMDLIST;
$otherflags.=' -S' if $SwitchDir;
for (1 .. $GRID_NUMPROCS) {
die "Error at fork: $!" unless defined ($pid = fork);
if ($pid) { # Parent here
$SMPChildren{$pid} = 1;
$SMPChildren++;
next;
} else { #Child here
# Child can *not* return from this subroutine.
#$SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
exec("$PERL_BIN $0 $otherflags -W $GRID_CMD"); #never returns
}
}
$SIG{INT}=\&smpTaskKillerINT;
$SIG{TERM}=\&smpTaskKiller;
return $jobid;
}
sub submitJob_condor {
my ($envhash)=@_;
my $jobid;
my $queue='queue';
$queue.=" $GRID_NUMPROCS" if ($GRID_NUMPROCS > 1);
#append our GRID_ environment
my $dprefix="gridx-$HOST".'_';
my $envparam="GRID_ENGINE=condor;".
"GRID_JOBDIR=$PWD/$dprefix\$(Cluster);".
"GRID_JOB=$HOST\_\$(Cluster);".
"GRID_TASKLAST=$GRID_TASKLAST;".
"GRID_MONHOME=$GRID_MONHOME;".
"GRID_CMD=$GRID_CMD;".
"GRID_DIRPREFIX=$GRID_DIRPREFIX";
$envparam.=";GRID_RESUME=$GRID_RESUME" if $GRID_RESUME;
$envparam.=";GRID_PSXFASTA=$GRID_PSXFASTA".
";GRID_PSXSTEP=$GRID_PSXSTEP" if $GRID_PSXFASTA;
$envparam.= ";GRID_PSXSKIP=$GRID_PSXSKIP" if $GRID_PSXSKIP;
$envparam.= ";GRID_PSXTOTAL=$GRID_PSXTOTAL" if $GRID_PSXTOTAL;
$envparam.=';BLASTMAT='.$ENV{BLASTMAT} if $ENV{BLASTMAT};
$envparam.= ";GRID_LOCAL_JOBDIR=$GRID_LOCAL_JOBDIR/$dprefix\$(Cluster);" if $GRID_LOCAL_JOBDIR;
if (keys(%$envhash)>0) {
$envparam.=';';
my @envars;
while (my ($env, $val)= each(%$envhash)) {
push(@envars, $env.'='.$val);
}
$envparam.=join(';',@envars);
}
my $logdir='';
if ($GRID_LOGDIR) {
#separate log dir given
$logdir=$GRID_LOGDIR;
if (-d $GRID_LOGDIR) {
print STDERR "Warning: log dir $GRID_LOGDIR exists; existing files will be overwritten!\n";
}
else {
mkdir($logdir) || die("Error creating log dir '$logdir'!\n");
}
$logdir.='/' unless $logdir=~m/\/$/;
}
my $otherflags;
$otherflags=' -D' if $GRID_DEBUG;
#$otherflags.=' -N' if $GRID_NOWRKLINKS;
$otherflags.=' -F' if $GRID_USECMDLIST;
$otherflags.=' -S' if $SwitchDir;
my $mtime=time();
my $cmdfile="condor.$$.t$mtime.$USER.$HOST.cmd";
local *CMDFILE;
open(CMDFILE, '>'.$cmdfile) || die "Cannot create $cmdfile!\n";
my $requirements = '(OpSys == "LINUX") && (Arch == "INTEL" || Arch == "x86_64")';
#my $requirements = '(OpSys == "LINUX") && (Arch == "INTEL")';
my $force_slot;
if ($UniqVMreq>0) {
$force_slot=$UniqVMreq;
}
elsif ($UniqueVM) {
$force_slot=3+int(rand(9)); #this is messed up, only works on >11 core machines
}
$requirements .= ' && (VirtualMachineId == '.$force_slot.')' if $force_slot;
if (@xmachinelist>0) {
#map { $_='Machine != "'.$_.'.'.$DOMAIN.'"' } @xmachinelist;
#$requirements.= ' && ('.join(' && ',@xmachinelist).')';
if (@xmachinelist==1 && ($xmachinelist[0]=~tr/|^?*\\//)) {
$requirements.=' && (TRUE != regexp("'.$xmachinelist[0].'", Machine, "i"))';
}
else {
$requirements.=' && (TRUE != regexp("^('.join('|',@xmachinelist).
')\..*", Machine, "i"))'
}
}
elsif (@ymachinelist>0) {
if (@ymachinelist==1 && ($ymachinelist[0]=~tr/|^?*\\//)>0) {
$requirements.=' && regexp("'.$ymachinelist[0].'", Machine, "i")';
}
else {
#map { $_='Machine == "'.$_.'.'.$DOMAIN.'"' } @ymachinelist;
#$requirements.= ' && ('.join(' || ',@ymachinelist).')';
$requirements.=' && regexp("^('.join('|',@ymachinelist).
')\..*", Machine, "i")'
}
}
print CMDFILE qq{universe = vanilla
requirements = $requirements
notification = Never
executable = $0
initialdir = $PWD
};
if ($logdir) {
print CMDFILE "error = ${logdir}log_$dprefix\$(Cluster).\$(Process).stderr\n".
"output = ${logdir}log_$dprefix\$(Cluster).\$(Process).stdout\n";
}
print CMDFILE "arguments = $otherflags -W $GRID_CMD\n".
"environment = $envparam;\n".
"$queue\n";
close(CMDFILE);
my $subcmd="condor_submit $cmdfile";
my $subout = `$subcmd`;
($jobid)=($subout=~/submitted\s+to\s+cluster\s+(\d+)\./s);
die "Error: No Job ID# could be parsed!\n($subout)" unless ($jobid);
$jobid=$HOST.'_'.$jobid;
setupJobDir($jobid);
#setupJobDir also chdirs() in the $GRID_JOBDIR
system("mv ../$cmdfile condor_submit.cmd");
return $jobid;
}
sub jobDie {
my $jobid=shift @_;
print STDERR 'Error: '.timeStamp().' '.join("\n",@_)."\n";
&$removeJob($jobid);
die();
}
sub setupJobDir {
my ($jobid)=@_;
my $jobdir = "gridx-$jobid";
jobDie($jobid, "job directory $jobdir already exists!")
if (-d $jobdir);
if ($GRID_RESUME) {
my $prevjobdir='gridx-'.$GRID_RESUME;
print STDERR " ..taking over jobdir: $prevjobdir\n";
unlink("$GRID_MONHOME/$prevjobdir") || warn(" couldn't unlink $GRID_MONHOME/$prevjobdir");
unlink("$prevjobdir/$F_LASTTASK");
unlink("$prevjobdir/$F_ALLDONE");
rename("$prevjobdir/$F_ERRTASKS", "$prevjobdir/prev_$F_ERRTASKS");
unlink("$prevjobdir/$F_RETRYTASKS");
system("/bin/rm -rf $prevjobdir/wrk_*/$F_WRKRUNNING");
system("/bin/rm -rf $prevjobdir/.wrk*");
system("/bin/rm -rf $prevjobdir/locks");
system("/bin/rm -rf $prevjobdir/running");
system("mv $prevjobdir $jobdir") &&
jobDie($jobid, "cannot 'mv $prevjobdir $jobdir' - $! - Resuming failed!");
}
else {
mkdir($jobdir) || jobDie($jobid, "cannot create subdirectory $jobdir");
runCmd("mv $TASKDB $jobdir/taskDb", $jobid);
runCmd("mv $TASKDB.cidx $jobdir/taskDb.cidx", $jobid);
}
mkdir("$jobdir/locks") || jobDie($jobid,
"cannot create subdirectory $jobdir/locks");
mkdir("$jobdir/running") || jobDie($jobid,
"cannot create subdirectory $jobdir/running");
if ($GRID_MONHOME ne $PWD) {
symlink("$PWD/$jobdir", "$GRID_MONHOME/$jobdir")
|| jobDie($jobid, "cannot symlink $GRID_MONHOME/$jobdir");
}
#- CHDIR to the new GRID_JOBDIR
chdir($jobdir) || jobDie($jobid, "cannot chdir($jobdir) (from $PWD)!");
readFile($F_TASKSDONE);
my $cmdfile="cmdline-$GRID_TASKLAST.cmd";
local *FHND;
open(FHND, ">$cmdfile") || jobDie($jobid, "cannot create file $cmdfile\n");
print FHND $CMDLINE."\n";
close(FHND);
open(FHND, ">$F_WRKDIR");
print FHND "$PWD/$jobdir\n";
close(FHND);
if ($mailnotify) {
open(FHND, ">$F_NOTIFY");
print FHND "$mailnotify\n";
close(FHND);
}
if ($gridEndCmd) {
open(FHND, ">$F_ENDCMD") || die("Error creating file $jobdir/.$F_ENDCMD ($!)\n");
print FHND $gridEndCmd."\n";
close(FHND);
}
$GRID_JOBDIR = "$PWD/$jobdir";
print STDOUT "Job $jobid scheduled to run with GRID_JOBDIR = $PWD/$jobdir\n";