-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgluex_MC.py
executable file
·1971 lines (1669 loc) · 112 KB
/
gluex_MC.py
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/python
##########################################################################################################################
#
# 2017/03 Thomas Britton
#
# Options:
# MC variation can be changed by supplying "variation=xxxxx" option otherwise default: mc
# the number of events to be generated per file (except for any remainder) can be set by "per_file=xxxx" default: 1000
#
# If the user does not want genr8, geant, smearing, reconstruction to be performed the sequence will be terminated at the first instance of genr8=0,geant=0,mcsmear=0,recon=0 default: all on
# Similarly, if the user wishes to retain the files created by any step you can supply the cleangenr8=0, cleangeant=0, cleanmcsmear=0, or cleanrecon=0 options. By default all but the reconstruction files # are cleaned.
#
# The reconstruction step is multi-threaded, for this step, if enabled, the script will use 4 threads. This threading can be changed with the "numthreads=xxx" option
#
# By default the job will run interactively in the local directory. If the user wishes to submit the jobs to swif the option "swif=1" must be supplied.
#
# SWIF DOCUMENTATION:
# https://scicomp.jlab.org/docs/swif
# https://scicomp.jlab.org/docs/swif-cli
# https://scicomp.jlab.org/help/swif/add-job.txt #consider phase!
#
##########################################################################################################################
from os import environ
from optparse import OptionParser
import os.path
import rcdb
import ccdb
import ccdb.path_utils
from ccdb import Directory, TypeTable, Assignment, ConstantSet
from array import array
from datetime import datetime
import mysql.connector
import time
import os
import getpass
import sys
import re
import subprocess
from subprocess import call
import glob
import hddm_s
import socket
try:
dbcnx = mysql.connector.connect(user='mcuser', database='gluex_mc', host='hallddb.jlab.org')
dbcursor = dbcnx.cursor()
except:
pass
MCWRAPPER_VERSION="2.10.1"
MCWRAPPER_DATE="09/26/24"
#group sync test
#====================================================
#Takes in a few pertinant pieces of info. Creates (if needed) a swif workflow and adds a job to it.
#if project ID is less than 0 its an attempt ID and is recorded as such
#if project ID is greater than 0 then it is a project ID and this call is going to record a new job (NOT ACTUALLY MAKING THE ATTEMPT)
#if project ID == 0 then it is neither and just scrape the batch_ID....do nothing. Note: this scheme requires the first id in the tables to be 1 and not 0)
#====================================================
def BundleJob(job_id):
bundle_query="select ID,FileNumber from Jobs where Project_ID in (SELECT Project_ID from Jobs where ID="+str(job_id)+") and RunNumber in (SELECT RunNumber from Jobs where ID="+str(job_id)+") and NumEvts in (SELECT NumEvts from Jobs where ID="+str(job_id)+") and IsActive=1;"
dbcursor.execute(bundle_query)
alljobs = dbcursor.fetchall()
print("count:",len(alljobs))
print(alljobs)
return alljobs
#====================================================
#simple function to email Project owner that their requested Project contains no events and set the Project.Tested to -2
#====================================================
def email_no_events(PROJECT_ID):
email_query="select Email from Projects where ID="+str(PROJECT_ID)+";"
dbcursor.execute(email_query)
allemails = dbcursor.fetchall()
if len(allemails)==1:
Project_update_q="update Projects set Tested=-2 where ID="+str(PROJECT_ID)+";"
dbcursor.execute(Project_update_q)
dbcnx.commit()
def swif_add_job(WORKFLOW, RUNNO, FILENO,SCRIPT,COMMAND, VERBOSE,PROJECT,TRACK,NCORES,DISK,RAM,TIMELIMIT,OS,DATA_OUTPUT_BASE_DIR, PROJECT_ID):
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNO) + "_" + str(FILENO)
JOBNAME = WORKFLOW + "_" + STUBNAME
# CREATE ADD-JOB COMMAND
# job
#try removing the name specification
mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
status = subprocess.call(mkdircom, shell=True)
add_command = "swif add-job -workflow " + WORKFLOW #+ " -name " + JOBNAME
# project/track
add_command += " -project " + PROJECT + " -track " + TRACK
# resources
add_command += " -create -cores " + NCORES + " -disk " + DISK + " -ram " + RAM + " -time " + TIMELIMIT + " -os " + OS
# stdout
add_command += " -stdout " + DATA_OUTPUT_BASE_DIR + "/log/" + str(RUNNO) + "_stdout." + STUBNAME + ".out"
# stderr
add_command += " -stderr " + DATA_OUTPUT_BASE_DIR + "/log/" + str(RUNNO) + "_stderr." + STUBNAME + ".err"
# tags
add_command += " -tag run_number " + str(RUNNO)
# tags
add_command += " -tag file_number " + str(FILENO)
# script with options command
add_command += " -fail-save-dir "+DATA_OUTPUT_BASE_DIR
add_command += " "+SCRIPT +" "+ getCommandString(COMMAND,"SWIF")
if(VERBOSE == True):
print( "job add command is \n" + str(add_command))
if(int(NCORES)==1 and int(RAM[:-2]) >= 10 and RAM[-2:]=="GB" ):
print( "SciComp has a limit on RAM requested per thread, as RAM is the limiting factor.")
print( "This will likely cause an AUGER-SUBMIT error.")
print( "Please either increase NCORES or decrease RAM requested and try again.")
exit(1)
# ADD JOB
if add_command.find(';')!=-1 or add_command.find('&')!=-1 :#THIS CHECK HELPS PROTECT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
#status = subprocess.call(add_command.split(" "))
SWIF_ID_NUM="-1"
if( int(PROJECT_ID) <=0 ):
print(add_command)
jobSubout=subprocess.check_output(add_command.split(" "))
print(jobSubout.decode())
idnumline=jobSubout.decode().split("\n")[0].strip().split("=")
if(len(idnumline) == 2 ):
SWIF_ID_NUM=str(idnumline[1])
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENO,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"SWIF",SWIF_ID_NUM,COMMAND['num_events'],NCORES,RAM)
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENO,"SWIF",SWIF_ID_NUM,COMMAND['num_events'],NCORES,RAM)
def swif2_add_job(WORKFLOW, RUNNO, FILENO,SCRIPT,COMMAND, VERBOSE,ACCOUNT,PARTITION,NCORES,DISK,RAM,TIMELIMIT,OS,DATA_OUTPUT_BASE_DIR,LOG_DIR, PROJECT_ID):
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNO) + "_" + str(FILENO)
JOBNAME = WORKFLOW + "_" + STUBNAME
# CREATE ADD-JOB COMMAND
# job
#try removing the name specification
mkdircom="mkdir -p "+LOG_DIR+"/log/"
status = subprocess.call(mkdircom, shell=True)
add_command = "swif2 add-job -workflow " + WORKFLOW #+ " -name " + JOBNAME
# account/partition (used to be project/track in swif)
add_command += " -account " + ACCOUNT + " -partition " + PARTITION
# resources
add_command += " -create -cores " + NCORES + " -disk " + DISK + " -ram " + RAM + " -time " + TIMELIMIT + " -os " + OS
# stdout
add_command += " -stdout " + LOG_DIR + "/log/" + str(RUNNO) + "_stdout." + STUBNAME + ".out"
# stderr
add_command += " -stderr " + LOG_DIR + "/log/" + str(RUNNO) + "_stderr." + STUBNAME + ".err"
# tags
add_command += " -tag run_number " + str(RUNNO)
# tags
add_command += " -tag file_number " + str(FILENO)
# script with options command
# add_command += " -fail-save-dir "+DATA_OUTPUT_BASE_DIR
add_command += " "+SCRIPT +" "+ getCommandString(COMMAND,"SWIF")
if(VERBOSE == True):
print( "job add command is \n" + str(add_command))
if(int(NCORES)==1 and int(RAM[:-2]) >= 10 and RAM[-2:]=="GB" ):
print( "SciComp has a limit on RAM requested per thread, as RAM is the limiting factor.")
print( "This will likely cause an AUGER-SUBMIT error.")
print( "Please either increase NCORES or decrease RAM requested and try again.")
exit(1)
# ADD JOB
if add_command.find(';')!=-1 or add_command.find('&')!=-1 :#THIS CHECK HELPS PROTECT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
#status = subprocess.call(add_command.split(" "))
SWIF_ID_NUM="-1"
if( int(PROJECT_ID) <=0 ):
print(add_command)
jobSubout=subprocess.check_output(add_command.split(" "))
print(jobSubout.decode())
idnumline=jobSubout.decode().split("\n")[0].strip().split("=")
if(len(idnumline) == 2 ):
SWIF_ID_NUM=str(idnumline[1])
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENO,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"SWIF",SWIF_ID_NUM,COMMAND['num_events'],NCORES,RAM)
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENO,"SWIF",SWIF_ID_NUM,COMMAND['num_events'],NCORES,RAM)
def swif2cont_add_job(WORKFLOW, RUNNO, FILENO,SCRIPT,COMMAND, VERBOSE,ACCOUNT,PARTITION,NCORES,DISK,RAM,TIMELIMIT,OS,DATA_OUTPUT_BASE_DIR,LOG_DIR, PROJECT_ID):
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNO) + "_" + str(FILENO)
JOBNAME = WORKFLOW + "_" + STUBNAME
# CREATE ADD-JOB COMMAND
# job
#try removing the name specification
mkdircom="mkdir -p "+LOG_DIR+"/log/"
status = subprocess.call(mkdircom, shell=True)
add_command = "swif2 add-job -workflow " + WORKFLOW #+ " -name " + JOBNAME
# account/partition (used to be project/track in swif)
add_command += " -account " + ACCOUNT + " -partition " + PARTITION
# resources
add_command += " -create -cores " + NCORES + " -disk " + DISK + " -ram " + RAM + " -time " + TIMELIMIT + " -os " + OS
# stdout
add_command += " -stdout " + LOG_DIR + "/log/" + str(RUNNO) + "_stdout." + STUBNAME + ".out"
# stderr
add_command += " -stderr " + LOG_DIR + "/log/" + str(RUNNO) + "_stderr." + STUBNAME + ".err"
# tags
add_command += " -tag run_number " + str(RUNNO)
# tags
add_command += " -tag file_number " + str(FILENO)
# script with options command
# add_command += " -fail-save-dir "+DATA_OUTPUT_BASE_DIR
add_command += " singularity exec --bind /scigroup/mcwrapper/ --bind /u --bind /group/halld/ --bind /scratch/slurm/ --bind /lustre/enp/swif2 --bind /cvmfs --bind /work/osgpool/ --bind /work/halld --bind /cache/halld --bind /volatile/halld --bind /work/halld2 /cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1 "+SCRIPT +" "+getCommandString(COMMAND,"SWIF")
# print(getCommandString(COMMAND,"SBATCH_SLURM"))
# add_command += " "+SCRIPT +" "+ getCommandString(COMMAND,"SWIF")
if(VERBOSE == True):
print( "job add command is \n" + str(add_command))
if(int(NCORES)==1 and int(RAM[:-2]) >= 10 and RAM[-2:]=="GB" ):
print( "SciComp has a limit on RAM requested per thread, as RAM is the limiting factor.")
print( "This will likely cause an AUGER-SUBMIT error.")
print( "Please either increase NCORES or decrease RAM requested and try again.")
exit(1)
# ADD JOB
if add_command.find(';')!=-1 or add_command.find('&')!=-1 :#THIS CHECK HELPS PROTECT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
#status = subprocess.call(add_command.split(" "))
SWIF_ID_NUM="-1"
if( int(PROJECT_ID) <=0 ):
print(add_command)
jobSubout=subprocess.check_output(add_command.split(" "))
print(jobSubout.decode())
idnumline=jobSubout.decode().split("\n")[0].strip().split("=")
if(len(idnumline) == 2 ):
SWIF_ID_NUM=str(idnumline[1])
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENO,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"SWIF",SWIF_ID_NUM,COMMAND['num_events'],NCORES,RAM)
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENO,"SWIF",SWIF_ID_NUM,COMMAND['num_events'],NCORES,RAM)
#====================================================
#Takes in a few pertinant pieces of info and submits a job to qsub. This has not been fully integrated into the autonomous side
#missing the batch_ID scraping. And missing better host recording (Stubbed as "QSUB" for now)
#====================================================
def qsub_add_job(VERBOSE, WORKFLOW, RUNNUM, FILENUM, SCRIPT_TO_RUN, COMMAND, NCORES, DATA_OUTPUT_BASE_DIR, TIMELIMIT, RUNNING_DIR, MEMLIMIT, QUEUENAME, LOG_DIR, PROJECT_ID ):
#name
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNUM) + "_" + str(FILENO)
JOBNAME = WORKFLOW + "_" + STUBNAME
sub_command="qsub MCqsub.submit"
qsub_ml_command=""
bits=NCORES.split(":")
if (len(bits)==3):
qsub_ml_command ="nodes="+bits[0]+":"+bits[1]+":ppn="+bits[2]
elif (len(bits)==2):
qsub_ml_command ="nodes="+bits[0]+":ppn="+bits[1]
shell_to_use="/bin/bash"
if (SCRIPT_TO_RUN[len(SCRIPT_TO_RUN)-3]=='c'):
shell_to_use="/bin/csh"
if( ".iu.edu" in socket.gethostname() and QUEUENAME.upper() == "STANLEY"):
f=open('MCqsub.submit','w')
f.write("#$ -o "+LOG_DIR+"/log/"+JOBNAME+".out"+"\n" )
f.write("#$ -N "+JOBNAME+"\n" )
f.write("#$ -j y\n" )
f.write(shell_to_use+indir+" "+COMMAND+"\n" )
f.write("exit 0\n")
f.close()
else:
f=open('MCqsub.submit','w')
f.write("#!/bin/sh -f"+"\n" )
f.write("#PBS"+" -N "+JOBNAME+"\n" )
f.write("#PBS"+" -l "+qsub_ml_command+"\n" )
f.write("#PBS"+" -o "+LOG_DIR+"/log/"+JOBNAME+".out"+"\n" )
f.write("#PBS"+" -e "+LOG_DIR+"/log/"+JOBNAME+".err"+"\n" )
f.write("#PBS"+" -l walltime="+TIMELIMIT+"\n" )
if (QUEUENAME != "DEF"):
f.write("#PBS"+" -q "+QUEUENAME+"\n" )
f.write("#PBS"+" -l mem="+MEMLIMIT+"\n" )
f.write("#PBS"+" -m a"+"\n" )
f.write("#PBS"+" -p 0"+"\n" )
f.write("#PBS -c c=2 \n")
f.write("NCPU=\\ \n")
f.write("NNODES=\\ \n")
# f.write("trap \'\' 2 9 15 \n" )
f.write(shell_to_use+" "+SCRIPT_TO_RUN+" "+getCommandString(COMMAND,"PBS")+"\n" )
f.write("exit 0\n")
f.close()
time.sleep(0.25)
if ( DATA_OUTPUT_BASE_DIR != LOG_DIR ) :
status = subprocess.call("mkdir -p "+LOG_DIR+"/log/", shell=True)
mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
status = subprocess.call(mkdircom, shell=True)
if( int(PROJECT_ID) <=0 ):
status = subprocess.call(sub_command, shell=True)
if ( VERBOSE == False ) :
status = subprocess.call("rm MCqsub.submit", shell=True)
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENO,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"QSUB",SWIF_ID_NUM,COMMAND['num_events'],NCORES,MEMLIMIT)
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENO,"QSUB",SWIF_ID_NUM,COMMAND['num_events'],NCORES,MEMLIMIT)
#====================================================
#Takes in a few pertinant pieces of info. Submits to condor
#this has not been fleshed out because of OSG integration.
#essentially take OSG_add_job and remove the OSG specific stuff (path remapping and + flags)
#====================================================
def condor_add_job(VERBOSE, WORKFLOW, RUNNUM, FILENUM, SCRIPT_TO_RUN, COMMAND, NCORES, DATA_OUTPUT_BASE_DIR, TIMELIMIT, RUNNING_DIR, PROJECT_ID, CONDOR_MAGIC ):
#print(CONDOR_MAGIC)
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNUM) + "_" + str(FILENUM)
JOBNAME = WORKFLOW + "_" + STUBNAME
mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
f=open('MCcondor.submit','w')
f.write("Executable = "+SCRIPT_TO_RUN+"\n")
f.write("Arguments = "+getCommandString(COMMAND,"CONDOR")+"\n")
f.write("Error = "+DATA_OUTPUT_BASE_DIR+"/log/"+"error_"+JOBNAME+".log\n")
f.write("Output = "+DATA_OUTPUT_BASE_DIR+"/log/"+"out_"+JOBNAME+".log\n")
f.write("Log = "+DATA_OUTPUT_BASE_DIR+"/log/"+"CONDOR_"+JOBNAME+".log\n")
f.write("RequestCpus = "+NCORES+"\n")
if CONDOR_MAGIC != []:
for magic in CONDOR_MAGIC:
f.write(magic+"\n")
f.write("Queue 1\n")
f.close()
JOBNAME=JOBNAME.replace(".","p")
if( int(PROJECT_ID) <=0 ):
add_command="condor_submit -batch-name "+WORKFLOW+" MCcondor.submit"
if add_command.find(';')!=-1 or add_command.find('&')!=-1 or mkdircom.find(';')!=-1 or mkdircom.find('&')!=-1:#THIS CHECK HELPS PROTEXT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
status = subprocess.call(mkdircom, shell=True)
status = subprocess.call(add_command, shell=True)
status = subprocess.call("rm MCcondor.submit", shell=True)
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENUM,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"Condor",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"UnSet")
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENUM,"Condor",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"UnSet")
#====================================================
#Takes in a few pertinant pieces of info. Submits to the OSG
#This involves a lot of string manipulation first to remap the passed locations to /srv/
#if project ID is less than 0 its an attempt ID and is recorded as such
#if project ID is greater than 0 then it is a project ID and this call is going to record a new job (NOT ACTUALLY MAKING THE ATTEMPT)
#if project ID == 0 then it is neither and just scrape the batch_ID....do nothing. Note: this scheme requires the first id in the tables to be 1 and not 0)
#====================================================
def OSG_add_job(VERBOSE, WORKFLOW, RUNNUM, FILENUM, SCRIPT_TO_RUN, COMMAND, NCORES, RAM, DATA_OUTPUT_BASE_DIR, TIMELIMIT, RUNNING_DIR, ENVFILE, ANAENVFILE, LOG_DIR, RANDBGTAG, PROJECT_ID,bundled ):
ship_random_triggers=False
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNUM)
numJobsInBundle=1
bundledJobs=[]
#print("PROJID:",str(PROJECT_ID))
#print("TO BUNDLE:",bundled)
if(int(PROJECT_ID)<0 and bundled):
bundledJobs=BundleJob(-1*int(PROJECT_ID))
numJobsInBundle=len(bundledJobs)
elif(int(PROJECT_ID)<0 and not bundled):
bundledJobs=[[-1*int(PROJECT_ID),FILENUM]]
numJobsInBundle=len(bundledJobs)
#print("FOUND JOBS:",bundledJobs)
#print("LENGTH: ",numJobsInBundle)
if(numJobsInBundle==1):
STUBNAME=STUBNAME+ "_" + str(FILENUM)
else:
STUBNAME=STUBNAME+ "_$(Process)"
JOBNAME = WORKFLOW + "_" + STUBNAME
mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
indir_parts=SCRIPT_TO_RUN.split("/")
script_to_use=indir_parts[len(indir_parts)-1]
print(script_to_use)
ENVFILE_parts=ENVFILE.split("/")
envfile_to_source="./"+ENVFILE_parts[len(ENVFILE_parts)-1] #"/srv/"+ENVFILE_parts[len(ENVFILE_parts)-1]
ANAENVFILE_parts=ANAENVFILE.split("/")
if(len(ANAENVFILE_parts) != 1):
anaenvfile_to_source="../"+ANAENVFILE_parts[len(ANAENVFILE_parts)-1] #"/srv/"+ANAENVFILE_parts[len(ANAENVFILE_parts)-1]
COMMAND_parts=COMMAND#COMMAND.split(" ")
COMMAND_parts['environment_file']=envfile_to_source
COMMAND_parts['output_directory']="./"
COMMAND_parts['running_directory']="./"
#print(COMMAND_parts)
additional_passins=""
if COMMAND_parts['ana_environment_file'] != "no_Analysis_env":
#print filegen_parts
additional_passins+=COMMAND_parts['ana_environment_file']+", "
COMMAND_parts['ana_environment_file']=anaenvfile_to_source
if COMMAND_parts['generator_config'][:5] == "file:":
gen_config_parts=COMMAND_parts['generator_config'].split("/")
gen_config_to_use=gen_config_parts[len(gen_config_parts)-1]
additional_passins+=COMMAND_parts['generator_config'][5:]+", "
COMMAND_parts['generator_config']="file:../"+gen_config_to_use #"file:/srv/"+gen_config_to_use
elif COMMAND_parts['generator_config'] != "NA":
gen_config_parts=COMMAND_parts['generator_config'].split("/")
gen_config_to_use=gen_config_parts[len(gen_config_parts)-1]
additional_passins+=COMMAND_parts['generator_config']+", "
COMMAND_parts['generator_config']="../"+gen_config_to_use #"/srv/"+gen_config_to_use
if COMMAND_parts['generator'][:5] == "file:":
filegen_parts=COMMAND_parts['generator'][5:].split("/")
#print filegen_parts
additional_passins+=COMMAND_parts['generator'][5:]+", "
COMMAND_parts['generator']="file:../"+filegen_parts[len(filegen_parts)-1] #"file:/srv/"+filegen_parts[len(filegen_parts)-1]
if COMMAND_parts['generator_post_config'] != "Default":
gen_post_config_parts=COMMAND_parts['generator_post_config'].split("/")
gen_post_config_to_use=gen_post_config_parts[len(gen_post_config_parts)-1]
additional_passins+=COMMAND_parts['generator_post_config']+", "
COMMAND_parts['generator_post_config']="../"+gen_post_config_to_use #"/srv/"+gen_post_config_to_use
if COMMAND_parts['generator_post_configevt'] != "Default":
gen_post_configevt_parts=COMMAND_parts['generator_post_configevt'].split("/")
gen_post_configevt_to_use=gen_post_configevt_parts[len(gen_post_configevt_parts)-1]
additional_passins+=COMMAND_parts['generator_post_configevt']+", "
COMMAND_parts['generator_post_configevt']="../"+gen_post_configevt_to_use #"/srv/"+gen_post_configevt_to_use
if COMMAND_parts['generator_post_configdec'] != "Default":
gen_post_configdec_parts=COMMAND_parts['generator_post_configdec'].split("/")
gen_post_configdec_to_use=gen_post_configdec_parts[len(gen_post_configdec_parts)-1]
additional_passins+=COMMAND_parts['generator_post_configdec']+", "
COMMAND_parts['generator_post_configdec']="../"+gen_post_configdec_to_use #"/srv/"+gen_post_configdec_to_use
if (COMMAND_parts['background_to_include'] == "Random" and COMMAND_parts['num_rand_trigs'] == -1 ) or COMMAND_parts['background_to_include'][:4] == "loc:" or ship_random_triggers:
formattedRUNNUM=""
for i in range(len(str(RUNNUM)),6):
formattedRUNNUM+="0"
formattedRUNNUM=formattedRUNNUM+str(RUNNUM)
if COMMAND_parts['background_to_include'] == "Random":
#print "/cache/halld/Simulation/random_triggers/"+RANDBGTAG+"/run"+formattedRUNNUM+"_random.hddm"
additional_passins+="/osgpool/halld/random_triggers/"+RANDBGTAG+"/run"+formattedRUNNUM+"_random.hddm"+", "
elif COMMAND_parts['background_to_include'][:4] == "loc:":
#print COMMAND_parts[21][4:]
additional_passins+=COMMAND_parts['background_to_include'][4:]+"/run"+formattedRUNNUM+"_random.hddm"+", "
if COMMAND_parts['custom_plugins'] != "None" and COMMAND_parts['custom_plugins'][:5]=="file:" :
janaconfig_parts=COMMAND_parts['custom_plugins'].split("/")
janaconfig_to_use=janaconfig_parts[len(janaconfig_parts)-1]
additional_passins+=COMMAND_parts['custom_plugins'][5:]+", "
COMMAND_parts['custom_plugins']="file:../"+janaconfig_to_use #"file:/srv/"+janaconfig_to_use
if COMMAND_parts['custom_ana_plugins'] != "None" and COMMAND_parts['custom_ana_plugins'][:5]=="file:" :
anajanaconfig_parts=COMMAND_parts['custom_ana_plugins'].split("/")
anajanaconfig_to_use=anajanaconfig_parts[len(anajanaconfig_parts)-1]
additional_passins+=COMMAND_parts['custom_ana_plugins'][5:]+", "
COMMAND_parts['custom_ana_plugins']="file:../"+anajanaconfig_to_use #"file:/srv/"+anajanaconfig_to_use
if COMMAND_parts['ccdb_sqlite_path'] != "no_sqlite" and COMMAND_parts['ccdb_sqlite_path'] != "batch_default":
ccdbsqlite_parts=COMMAND_parts['ccdb_sqlite_path'].split("/")
ccdbsqlite_to_use=ccdbsqlite_parts[len(ccdbsqlite_parts)-1]
additional_passins+=COMMAND_parts['ccdb_sqlite_path']+", "
COMMAND_parts['ccdb_sqlite_path']="../"+ccdbsqlite_to_use #"/srv/"+ccdbsqlite_to_use
if COMMAND_parts['rcdb_sqlite_path'] != "no_sqlite" and COMMAND_parts['rcdb_sqlite_path'] != "batch_default":
rcdbsqlite_parts=COMMAND_parts['rcdb_sqlite_path'].split("/")
rcdbsqlite_to_use=rcdbsqlite_parts[len(rcdbsqlite_parts)-1]
additional_passins+=COMMAND_parts['rcdb_sqlite_path']+", "
COMMAND_parts['rcdb_sqlite_path']="../"+rcdbsqlite_to_use #"/srv/"+rcdbsqlite_to_use
if COMMAND_parts['flux_to_generate'] != "unset" and COMMAND_parts['flux_to_generate']!="ccdb" and COMMAND_parts['flux_to_generate']!="cobrems" :
flux_to_use=COMMAND_parts['flux_to_generate']
additional_passins+=COMMAND_parts['flux_to_generate']+", "
COMMAND_parts['flux_to_generate']="../"+flux_to_use #"/srv/"+flux_to_use
if COMMAND_parts['polarization_to_generate']!="ccdb" and COMMAND_parts['polarization_histogram'] != "unset":
tpol_to_use=COMMAND_parts['polarization_to_generate']
additional_passins+=COMMAND_parts['polarization_to_generate']+", "
COMMAND_parts['polarization_to_generate']="../"+flux_to_use #"/srv/"+tpol_to_use
if additional_passins != "":
additional_passins=", "+additional_passins
additional_passins=additional_passins[:-2]
f=open('MCOSG_'+str(PROJECT_ID)+'.submit','w')
f.write("universe = vanilla"+"\n")
f.write("Executable = "+os.environ.get('MCWRAPPER_CENTRAL')+"/osg-container.sh"+"\n")
f.write('+ProjectName = "gluex"'+"\n")
#f.write("Arguments = "+SCRIPT_TO_RUN+" "+COMMAND+"\n")
f.write("Arguments = "+"./"+script_to_use+" "+getCommandString(COMMAND_parts,"OSG",numJobsInBundle)+"\n")
f.write("Requirements = (HAS_SINGULARITY == TRUE) && (HAS_CVMFS_oasis_opensciencegrid_org == True) && (TARGET.GLIDEIN_Entry_Name =!= \"OSG_US_ODU-Ubuntu\")"+"\n")
#f.write("Requirements = (HAS_SINGULARITY == TRUE) && (HAS_CVMFS_oasis_opensciencegrid_org == True) && (TARGET.GLIDEIN_Entry_Name =!= \"OSG_US_ODU-Ubuntu\") && GLIDEIN_ResourceName==\"ComputeCanada-Cedar\""+"\n")
#f.write("Requirements = (HAS_SINGULARITY == TRUE) && (HAS_CVMFS_oasis_opensciencegrid_org == True) && (TARGET.GLIDEIN_Entry_Name =!= \"OSG_US_ODU-Ubuntu\") && GLIDEIN_ResourceName==\"JLab-FARM-CE\""+"\n")
#f.write("Requirements = (HAS_SINGULARITY == TRUE) && (HAS_CVMFS_oasis_opensciencegrid_org == True) && (GLIDEIN_SITE=!=\"UConn\") && (GLIDEIN_SITE=!=\"Cedar\")"+"\n")
# f.write("Requirements = (HAS_SINGULARITY == TRUE) && (HAS_CVMFS_oasis_opensciencegrid_org == True) && (GLIDEIN_SITE==\"UConn\")"+"\n")
#f.write('wantjobrouter=true'+"\n")
if("data_mirror_test" in DATA_OUTPUT_BASE_DIR):
f.write('+SingularityImage = "/cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_devel:latest"'+"\n")
f.write("use_oauth_services = jlab_gluex"+"\n")
else:
#f.write('+SingularityImage = "/cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_devel:latest"'+"\n")
f.write('+SingularityImage = "/cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1"'+"\n")
#f.write('+SingularityImage = "/cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1"'+"\n")
f.write("use_oauth_services = jlab_gluex"+"\n")
f.write('+SingularityBindCVMFS = True'+"\n")
#f.write('+UNDESIRED_Sites = "OSG_US_ODU-Ubuntu"'+"\n")
f.write('+SingularityAutoLoad = True'+"\n")
# f.write('+CVMFSReposList = "oasis.opensciencegrid.org"'+"\n")
#f.write('+DesiredSites="JLab-FARM-CE"'+"\n")
f.write('should_transfer_files = YES'+"\n")
#f.write('should_transfer_files = NO'+"\n")
#f.write('when_to_transfer_output = ON_EXIT'+"\n")
#f.write('should_transfer_files = NO'+"\n")
f.write('concurrency_limits = GluexProduction'+"\n")
f.write('on_exit_remove = true'+"\n")
f.write('on_exit_hold = false'+"\n")
#STUBNAME = STUBNAME+str(RUNNUM) + "_" + str(FILENUM)
#JOBNAME = WORKFLOW + "_" + STUBNAME
f.write("Error = "+DATA_OUTPUT_BASE_DIR+"/log/"+"error_"+JOBNAME+".log\n")
f.write("output = "+DATA_OUTPUT_BASE_DIR+"/log/"+"out_"+JOBNAME+".log\n")
f.write("log = "+LOG_DIR+"/log/"+"OSG_"+JOBNAME+".log\n")
f.write("initialdir = "+RUNNING_DIR+"\n")
f.write("request_cpus = "+str(NCORES)+"\n")
f.write("request_memory = "+str(RAM)+"\n")
f.write("request_disk = 5.0GB"+"\n")
#f.write("transfer_input_files = "+ENVFILE+"\n")
f.write("transfer_input_files = "+SCRIPT_TO_RUN+", "+ENVFILE+additional_passins+"\n")
#if(numJobsInBundle==1):
# f.write("transfer_output_files = "+str(RUNNUM)+"_"+str(FILENUM)+"\n")
# f.write("transfer_output_remaps = "+"\""+str(RUNNUM)+"_"+str(FILENUM)+"="+DATA_OUTPUT_BASE_DIR+"\""+"\n")
#else:
# f.write("transfer_output_files = "+str(RUNNUM)+"_$(Process)"+"\n")
# f.write("transfer_output_remaps = "+"\""+str(RUNNUM)+"_$(Process)"+"="+DATA_OUTPUT_BASE_DIR+"\""+"\n")
f.write("queue "+str(numJobsInBundle)+"\n")
f.close()
JOBNAME=JOBNAME.replace(".","p")
#"condor_submit -batch-name "+WORKFLOW+" MCcondor.submit"
#add_command="condor_submit -name "+JOBNAME+" MCOSG_"+str(PROJECT_ID)+".submit"
add_command="condor_submit "+"MCOSG_"+str(PROJECT_ID)+".submit"
if add_command.find(';')!=-1 or add_command.find('&')!=-1 :#THIS CHECK HELPS PROTEXT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
mkdircom2="mkdir -p "+LOG_DIR+"/log/"
status2 = subprocess.call(mkdircom2, shell=True)
status = subprocess.call(mkdircom, shell=True)
SWIF_ID_NUM="-1"
if( int(PROJECT_ID) <=0 ):
#do in Popen with the environment
#print(add_command)
#add bearer token to env
os.environ["BEARER_TOKEN_FILE"]="/var/run/user/10967/bt_u10967"
os.environ["XDG_RUNTIME_DIR"]="/run/user/10967"
token_str='eval `ssh-agent`; /usr/bin/ssh-add;'
agent_kill_str="; ssh-agent -k"
print("Submitting: ",token_str+add_command+agent_kill_str)
jobSubout,jobSuberr=subprocess.Popen(token_str+add_command+agent_kill_str,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,env=os.environ,executable='/bin/bash',close_fds=True).communicate()
#jobSubout=subprocess.check_output(add_command.split(" "))
print("JOBSUB OUTPUT",jobSubout)
print("JOBSUB ERROR",jobSuberr)
#'Agent pid 2322136\nSubmitting job(s).\n1 job(s) submitted to cluster 925999.\n'
idnumline=jobSubout.split("\n")[2].split(".")[0].split(" ")
#1 job(s) submitted to cluster 425013.
status = subprocess.call('rm -f MCOSG_'+str(PROJECT_ID)+'.submit', shell=True)
status = subprocess.call('rm -f /tmp/MCOSG_'+str(PROJECT_ID)+'.submit', shell=True)
#print "DECIDING IF FIRST JOB"
#print PROJECT_ID
if int(PROJECT_ID) > 0:
#print "FIRST ATTEMPT"
recordJob(PROJECT_ID,RUNNUM,FILENUM,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNUM,FILENUM,"OSG",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"Unset")
elif int(PROJECT_ID) < 0:
if(int(idnumline[0])==numJobsInBundle):
#print "A NEW SET OF ATTEMPTS"
#print("JOBS BUNDLE:",bundledJobs)
transactions_Array=[]
trans_block_count=0
transaction_stub="INSERT INTO Attempts (Job_ID,Creation_Time,BatchSystem,SubmitHost,BatchJobID,Status,WallTime,CPUTime,ThreadsRequested,RAMRequested, RAMUsed) VALUES "
transaction_str=""
#print("BUNDLING!")
for job in bundledJobs:
#***********************
#THE FOLLOWING IF CHECKS IF THE ASSIGNED BATCH ID HAS BEEN ASSIGNED BEFORE FROM SCOSG16
#THIS OCCURED BEFORE CAUSING UNIQUENESS TO BE VIOLATED AND REQUIRING ~8K JOBS TO BE SCRUBBED
#***********************
if(trans_block_count % 500 == 0 and trans_block_count != 0):
transactions_Array.append(transaction_stub+transaction_str[:-2])
transaction_str=""
#print("JOB:",job)
SWIF_ID_NUM=str(idnumline[5])+".0"
if(numJobsInBundle>1):
SWIF_ID_NUM=str(idnumline[5])+"."+str(job[1])
#if int(PROJECT_ID) !=0:
# findmyjob="SELECT * FROM Attempts where BatchJobID='"+str(SWIF_ID_NUM)+"' && BatchSystem='OSG';"
# dbcursor.execute(findmyjob)
# MYJOB = dbcursor.fetchall()
#if len(MYJOB) != 0:
# #SELECT DISTINCT Project_ID FROM Jobs where ID in (select Job_ID from Attempts WHERE BatchSystem='OSG' GROUP BY BatchJobID HAVING COUNT(Job_ID)>1 ORDER BY BatchJobID DESC);
# print("THE TIMELINE HAS BEEN FRACTURED. TERMINATING SUBMITS AND SHUTTING THE ROBOT DOWN!!!")
# f=open("/osgpool/halld/tbritton/.ALLSTOP","x")
# exit(1)
transaction_str+=Build_recordAttemptString(int(job[0]),RUNNUM,job[1],"OSG","'"+socket.gethostname()+"'",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"Unset")+", "
trans_block_count+=1
#print(transaction_str)
#recordAttempt(int(job[0]),RUNNUM,job[1],"OSG",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"Unset")
if(transaction_str != ""):
transactions_Array.append(transaction_stub+transaction_str[:-2])
#print(transactions_Array)
for transaction in transactions_Array:
print(transaction)
print("===================================================")
Transact_recordAttempt(transaction)
#====================================================
#Takes in a few pertinant pieces of info. Submits to the JSUB
#Currently a stub. No time to implement (or real demand)
#====================================================
def JSUB_add_job(VERBOSE, WORKFLOW, PROJECT,TRACK, RUNNUM, FILENUM, SCRIPT_TO_RUN, COMMAND, NCORES, DATA_OUTPUT_BASE_DIR, TIMELIMIT, RUNNING_DIR, ENVFILE, ANAENVFILE, LOG_DIR, RANDBGTAG, PROJECT_ID):
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNUM) + "_" + str(FILENUM)
JOBNAME = WORKFLOW + "_" + STUBNAME
#mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
f=open('MCJSUB.submit','w')
f.write("<Request>"+"\n")
f.write("<Project name=\""+PROJECT+"\"/>"+"\n")
f.write("<Track name=\""+TRACK+"\"/>"+"\n")
f.write("<Name name=\""+JOBNAME+"\"/>"+"\n")
f.write("<Command><![CDATA[ "+SCRIPT_TO_RUN+" "+getCommandString(COMMAND,"JSUB")+" ]></Command>"+"\n")
f.write("<Job> </Job>"+"\n")
f.write("</Request>"+"\n")
f.close()
exit(1)
#====================================================
#Takes in a few pertinant pieces of info. Submits to SLURM
#This was originally targetting NERSC. Then JLab announced a switch to slurm. And then swif did it. If there is demand this should be finished up
#if project ID is less than 0 its an attempt ID and is recorded as such
#if project ID is greater than 0 then it is a project ID and this call is going to record a new job (NOT ACTUALLY MAKING THE ATTEMPT)
#if project ID == 0 then it is neither and just scrape the batch_ID....do nothing. Note: this scheme requires the first id in the tables to be 1 and not 0)
#====================================================
def SLURMcont_add_job(VERBOSE, WORKFLOW, RUNNUM, FILENUM, SCRIPT_TO_RUN, COMMAND, NCORES, RAM, DATA_OUTPUT_BASE_DIR, TIMELIMIT, RUNNING_DIR, ENVFILE, ANAENVFILE, LOG_DIR, RANDBGTAG, PROJECT_ID ):
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNUM) + "_" + str(FILENUM)
JOBNAME = WORKFLOW + "_" + STUBNAME
mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
status = subprocess.call(mkdircom, shell=True)
f=open('MCSLURM.submit','w')
f.write("#!/bin/bash -l"+"\n")
f.write("#SBATCH -J "+JOBNAME+"\n")
#f.write("#SBATCH --image=/cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1"+"\n")
f.write("#SBATCH --nodes=1"+"\n")
f.write("#SBATCH --time="+TIMELIMIT+"\n")
f.write("#SBATCH --tasks-per-node=1"+"\n")
f.write("#SBATCH --cpus-per-task="+NCORES+"\n")
f.write("#SBATCH --mem="+RAM+"\n")
#f.write("#SBATCH -A gluex"+"\n")
f.write("#SBATCH -p production"+"\n")
f.write("#SBATCH -o "+DATA_OUTPUT_BASE_DIR+"/log/"+JOBNAME+".out\n")
f.write("#SBATCH -e "+DATA_OUTPUT_BASE_DIR+"/log/"+JOBNAME+".err\n")
#f.write("srun "+SCRIPT_TO_RUN+" "+COMMAND+"\n")
#/group/halld/www/halldweb/html/dist/gluex_centos7.img /cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1
f.write("singularity exec --bind /scigroup/mcwrapper/ --bind /u --bind /group/halld/ --bind /scratch/slurm/ --bind /cvmfs --bind /work/osgpool/ --bind /work/halld --bind /cache/halld --bind /volatile/halld --bind /work/halld2 /cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1 $MCWRAPPER_CENTRAL/MakeMC.sh "+getCommandString(COMMAND,"SBATCH_SLURM")+"\n")
#print(getCommandString(COMMAND,"SBATCH_SLURM"))
f.close()
if( int(PROJECT_ID) <=0 ):
add_command="sbatch MCSLURM.submit"
if add_command.find(';')!=-1 or add_command.find('&')!=-1 :#THIS CHECK HELPS PROTEXT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENO,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"SLURM",SWIF_ID_NUM,COMMAND['num_events'],NCORES, "UnSet")
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENO,"SLURM",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"UnSet")
status = subprocess.call(add_command, shell=True)
status = subprocess.call("rm MCSLURM.submit", shell=True)
def SLURM_add_job(VERBOSE, WORKFLOW, RUNNUM, FILENUM, SCRIPT_TO_RUN, COMMAND, NCORES, DATA_OUTPUT_BASE_DIR, TIMELIMIT, RUNNING_DIR, ENVFILE, ANAENVFILE, LOG_DIR, RANDBGTAG, PROJECT_ID ):
STUBNAME=""
if(COMMAND['custom_tag_string'] != "I_dont_have_one"):
STUBNAME=COMMAND['custom_tag_string']+"_"
# PREPARE NAMES
STUBNAME = STUBNAME+str(RUNNUM) + "_" + str(FILENUM)
JOBNAME = WORKFLOW + "_" + STUBNAME
mkdircom="mkdir -p "+DATA_OUTPUT_BASE_DIR+"/log/"
status = subprocess.call(mkdircom, shell=True)
f=open('MCSLURM.submit','w')
f.write("#!/bin/bash -l"+"\n")
f.write("#SBATCH -J "+JOBNAME+"\n")
#f.write("#SBATCH --image=/cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1"+"\n")
f.write("#SBATCH --nodes=1"+"\n")
f.write("#SBATCH --time="+TIMELIMIT+"\n")
f.write("#SBATCH --tasks-per-node=1"+"\n")
f.write("#SBATCH --cpus-per-task="+NCORES+"\n")
#f.write("#SBATCH -A gluex"+"\n")
f.write("#SBATCH -p production"+"\n")
f.write("#SBATCH -o "+DATA_OUTPUT_BASE_DIR+"/log/"+JOBNAME+".out\n")
f.write("#SBATCH -e "+DATA_OUTPUT_BASE_DIR+"/log/"+JOBNAME+".err\n")
#f.write("srun "+SCRIPT_TO_RUN+" "+COMMAND+"\n")
#/group/halld/www/halldweb/html/dist/gluex_centos7.img /cvmfs/singularity.opensciencegrid.org/jeffersonlab/gluex_prod:v1
f.write(SCRIPT_TO_RUN+" "+getCommandString(COMMAND,"SLURM")+"\n")
f.close()
if( int(PROJECT_ID) <=0 ):
add_command="sbatch MCSLURM.submit"
if add_command.find(';')!=-1 or add_command.find('&')!=-1 :#THIS CHECK HELPS PROTEXT AGAINST A POTENTIAL HACK VIA CONFIG FILES
print( "Nice try.....you cannot use ; or &")
exit(1)
if int(PROJECT_ID) > 0:
recordJob(PROJECT_ID,RUNNO,FILENO,SWIF_ID_NUM,COMMAND['num_events'])
#recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,"SLURM",SWIF_ID_NUM,COMMAND['num_events'],NCORES, "UnSet")
elif int(PROJECT_ID) < 0:
recordAttempt(abs(int(PROJECT_ID)),RUNNO,FILENO,"SLURM",SWIF_ID_NUM,COMMAND['num_events'],NCORES,"UnSet")
status = subprocess.call(add_command, shell=True)
status = subprocess.call("rm MCSLURM.submit", shell=True)
#====================================================
#function to split monolithic hddm file by run number
#credit to sdobbs for the base
#====================================================
def split_file_on_run_number(infname):
# output files
fout = {}
outevts = {}
# iterate through the file, splitting by run number
for rec in hddm_r.istream(infnamepath):
evt = rec.getReconstructedPhysicsEvent()
if evt.runNo not in fout:
outfname = "{0}_run{1}.hddm".format(infname[:-5],evt.runNo)
print("Creating output file {0} ...".format(outfname))
fout[evt.runNo] = hddm_r.ostream(outfname)
outevts[evt.runNo] = 0
else:
outevts[evt.runNo] += 1
fout[evt.runNo].write(rec)
print(fout)
print(outevts)
return outevts
#====================================================
#Simple function to take in the column information and insert into the Jobs Table
#====================================================
def recordJob(PROJECT_ID,RUNNO,FILENO,BatchJobID, NUMEVTS):
dbcursor.execute("INSERT INTO Jobs (Project_ID, RunNumber, FileNumber, Creation_Time, IsActive, NumEvts) VALUES ("+str(PROJECT_ID)+", "+str(RUNNO)+", "+str(FILENO)+", NOW(), 1, "+str(NUMEVTS)+")")
dbcnx.commit()
#====================================================
#This deprecated function used to find the job to attach to and indsert into the jobs table
#====================================================
def recordFirstAttempt(PROJECT_ID,RUNNO,FILENO,BatchSYS,BatchJobID, NUMEVTS,NCORES, RAM):
findmyjob="SELECT ID FROM Jobs WHERE Project_ID="+str(PROJECT_ID)+" && RunNumber="+str(RUNNO)+" && FileNumber="+str(FILENO)+" && NumEvts="+str(NUMEVTS)+" && IsActive=1;"
dbcursor.execute(findmyjob)
MYJOB = dbcursor.fetchall()
if len(MYJOB) != 1:
print("I either can't find a job or too many jobs might be mine")
exit(1)
Job_ID=MYJOB[0][0]
addAttempt="INSERT INTO Attempts (Job_ID,Creation_Time,BatchSystem,HostName,BatchJobID,Status,WallTime,CPUTime,ThreadsRequested,RAMRequested, RAMUsed) VALUES ("+str(Job_ID)+", NOW(), "+str("'"+BatchSYS+"'")+", "+str(socket.gethostname())+", "+str(BatchJobID)+", 'Created', 0, 0, "+str(NCORES)+", "+str("'"+RAM+"'")+", '0'"+");"
print(addAttempt)
dbcursor.execute(addAttempt)
dbcnx.commit()
#====================================================
#This function attaches itself directly to the passed in JOB_ID and inserts a new job
#====================================================
def Transact_recordAttempt(trans_string):
#print(trans_string)
dbcursor.execute(trans_string)#,multi=True)
dbcnx.commit()
def Build_recordAttemptString(JOB_ID,RUNNO,FILENO,BatchSYS,hostname,BatchJobID, NUMEVTS,NCORES, RAM):
#findmyjob="SELECT * FROM Jobs WHERE ID="+str(JOB_ID)
##print findmyjob
#dbcursor.execute(findmyjob)
#MYJOB = dbcursor.fetchall()
#print MYJOB#
#if len(MYJOB) != 1:
# print("I either can't find a job or too many jobs might be mine")
# exit(1)
#Job_ID=MYJOB[0][0]
addAttempt="("+str(JOB_ID)+", NOW(), "+str("'"+BatchSYS+"'")+", "+str(hostname)+", "+str(BatchJobID)+", 'Created', 0, 0, "+str(NCORES)+", "+str("'"+RAM+"'")+", '0'"+")"
return addAttempt
def recordAttempt(JOB_ID,RUNNO,FILENO,BatchSYS,BatchJobID, NUMEVTS,NCORES, RAM):
#print "RECORDING ATTEMPT"
#print JOB_ID
findmyjob="SELECT * FROM Jobs WHERE ID="+str(JOB_ID)
#print findmyjob
dbcursor.execute(findmyjob)
MYJOB = dbcursor.fetchall()
#print MYJOB
if len(MYJOB) != 1:
print("I either can't find a job or too many jobs might be mine")
exit(1)
Job_ID=MYJOB[0][0]
addAttempt="INSERT INTO Attempts (Job_ID,Creation_Time,BatchSystem,SubmitHost,BatchJobID,Status,WallTime,CPUTime,ThreadsRequested,RAMRequested, RAMUsed) VALUES ("+str(JOB_ID)+", NOW(), "+str("'"+BatchSYS+"'")+", "+str(socket.gethostname())+", "+str(BatchJobID)+", 'Created', 0, 0, "+str(NCORES)+", "+str("'"+RAM+"'")+", '0'"+");"
print(addAttempt)
dbcursor.execute(addAttempt)
dbcnx.commit()
#====================================================
#The argument string passed to the MakeMC script is order dependent. THe following is that order.
#it is dictionary based and should be fairly trivial to redesign into an order independent method
#if a new MakeMC script came around this is where you would add an if and conform to its requirements
#the COMMAND dictionary expects ALL the KEYS
#====================================================
def getCommandString(COMMAND,USER,numbundled=1):
if(USER=="OSG" and numbundled!=1):
return COMMAND['batchrun']+" "+COMMAND['environment_file']+" "+COMMAND['ana_environment_file']+" "+COMMAND['generator_config']+" "+COMMAND['output_directory']+" "+COMMAND['run_number']+" "+"$(Process)"+" "+COMMAND['num_events']+" "+COMMAND['jana_calib_context']+" "+COMMAND['jana_calibtime']+" "+COMMAND['do_gen']+" "+COMMAND['do_geant']+" "+COMMAND['do_mcsmear']+" "+COMMAND['do_recon']+" "+COMMAND['clean_gen']+" "+COMMAND['clean_geant']+" "+COMMAND['clean_mcsmear']+" "+COMMAND['clean_recon']+" "+COMMAND['batch_system']+" "+COMMAND['num_cores']+" "+COMMAND['generator']+" "+COMMAND['geant_version']+" "+COMMAND['background_to_include']+" "+COMMAND['custom_Gcontrol']+" "+COMMAND['eBeam_energy']+" "+COMMAND['coherent_peak']+" "+COMMAND['min_generator_energy']+" "+COMMAND['max_generator_energy']+" "+COMMAND['custom_tag_string']+" "+COMMAND['custom_plugins']+" "+COMMAND['custom_ana_plugins']+" "+COMMAND['events_per_file']+" "+COMMAND['running_directory']+" "+COMMAND['ccdb_sqlite_path']+" "+COMMAND['rcdb_sqlite_path']+" "+COMMAND['background_tagger_only']+" "+COMMAND['radiator_thickness']+" "+COMMAND['background_rate']+" "+COMMAND['random_background_tag']+" "+COMMAND['recon_calibtime']+" "+COMMAND['no_geant_secondaries']+" "+COMMAND['mcwrapper_version']+" "+COMMAND['no_bcal_sipm_saturation']+" "+COMMAND['flux_to_generate']+" "+COMMAND['flux_histogram']+" "+COMMAND['polarization_to_generate']+" "+COMMAND['polarization_histogram']+" "+COMMAND['eBeam_current']+" "+COMMAND['experiment']+" "+COMMAND['num_rand_trigs']+" "+COMMAND['location']+" "+COMMAND['generator_post']+" "+COMMAND['generator_post_config']+" "+COMMAND['generator_post_configevt']+" "+COMMAND['generator_post_configdec']+" "+COMMAND['geant_vertex_area']+" "+COMMAND['geant_vertex_length']+" "+COMMAND['mcsmear_notag']+" "+COMMAND['project_directory_name']
else:
return COMMAND['batchrun']+" "+COMMAND['environment_file']+" "+COMMAND['ana_environment_file']+" "+COMMAND['generator_config']+" "+COMMAND['output_directory']+" "+COMMAND['run_number']+" "+COMMAND['file_number']+" "+COMMAND['num_events']+" "+COMMAND['jana_calib_context']+" "+COMMAND['jana_calibtime']+" "+COMMAND['do_gen']+" "+COMMAND['do_geant']+" "+COMMAND['do_mcsmear']+" "+COMMAND['do_recon']+" "+COMMAND['clean_gen']+" "+COMMAND['clean_geant']+" "+COMMAND['clean_mcsmear']+" "+COMMAND['clean_recon']+" "+COMMAND['batch_system']+" "+COMMAND['num_cores']+" "+COMMAND['generator']+" "+COMMAND['geant_version']+" "+COMMAND['background_to_include']+" "+COMMAND['custom_Gcontrol']+" "+COMMAND['eBeam_energy']+" "+COMMAND['coherent_peak']+" "+COMMAND['min_generator_energy']+" "+COMMAND['max_generator_energy']+" "+COMMAND['custom_tag_string']+" "+COMMAND['custom_plugins']+" "+COMMAND['custom_ana_plugins']+" "+COMMAND['events_per_file']+" "+COMMAND['running_directory']+" "+COMMAND['ccdb_sqlite_path']+" "+COMMAND['rcdb_sqlite_path']+" "+COMMAND['background_tagger_only']+" "+COMMAND['radiator_thickness']+" "+COMMAND['background_rate']+" "+COMMAND['random_background_tag']+" "+COMMAND['recon_calibtime']+" "+COMMAND['no_geant_secondaries']+" "+COMMAND['mcwrapper_version']+" "+COMMAND['no_bcal_sipm_saturation']+" "+COMMAND['flux_to_generate']+" "+COMMAND['flux_histogram']+" "+COMMAND['polarization_to_generate']+" "+COMMAND['polarization_histogram']+" "+COMMAND['eBeam_current']+" "+COMMAND['experiment']+" "+COMMAND['num_rand_trigs']+" "+COMMAND['location']+" "+COMMAND['generator_post']+" "+COMMAND['generator_post_config']+" "+COMMAND['generator_post_configevt']+" "+COMMAND['generator_post_configdec']+" "+COMMAND['geant_vertex_area']+" "+COMMAND['geant_vertex_length']+" "+COMMAND['mcsmear_notag']+" "+COMMAND['project_directory_name']
def LoadCCDB():
sqlite_connect_str = "mysql://ccdb_user@hallddb.jlab.org/ccdb"
provider = ccdb.AlchemyProvider() # this class has all CCDB manipulation functions
provider.connect(sqlite_connect_str) # use usual connection string to connect to database
provider.authentication.current_user_name = "psflux_user" # to have a name in logs
return provider
def PSAcceptance(x, par0, par1, par2):
min = par1
max = par2
if x > 2.*min and x < min + max:
return par0*(1-2.*min/x)
elif x >= min + max:
return par0*(2.*max/x - 1)
return 0.
def calcFluxCCDB(ccdb_conn, run, emin, emax):
flux = 0.
VARIATION = "default"
CALIBTIME = datetime.now()
CALIBTIME_USER = CALIBTIME
CALIBTIME_ENERGY = CALIBTIME
# Set livetime scale factor
livetime_ratio = 0.0
try:
livetime_assignment = ccdb_conn.get_assignment("/PHOTON_BEAM/pair_spectrometer/lumi/trig_live", run[0], VARIATION, CALIBTIME)
livetime = livetime_assignment.constant_set.data_table
if float(livetime[3][1]) > 0.0: # check that livetimes are non-zero
livetime_ratio = float(livetime[0][1])/float(livetime[3][1])
else: # if bad livetime assume ratio is 1
livetime_ratio = 1.0
except:
livetime_ratio = 1.0 # default to unity if table doesn't exist
# Conversion factors for total flux
converterThickness = run[2]
converterLength = 75e-6 # default is 75 um
if converterThickness == "Be 750um":
converterLength = 750e-6
elif converterThickness != "Be 75um":
print("Unknown converter thickness for run %s: %s, assuming Be 75um" % (run[0],run[2]))