This repository has been archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
RunJobHpcEvent.py
1837 lines (1590 loc) · 85.7 KB
/
RunJobHpcEvent.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
# Class definition:
# RunJobHpcEvent
# This class is the base class for the HPC Event Server classes.
# Instances are generated with RunJobFactory via pUtil::getRunJob()
# Implemented as a singleton class
# http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern
import commands
import json
import os
import re
import shutil
import subprocess
import sys
import time
import traceback
# Import relevant python/pilot modules
# Pilot modules
import Job
import Node
import Site
import pUtil
import RunJobUtilities
import Mover as mover
from ThreadPool import ThreadPool
from RunJob import RunJob # Parent RunJob class
from JobState import JobState
from JobRecovery import JobRecovery
from PilotErrors import PilotErrors
from ErrorDiagnosis import ErrorDiagnosis
from pUtil import tolog, getExperiment, isAnalysisJob, createPoolFileCatalog, getSiteInformation, getDatasetDict
from objectstoreSiteMover import objectstoreSiteMover
from Mover import getFilePathForObjectStore, getInitialTracingReport
from PandaServerClient import PandaServerClient
import EventRanges
from GetJob import GetJob
from HPC.HPCManager import HPCManager
class RunJobHpcEvent(RunJob):
# private data members
__runjob = "RunJobHpcEvent" # String defining the sub class
__instance = None # Boolean used by subclasses to become a Singleton
#__error = PilotErrors() # PilotErrors object
# Required methods
def __init__(self):
""" Default initialization """
# e.g. self.__errorLabel = errorLabel
pass
self.__output_es_files = []
self.__eventRanges = {}
self.__failedStageOuts = []
self.__hpcManager = None
self.__stageout_threads = 1
self.__userid = None
self.__stageinretry = 1
self.__siteInfo = None
# multi-jobs
self.__firstJob = True
self.__firstJobId = None
self.__pilotWorkingDir = None
self.__jobs = {}
self.__jobEventRanges = {}
self.__nJobs = 1
self.__hpcMode = 'normal'
self.__hpcStatue = 'starting'
self.__hpcCoreCount = 0
self.__hpcEventRanges = 0
self.__hpcJobId = None
self.__neededEventRanges = 0
self.__maxEventsPerJob = 1000
self.__neededJobs = None
self.__avail_files = {}
self.__avail_tag_files = {}
# event Stager
self.__yoda_to_os = False
self.__yoda_to_zip = False
self.__es_to_zip = False
self.__stageout_status = False
# for recovery
self.__jobStateFile = None
def __new__(cls, *args, **kwargs):
""" Override the __new__ method to make the class a singleton """
if not cls.__instance:
cls.__instance = super(RunJobHpcEvent, cls).__new__(cls, *args, **kwargs)
return cls.__instance
def getRunJob(self):
""" Return a string with the experiment name """
return self.__runjob
def getRunJobFileName(self):
""" Return the filename of the module """
return super(RunJobHpcEvent, self).getRunJobFileName()
# def argumentParser(self): <-- see example in RunJob.py
def allowLoopingJobKiller(self):
""" Should the pilot search for looping jobs? """
# The pilot has the ability to monitor the payload work directory. If there are no updated files within a certain
# time limit, the pilot will consider the as stuck (looping) and will kill it. The looping time limits are set
# in environment.py (see e.g. loopingLimitDefaultProd)
return False
def setupHPCEvent(self, rank=None):
self.__jobSite = Site.Site()
self.__jobSite.setSiteInfo(self.argumentParser())
self.__logguid = None
## For HPC job, we don't need to reassign the workdir
# reassign workdir for this job
self.__jobSite.workdir = self.__jobSite.wntmpdir
if not os.path.exists(self.__jobSite.workdir):
os.makedirs(self.__jobSite.workdir)
tolog("runJobHPCEvent.getPilotLogFilename=%s"% self.getPilotLogFilename())
if self.getPilotLogFilename() != "":
pilotLogFilename = self.getPilotLogFilename()
if rank:
pilotLogFilename = '%s.%s' % (pilotLogFilename, rank)
tolog("runJobHPCEvent.setPilotLogFilename=%s"% pilotLogFilename)
pUtil.setPilotlogFilename(pilotLogFilename)
# set node info
self.__node = Node.Node()
self.__node.setNodeName(os.uname()[1])
self.__node.collectWNInfo(self.__jobSite.workdir)
# redirect stderr
#sys.stderr = open("%s/runJobHPCEvent.stderr" % (self.__jobSite.workdir), "w")
self.__pilotWorkingDir = self.getParentWorkDir()
tolog("Pilot workdir is: %s" % self.__pilotWorkingDir)
os.chdir(self.__pilotWorkingDir)
tolog("Current job workdir is: %s" % os.getcwd())
# self.__jobSite.workdir = self.__pilotWorkingDir
tolog("Site workdir is: %s" % self.__jobSite.workdir)
# get the experiment object
self.__thisExperiment = getExperiment(self.getExperiment())
tolog("runEvent will serve experiment: %s" % (self.__thisExperiment.getExperiment()))
self.__siteInfo = getSiteInformation(self.getExperiment())
def getDefaultResources(self):
siteInfo = self.__siteInfo
catchalls = siteInfo.readpar("catchall")
values = {}
res = {}
if "yoda_to_os" in catchalls:
res['yoda_to_os'] = True
else:
res['yoda_to_os'] = False
self.__yoda_to_os = res['yoda_to_os']
if "es_to_zip" in catchalls:
res['es_to_zip'] = True
else:
res['es_to_zip'] = False
self.__es_to_zip = res['es_to_zip']
if "yoda_to_zip" in catchalls:
res['yoda_to_zip'] = True
else:
res['yoda_to_zip'] = False
self.__yoda_to_zip = res['yoda_to_zip']
if "copyOutputToGlobal" in catchalls:
res['copyOutputToGlobal'] = True
else:
res['copyOutputToGlobal'] = False
for catchall in catchalls.split(","):
if '=' in catchall:
values[catchall.split('=')[0]] = catchall.split('=')[1]
res['queue'] = values.get('queue', 'regular')
res['mppwidth'] = values.get('mppwidth', 48)
res['mppnppn'] = values.get('mppnppn', 1)
res['walltime_m'] = values.get('walltime_m', 30)
res['ATHENA_PROC_NUMBER'] = values.get('ATHENA_PROC_NUMBER', 23)
res['max_nodes'] = values.get('max_nodes', 3)
res['min_walltime_m'] = values.get('min_walltime_m', 20)
res['max_walltime_m'] = values.get('max_walltime_m', 2000)
res['nodes'] = values.get('nodes', 2)
if self.getYodaNodes():
res['nodes'] = self.getYodaNodes()
if self.getYodaQueue():
res['queue'] = self.getYodaQueue()
res['min_nodes'] = values.get('min_nodes', 1)
res['cpu_per_node'] = values.get('cpu_per_node', 24)
res['partition'] = values.get('partition', None)
res['repo'] = values.get('repo', None)
res['max_events'] = values.get('max_events', 10000)
res['initialtime_m'] = values.get('initialtime_m', 15)
res['time_per_event_m'] = values.get('time_per_event_m', 10)
res['mode'] = values.get('mode', 'normal')
res['backfill_queue'] = values.get('backfill_queue', 'regular')
res['stageout_threads'] = int(values.get('stageout_threads', 4))
res['copy_input_files'] = values.get('copy_input_files', 'false').lower()
res['plugin'] = values.get('plugin', 'pbs').lower()
res['localWorkingDir'] = values.get('localWorkingDir', None)
res['parallel_jobs'] = values.get('parallel_jobs', 1)
res['events_limit_per_job'] = int(values.get('events_limit_per_job', 1000))
if 'debug' in res['queue']:
res['walltime_m'] = 30
siteInfo = getSiteInformation(self.getExperiment())
# get the copy tool
setup = siteInfo.getCopySetup(stageIn=False)
tolog("Copy Setup: %s" % (setup))
# espath = getFilePathForObjectStore(filetype="eventservice")
ddmendpoint = siteInfo.getObjectstoreDDMEndpoint(os_bucket_name='eventservice')
os_bucket_id = siteInfo.getObjectstoreBucketID(ddmendpoint)
tolog("Will use the default bucket ID: %s" % (os_bucket_id))
espath = siteInfo.getObjectstorePath(os_bucket_id=os_bucket_id, label='w')
tolog("ES path: %s" % (espath))
os_bucket_id = siteInfo.getObjectstoresField('os_bucket_id', 'eventservice')
tolog("The default bucket ID: %s for queue %s" % (os_bucket_id, self.__jobSite.computingElement))
res['setup'] = setup
res['esPath'] = espath
res['os_bucket_id'] = os_bucket_id
return res
def getYodaSetup(self):
siteInfo = self.__siteInfo
envsetup = siteInfo.readpar("envsetup")
setupPath = os.path.dirname(envsetup)
yodaSetup = os.path.join(setupPath, 'yodasetup.sh')
if os.path.exists(yodaSetup):
setup = ""
f = open(yodaSetup)
for line in f:
setup += line + "\n"
f.close()
return setup
return None
def setupHPCManager(self):
logFileName = None
tolog("runJobHPCEvent.getPilotLogFilename=%s"% self.getPilotLogFilename())
if self.getPilotLogFilename() != "":
logFileName = self.getPilotLogFilename()
defRes = self.getDefaultResources()
if defRes['copy_input_files'] == 'true' and defRes['localWorkingDir']:
self.__copyInputFiles = True
else:
self.__copyInputFiles = False
self.__nJobs = defRes['parallel_jobs']
self.__stageout_threads = defRes['stageout_threads']
self.__copyOutputToGlobal = defRes['copyOutputToGlobal']
tolog("Setup HPC Manager")
hpcManager = HPCManager(globalWorkingDir=self.__pilotWorkingDir, localWorkingDir=defRes['localWorkingDir'], logFileName=logFileName, copyInputFiles=self.__copyInputFiles)
#jobStateFile = '%s/jobState-%s.pickle' % (self.__pilotWorkingDir, self.__job.jobId)
#hpcManager.setPandaJobStateFile(jobStateFile)
self.__hpcMode = "HPC_" + hpcManager.getMode(defRes)
self.__hpcStatue = 'waitingResource'
pluginName = defRes.get('plugin', 'pbs')
hpcManager.setupPlugin(pluginName)
tolog("Get Yoda setup")
yodaSetup = self.getYodaSetup()
tolog("Yoda setup: %s" % yodaSetup)
hpcManager.setLocalSetup(yodaSetup)
tolog("HPC Manager getting free resouces")
hpcManager.getFreeResources(defRes)
self.__hpcStatue = 'gettingJobs'
tolog("HPC Manager getting needed events number")
self.__hpcEventRanges = hpcManager.getEventsNumber()
tolog("HPC Manager needs events: %s, max_events: %s; use the smallest one." % (self.__hpcEventRanges, defRes['max_events']))
if self.__hpcEventRanges > int(defRes['max_events']):
self.__hpcEventRanges = int(defRes['max_events'])
self.__neededEventRanges = self.__hpcEventRanges
self.__maxEventsPerJob = defRes['events_limit_per_job']
self.__hpcManager = hpcManager
tolog("HPC Manager setup finished")
def setupJob(self, job, data):
tolog("setupJob")
try:
job.coreCount = 0
job.hpcEvent = True
if self.__firstJob:
job.workdir = self.__jobSite.workdir
self.__firstJob = False
else:
# job.mkJobWorkdir(self.__pilotWorkingDir)
pass
job.experiment = self.getExperiment()
# figure out and set payload file names
job.setPayloadName(self.__thisExperiment.getPayloadName(job))
# reset the default job output file list which is anyway not correct
job.outFiles = []
except Exception, e:
pilotErrorDiag = "Failed to process job info: %s" % str(e)
tolog("!!WARNING!!3000!! %s" % (pilotErrorDiag))
self.failOneJob(0, PilotErrors.ERR_UNKNOWN, job, pilotErrorDiag=pilotErrorDiag, final=True, updatePanda=False)
return -1
current_dir = self.__pilotWorkingDir
os.chdir(job.workdir)
tolog("Switch from current dir %s to job %s workdir %s" % (current_dir, job.jobId, job.workdir))
self.__userid = job.prodUserID
self.__jobs[job.jobId] = {'job': job}
# prepare for the output file data directory
# (will only created for jobs that end up in a 'holding' state)
job.datadir = self.__pilotWorkingDir + "/PandaJob_%s_data" % (job.jobId)
# See if it's an analysis job or not
trf = job.trf
self.__jobs[job.jobId]['analysisJob'] = isAnalysisJob(trf.split(",")[0])
# Setup starts here ................................................................................
# Update the job state file
job.jobState = "starting"
job.setHpcStatus('init')
# Send [especially] the process group back to the pilot
job.setState([job.jobState, 0, 0])
job.jobState = job.result
rt = RunJobUtilities.updatePilotServer(job, self.getPilotServer(), self.getPilotPort())
JR = JobRecovery(pshttpurl='https://pandaserver.cern.ch', pilot_initdir=job.workdir)
JR.updateJobStateTest(job, self.__jobSite, self.__node, mode="test")
JR.updatePandaServer(job, self.__jobSite, self.__node, 25443)
self.__jobs[job.jobId]['job'] = job
self.__jobs[job.jobId]['JR'] = JR
# prepare the setup and get the run command list
ec, runCommandList, job, multi_trf = self.setup(job, self.__jobSite, self.__thisExperiment)
if ec != 0:
tolog("!!WARNING!!2999!! runJob setup failed: %s" % (job.pilotErrorDiag))
self.failOneJob(0, ec, job, pilotErrorDiag=job.pilotErrorDiag, final=True, updatePanda=False)
return -1
tolog("Setup has finished successfully")
# job has been updated, display it again
job.displayJob()
tolog("RunCommandList: %s" % runCommandList)
tolog("Multi_trf: %s" % multi_trf)
self.__jobs[job.jobId]['job'] = job
self.__jobs[job.jobId]['JR'] = JR
self.__jobs[job.jobId]['runCommandList'] = runCommandList
self.__jobs[job.jobId]['multi_trf'] = multi_trf
# backup job file
filename = os.path.join(self.__pilotWorkingDir, "Job_%s.json" % job.jobId)
content = {'workdir': job.workdir, 'data': data, 'experiment': self.getExperiment(), 'runCommandList': runCommandList}
with open(filename, 'w') as outputFile:
json.dump(content, outputFile)
# copy queue data
try:
copy_src = self.__siteInfo.getQueuedataFileName()
copy_dest = os.path.join(job.workdir, os.path.basename(copy_src))
tolog("Copy %s to %s" % (copy_src, copy_dest))
shutil.copyfile(copy_src, copy_dest)
except:
tolog("Failed to copy queuedata to job working dir: %s" % (traceback.format_exc()))
tolog("Switch back from job %s workdir %s to current dir %s" % (job.jobId, job.workdir, current_dir))
os.chdir(current_dir)
return 0
def getHPCEventJobFromPanda(self, nJobs=1):
try:
tolog("Switch to pilot working dir: %s" % self.__pilotWorkingDir)
os.chdir(self.__pilotWorkingDir)
tolog("Get new job from Panda")
getJob = GetJob(self.__pilotWorkingDir, self.__node, self.__siteInfo, self.__jobSite)
jobs, data, errLog = getJob.getNewJob(nJobs=nJobs)
if not jobs:
if "No job received from jobDispatcher" in errLog or "Dispatcher has no jobs" in errLog:
errorText = "!!FINISHED!!0!!Dispatcher has no jobs"
else:
errorText = "!!FAILED!!1999!!%s" % (errLog)
tolog(errorText)
# remove the site workdir before exiting
# pUtil.writeExitCode(thisSite.workdir, error.ERR_GENERALERROR)
# raise SystemError(1111)
#pUtil.fastCleanup(self.__jobSite.workdir, self.__pilotWorkingDir, True)
return -1
else:
for job in jobs:
tolog("download job definition id: %s" % (job.jobDefinitionID))
# verify any contradicting job definition parameters here
try:
ec, pilotErrorDiag = self.__thisExperiment.postGetJobActions(job)
if ec == 0:
tolog("postGetJobActions: OK")
# return ec
else:
tolog("!!WARNING!!1231!! Post getJob() actions encountered a problem - job will fail")
try:
# job must be failed correctly
pUtil.tolog("Updating PanDA server for the failed job (error code %d)" % (ec))
job.jobState = 'failed'
job.setState([job.jobState, 0, ec])
# note: job.workdir has not been created yet so cannot create log file
pilotErrorDiag = "Post getjob actions failed - workdir does not exist, cannot create job log, see batch log"
tolog("!!WARNING!!2233!! Work dir has not been created yet so cannot create job log in this case - refer to batch log")
JR = JobRecovery(pshttpurl='https://pandaserver.cern.ch', pilot_initdir=job.workdir)
JR.updatePandaServer(job, self.__jobSite, self.__node, 25443)
#pUtil.fastCleanup(self.__jobSite.workdir, self.__pilotWorkingDir, True)
#return ec
continue
except Exception, e:
pUtil.tolog("Caught exception: %s" % (e))
#return ec
continue
except Exception, e:
pUtil.tolog("Caught exception: %s" % (e))
#return -1
continue
self.setupJob(job, data[job.jobId])
tolog("Get Event Ranges for job %s" % job.jobId)
eventRanges = self.getJobEventRanges(job, numRanges=self.__neededEventRanges)
self.__neededEventRanges = self.__neededEventRanges - len(eventRanges)
tolog("Get %s Event ranges for job %s" % (len(eventRanges), job.jobId))
if len(eventRanges) > self.__maxEventsPerJob:
self.__maxEventsPerJob = len(eventRanges)
self.__eventRanges[job.jobId] = {}
self.__jobEventRanges[job.jobId] = eventRanges
for eventRange in eventRanges:
self.__eventRanges[job.jobId][eventRange['eventRangeID']] = 'new'
self.updateJobState(job, 'starting', '', final=False)
except:
tolog("Failed to get job: %s" % (traceback.format_exc()))
return -1
return 0
def getHPCEventJobFromEnv(self):
tolog("getHPCEventJobFromEnv")
try:
# always use this filename as the new jobDef module name
import newJobDef
job = Job.Job()
job.setJobDef(newJobDef.job)
logGUID = newJobDef.job.get('logGUID', "")
if logGUID != "NULL" and logGUID != "":
job.tarFileGuid = logGUID
if self.__firstJob:
job.workdir = self.__jobSite.workdir
self.__firstJob = False
self.__firstJobId = job.jobId
filename = os.path.join(self.__pilotWorkingDir, "Job_%s.json" % job.jobId)
content = {'workdir': job.workdir, 'data': newJobDef.job, 'experiment': self.__thisExperiment.getExperiment()}
with open(filename, 'w') as outputFile:
json.dump(content, outputFile)
self.__jobStateFile = '%s/jobState-%s.pickle' % (self.__pilotWorkingDir, job.jobId)
except Exception, e:
pilotErrorDiag = "Failed to process job info: %s" % str(e)
tolog("!!WARNING!!3000!! %s" % (pilotErrorDiag))
self.failOneJob(0, PilotErrors.ERR_UNKNOWN, job, pilotErrorDiag=pilotErrorDiag, final=True, updatePanda=False)
return -1
self.setupJob(job, newJobDef.job)
tolog("Get Event Ranges for job %s" % job.jobId)
eventRanges = self.getJobEventRanges(job, numRanges=self.__neededEventRanges)
self.__neededEventRanges = self.__neededEventRanges - len(eventRanges)
tolog("Get %s Event ranges for job %s" % (len(eventRanges), job.jobId))
if len(eventRanges) > self.__maxEventsPerJob:
self.__maxEventsPerJob = len(eventRanges)
self.__eventRanges[job.jobId] = {}
self.__jobEventRanges[job.jobId] = eventRanges
for eventRange in eventRanges:
self.__eventRanges[job.jobId][eventRange['eventRangeID']] = 'new'
self.updateJobState(job, 'starting', '', final=False)
return 0
def updateJobState(self, job, jobState, hpcState, final=False, updatePanda=True, errorCode=0):
job.HPCJobId = self.__hpcJobId
job.setMode(self.__hpcMode)
job.jobState = jobState
job.setState([job.jobState, 0, errorCode])
job.setHpcStatus(hpcState)
if job.pilotErrorDiag and len(job.pilotErrorDiag.strip()) == 0:
job.pilotErrorDiag = None
JR = self.__jobs[job.jobId]['JR']
pilotErrorDiag = job.pilotErrorDiag
JR.updateJobStateTest(job, self.__jobSite, self.__node, mode="test")
rt = RunJobUtilities.updatePilotServer(job, self.getPilotServer(), self.getPilotPort(), final=final)
if updatePanda:
JR.updatePandaServer(job, self.__jobSite, self.__node, 25443)
job.pilotErrorDiag = pilotErrorDiag
def updateAllJobsState(self, jobState, hpcState, final=False, updatePanda=False):
for jobId in self.__jobs:
self.updateJobState(self.__jobs[jobId]['job'], jobState, hpcState, final=final, updatePanda=updatePanda)
def getHPCEventJobs(self):
self.getHPCEventJobFromEnv()
tolog("NJobs: %s" % self.__nJobs)
failures = 0
while self.__neededEventRanges > 0 and (len(self.__jobs.keys()) < int(self.__nJobs)):
tolog("Len(jobs): %s" % len(self.__jobs.keys()))
tolog("NJobs: %s" % self.__nJobs)
toGetNJobs = self.__neededEventRanges/self.__maxEventsPerJob
if toGetNJobs < 1:
toGetNJobs = 1
if toGetNJobs > 50:
toGetNJobs = 50
tolog("Will try to get NJobs: %s" % toGetNJobs)
try:
ret = self.getHPCEventJobFromPanda(nJobs=toGetNJobs)
if ret != 0:
tolog("Failed to get a job from panda.")
failures += 1
except:
tolog("Failed to get job: %s" % (traceback.format_exc()))
failures += 1
if failures > 5:
break
self.__hpcStatue = ''
#self.updateAllJobsState('starting', self.__hpcStatue)
def stageInOneJob_new(self, job, jobSite, analysisJob, avail_files={}, pfc_name="PoolFileCatalog.xml"):
""" Perform the stage-in """
current_dir = self.__pilotWorkingDir
os.chdir(job.workdir)
tolog("Start to stage in input files for job %s" % job.jobId)
tolog("Switch from current dir %s to job %s workdir %s" % (current_dir, job.jobId, job.workdir))
real_stagein = False
for lfn in job.inFiles:
if not (lfn in self.__avail_files):
real_stagein = True
if not real_stagein:
tolog("All files for job %s have copies locally, will try to copy locally" % job.jobId)
for lfn in job.inFiles:
try:
copy_src = self.__avail_files[lfn]
copy_dest = os.path.join(job.workdir, lfn)
tolog("Copy %s to %s" % (copy_src, copy_dest))
shutil.copyfile(copy_src, copy_dest)
except:
tolog("Failed to copy file: %s" % traceback.format_exc())
real_stagein = True
break
if not real_stagein:
tolog("All files for job %s copied locally" % job.jobId)
tolog("Switch back from job %s workdir %s to current dir %s" % (job.jobId, job.workdir, current_dir))
os.chdir(current_dir)
return job, job.inFiles, None, None
tolog("Preparing for get command [stageIn_new]")
infiles = [e.lfn for e in job.inData]
tolog("Input file(s): (%s in total)" % len(infiles))
for ind, lfn in enumerate(infiles, 1):
tolog("%s. %s" % (ind, lfn))
if not infiles:
tolog("No input files for this job .. skip stage-in")
return job, infiles, None, False
t0 = os.times()
job.result[2], job.pilotErrorDiag, _dummy, FAX_dictionary = mover.get_data_new(job, jobSite, stageinTries=self.__stageinretry, proxycheck=False, workDir=job.workdir, pfc_name=pfc_name)
t1 = os.times()
job.timeStageIn = int(round(t1[4] - t0[4]))
usedFAXandDirectIO = FAX_dictionary.get('usedFAXandDirectIO', False)
statusPFCTurl = None
return job, infiles, statusPFCTurl, usedFAXandDirectIO
@mover.use_newmover(stageInOneJob_new)
def stageInOneJob(self, job, jobSite, analysisJob, avail_files={}, pfc_name="PoolFileCatalog.xml"):
""" Perform the stage-in """
current_dir = self.__pilotWorkingDir
os.chdir(job.workdir)
tolog("Start to stage in input files for job %s" % job.jobId)
tolog("Switch from current dir %s to job %s workdir %s" % (current_dir, job.jobId, job.workdir))
real_stagein = False
for lfn in job.inFiles:
if not (lfn in self.__avail_files):
real_stagein = True
if not real_stagein:
tolog("All files for job %s have copies locally, will try to copy locally" % job.jobId)
for lfn in job.inFiles:
try:
copy_src = self.__avail_files[lfn]
copy_dest = os.path.join(job.workdir, lfn)
tolog("Copy %s to %s" % (copy_src, copy_dest))
shutil.copyfile(copy_src, copy_dest)
except:
tolog("Failed to copy file: %s" % traceback.format_exc())
real_stagein = True
break
if not real_stagein:
tolog("All files for job %s copied locally" % job.jobId)
tolog("Switch back from job %s workdir %s to current dir %s" % (job.jobId, job.workdir, current_dir))
os.chdir(current_dir)
return job, job.inFiles, None, None
ec = 0
statusPFCTurl = None
usedFAXandDirectIO = False
# Prepare the input files (remove non-valid names) if there are any
ins, job.filesizeIn, job.checksumIn = RunJobUtilities.prepareInFiles(job.inFiles, job.filesizeIn, job.checksumIn)
if ins:
tolog("Preparing for get command")
# Get the file access info (only useCT is needed here)
useCT, oldPrefix, newPrefix = self.__siteInfo.getFileAccessInfo(job.transferType)
# Transfer input files
tin_0 = os.times()
ec, job.pilotErrorDiag, statusPFCTurl, FAX_dictionary = \
mover.get_data(job, jobSite, ins, self.__stageinretry, analysisJob=analysisJob, usect=useCT,\
pinitdir=self.getPilotInitDir(), proxycheck=False, inputDir='', workDir=job.workdir, pfc_name=pfc_name)
if ec != 0:
job.result[2] = ec
tin_1 = os.times()
job.timeStageIn = int(round(tin_1[4] - tin_0[4]))
# Extract any FAX info from the dictionary
if FAX_dictionary.has_key('N_filesWithoutFAX'):
job.filesWithoutFAX = FAX_dictionary['N_filesWithoutFAX']
if FAX_dictionary.has_key('N_filesWithFAX'):
job.filesWithFAX = FAX_dictionary['N_filesWithFAX']
if FAX_dictionary.has_key('bytesWithoutFAX'):
job.bytesWithoutFAX = FAX_dictionary['bytesWithoutFAX']
if FAX_dictionary.has_key('bytesWithFAX'):
job.bytesWithFAX = FAX_dictionary['bytesWithFAX']
if FAX_dictionary.has_key('usedFAXandDirectIO'):
usedFAXandDirectIO = FAX_dictionary['usedFAXandDirectIO']
tolog("Switch back from job %s workdir %s to current dir %s" % (job.jobId, job.workdir, current_dir))
os.chdir(current_dir)
if ec == 0:
for inFile in ins:
self.__avail_files[inFile] = os.path.join(job.workdir, inFile)
return job, ins, statusPFCTurl, usedFAXandDirectIO
def failOneJob(self, transExitCode, pilotExitCode, job, ins=None, pilotErrorDiag=None, docleanup=True, final=True, updatePanda=False):
""" set the fail code and exit """
current_dir = self.__pilotWorkingDir
if pilotExitCode and job.attemptNr < 4 and job.eventServiceMerge:
pilotExitCode = PilotErrors.ERR_ESRECOVERABLE
job.setState(["failed", transExitCode, pilotExitCode])
if pilotErrorDiag:
job.pilotErrorDiag = pilotErrorDiag
tolog("Job %s failed. Will now update local pilot TCP server" % job.jobId)
self.updateJobState(job, 'failed', 'failed', final=final, updatePanda=updatePanda)
if ins:
ec = pUtil.removeFiles(job.workdir, ins)
self.cleanup(job)
sys.stderr.close()
tolog("Job %s has failed" % job.jobId)
os.chdir(current_dir)
def failAllJobs(self, transExitCode, pilotExitCode, jobs, pilotErrorDiag=None, docleanup=True, updatePanda=False):
firstJob = None
for jobId in jobs:
if self.__firstJobId and (jobId == self.__firstJobId):
firstJob = jobs[jobId]['job']
continue
job = jobs[jobId]['job']
self.failOneJob(transExitCode, pilotExitCode, job, ins=job.inFiles, pilotErrorDiag=pilotErrorDiag, updatePanda=updatePanda)
if firstJob:
self.failOneJob(transExitCode, pilotExitCode, firstJob, ins=firstJob.inFiles, pilotErrorDiag=pilotErrorDiag, updatePanda=updatePanda)
os._exit(pilotExitCode)
def stageInHPCJobs(self):
tolog("Setting stage-in state until all input files have been copied")
jobResult = 0
pilotErrorDiag = ""
self.__avail_files = {}
failedJobIds = []
for jobId in self.__jobs:
try:
job = self.__jobs[jobId]['job']
# self.updateJobState(job, 'transferring', '')
self.updateJobState(job, 'starting', '')
# stage-in all input files (if necessary)
jobRet, ins, statusPFCTurl, usedFAXandDirectIO = self.stageInOneJob(job, self.__jobSite, self.__jobs[job.jobId]['analysisJob'], self.__avail_files, pfc_name="PFC.xml")
if jobRet.result[2] != 0:
tolog("Failing job with ec: %d" % (jobRet.result[2]))
jobResult = jobRet.result[2]
pilotErrorDiag = job.pilotErrorDiag
failedJobIds.append(jobId)
self.failOneJob(0, jobResult, job, ins=job.inFiles, pilotErrorDiag=pilotErrorDiag, updatePanda=True)
continue
#break
job.displayJob()
self.__jobs[job.jobId]['job'] = job
except:
tolog("stageInHPCJobsException")
try:
tolog(traceback.format_exc())
except:
tolog("Failed to print traceback")
job = self.__jobs[jobId]['job']
jobResult = PilotErrors.ERR_STAGEINFAILED
pilotErrorDiag = "stageInHPCJobsException"
failedJobIds.append(jobId)
self.failOneJob(0, jobResult, job, ins=job.inFiles, pilotErrorDiag=pilotErrorDiag, updatePanda=True)
for jobId in failedJobIds:
del self.__jobs[jobId]
#if jobResult != 0:
# self.failAllJobs(0, jobResult, self.__jobs, pilotErrorDiag=pilotErrorDiag)
def updateEventRange(self, event_range_id, jobid, status='finished', os_bucket_id=-1):
""" Update an event range on the Event Server """
message = EventRanges.updateEventRange(event_range_id, [], jobid, status, os_bucket_id)
return 0, message
def updateEventRanges(self, event_ranges):
""" Update an event range on the Event Server """
return EventRanges.updateEventRanges(event_ranges, url=self.getPanDAServer())
return status, message
def getJobEventRanges(self, job, numRanges=2):
""" Download event ranges from the Event Server """
tolog("Server: Downloading new event ranges..")
message = EventRanges.downloadEventRanges(job.jobId, job.jobsetID, job.taskID, numRanges=numRanges, url=self.getPanDAServer())
try:
if "Failed" in message or "No more events" in message:
tolog(message)
return []
else:
return json.loads(message)
except:
tolog(traceback.format_exc())
return []
def updateHPCEventRanges(self):
for jobId in self.__eventRanges:
for eventRangeID in self.__eventRanges[jobId]:
if self.__eventRanges[jobId][eventRangeID] == 'stagedOut' or self.__eventRanges[jobId][eventRangeID] == 'failed':
if self.__eventRanges[jobId][eventRangeID] == 'stagedOut':
eventStatus = 'finished'
else:
eventStatus = 'failed'
try:
ret, message = self.updateEventRange(eventRangeID, jobId, eventStatus)
except Exception, e:
tolog("Failed to update event range: %s, %s, exception: %s " % (eventRangeID, eventStatus, str(e)))
else:
if ret == 0:
self.__eventRanges[jobId][eventRangeID] = "Done"
else:
tolog("Failed to update event range: %s" % eventRangeID)
def prepareHPCJob(self, job):
tolog("Prepare for job %s" % job.jobId)
current_dir = self.__pilotWorkingDir
os.chdir(job.workdir)
tolog("Switch from current dir %s to job %s workdir %s" % (current_dir, job.jobId, job.workdir))
#print self.__runCommandList
#print self.getParentWorkDir()
#print self.__job.workdir
# 1. input files
inputFiles = []
inputFilesGlobal = []
for inputFile in job.inFiles:
#inputFiles.append(os.path.join(self.__job.workdir, inputFile))
inputFilesGlobal.append(os.path.join(job.workdir, inputFile))
inputFiles.append(os.path.join('HPCWORKINGDIR', inputFile))
inputFileDict = dict(zip(job.inFilesGuids, inputFilesGlobal))
self.__jobs[job.jobId]['inputFilesGlobal'] = inputFilesGlobal
tagFiles = {}
EventFiles = {}
for guid in inputFileDict:
if '.TAG.' in inputFileDict[guid]:
tagFiles[guid] = inputFileDict[guid]
elif not "DBRelease" in inputFileDict[guid]:
EventFiles[guid] = {}
EventFiles[guid]['file'] = inputFileDict[guid]
# 2. create TAG file
jobRunCmd = self.__jobs[job.jobId]['runCommandList'][0]
usingTokenExtractor = 'TokenScatterer' in jobRunCmd or 'UseTokenExtractor=True' in jobRunCmd.replace(" ","").replace(" ","")
if usingTokenExtractor:
for guid in EventFiles:
local_copy = False
if guid in self.__avail_tag_files:
local_copy = True
try:
tolog("Copy TAG file from %s to %s" % (self.__avail_tag_files[guid]['TAG_path'], job.workdir))
shutil.copy(self.__avail_tag_files[guid]['TAG_path'], job.workdir)
except:
tolog("Failed to copy %s to %s" % (self.__avail_tag_files[guid]['TAG_path'], job.workdir))
local_copy = False
if local_copy:
tolog("Tag file for %s already copied locally. Will not create it again" % guid)
EventFiles[guid]['TAG'] = self.__avail_tag_files[guid]['TAG']
EventFiles[guid]['TAG_guid'] = self.__avail_tag_files[guid]['TAG_guid']
else:
tolog("Tag file for %s does not exist. Will create it." % guid)
inFiles = [EventFiles[guid]['file']]
input_tag_file, input_tag_file_guid = self.createTAGFile(self.__jobs[job.jobId]['runCommandList'][0], job.trf, inFiles, "MakeRunEventCollection.py")
if input_tag_file != "" and input_tag_file_guid != "":
tolog("Will run TokenExtractor on file %s" % (input_tag_file))
EventFiles[guid]['TAG'] = input_tag_file
EventFiles[guid]['TAG_guid'] = input_tag_file_guid
self.__avail_tag_files[guid] = {'TAG': input_tag_file, 'TAG_path': os.path.join(job.workdir, input_tag_file), 'TAG_guid': input_tag_file_guid}
else:
# only for current test
if len(tagFiles)>0:
EventFiles[guid]['TAG_guid'] = tagFiles.keys()[0]
EventFiles[guid]['TAG'] = tagFiles[tagFiles.keys()[0]]
else:
return -1, "Failed to create the TAG file", None
# 3. create Pool File Catalog
inputFileDict = dict(zip(job.inFilesGuids, inputFilesGlobal))
poolFileCatalog = os.path.join(job.workdir, "PoolFileCatalog_HPC.xml")
createPoolFileCatalog(inputFileDict, [], pfc_name=poolFileCatalog)
inputFileDictTemp = dict(zip(job.inFilesGuids, inputFiles))
poolFileCatalogTemp = os.path.join(job.workdir, "PoolFileCatalog_Temp.xml")
poolFileCatalogTempName = "HPCWORKINGDIR/PoolFileCatalog_Temp.xml"
createPoolFileCatalog(inputFileDictTemp, [], pfc_name=poolFileCatalogTemp)
self.__jobs[job.jobId]['poolFileCatalog'] = poolFileCatalog
self.__jobs[job.jobId]['poolFileCatalogTemp'] = poolFileCatalogTemp
self.__jobs[job.jobId]['poolFileCatalogTempName'] = poolFileCatalogTempName
# 4. getSetupCommand
setupCommand = self.stripSetupCommand(self.__jobs[job.jobId]['runCommandList'][0], job.trf)
_cmd = re.search('(source.+\;)', setupCommand)
source_setup = None
if _cmd:
setup = _cmd.group(1)
source_setup = setup.split(";")[0]
#setupCommand = setupCommand.replace(source_setup, source_setup + " --cmtextratags=ATLAS,useDBRelease")
# for test, asetup has a bug
#new_source_setup = source_setup.split("cmtsite/asetup.sh")[0] + "setup-19.2.0-quick.sh"
#setupCommand = setupCommand.replace(source_setup, new_source_setup)
tolog("setup command: " + setupCommand)
# 5. check if release-compact.tgz exists. If it exists, use it.
preSetup = None
postRun = None
# yoda_setup_command = 'export USING_COMPACT=1; %s' % source_setup
# 6. AthenaMP command
runCommandList_0 = self.__jobs[job.jobId]['runCommandList'][0]
runCommandList_0 = 'export USING_COMPACT=1; %s' % runCommandList_0
# Tell AthenaMP the name of the yampl channel
runCommandList_0 = 'export PILOT_EVENTRANGECHANNEL=PILOT_EVENTRANGECHANNEL_CHANGE_ME; %s' % runCommandList_0
if not "--preExec" in runCommandList_0:
runCommandList_0 += " --preExec \'from AthenaMP.AthenaMPFlags import jobproperties as jps;jps.AthenaMPFlags.EventRangeChannel=\"PILOT_EVENTRANGECHANNEL_CHANGE_ME\"\' "
else:
if "import jobproperties as jps" in runCommandList_0:
runCommandList_0 = runCommandList_0.replace("import jobproperties as jps;", "import jobproperties as jps;jps.AthenaMPFlags.EventRangeChannel=\"PILOT_EVENTRANGECHANNEL_CHANGE_ME\";")
else:
if "--preExec " in runCommandList_0:
runCommandList_0 = runCommandList_0.replace("--preExec ", "--preExec \'from AthenaMP.AthenaMPFlags import jobproperties as jps;jps.AthenaMPFlags.EventRangeChannel=\"PILOT_EVENTRANGECHANNEL_CHANGE_ME\"\' ")
else:
tolog("!!WARNING!!43431! --preExec has an unknown format - expected \'--preExec \"\' or \"--preExec \'\", got: %s" % (runCommandList[0]))
# if yoda_setup_command:
# runCommandList_0 = self.__jobs[job.jobId]['runCommandList'][0]
# runCommandList_0 = runCommandList_0.replace(source_setup, yoda_setup_command)
if not self.__copyInputFiles:
jobInputFileList = None
# jobInputFileList = inputFilesGlobal[0]
for inputFile in job.inFiles:
if not jobInputFileList:
jobInputFileList = os.path.join(job.workdir, inputFile)
else:
jobInputFileList += "," + os.path.join(job.workdir, inputFile)
command_list = runCommandList_0.split(" ")
command_list_new = []
for command_part in command_list:
if command_part.startswith("--input"):
command_arg = command_part.split("=")[0]
command_part_new = command_arg + "=" + jobInputFileList
command_list_new.append(command_part_new)
else:
command_list_new.append(command_part)
runCommandList_0 = " ".join(command_list_new)
#runCommandList_0 += " '--postExec' 'svcMgr.PoolSvc.ReadCatalog += [\"xmlcatalog_file:%s\"]'" % (poolFileCatalog)
else:
#runCommandList_0 += " '--postExec' 'svcMgr.PoolSvc.ReadCatalog += [\"xmlcatalog_file:%s\"]'" % (poolFileCatalogTempName)
pass
# should not have --DBRelease and UserFrontier.py in HPC
if not os.environ.has_key('Nordugrid_pilot'):
runCommandList_0 = runCommandList_0.replace("--DBRelease=current", "").replace('--DBRelease="default:current"', '').replace("--DBRelease='default:current'", '')
if 'RecJobTransforms/UseFrontier.py,' in runCommandList_0:
runCommandList_0 = runCommandList_0.replace('RecJobTransforms/UseFrontier.py,', '')
if ',RecJobTransforms/UseFrontier.py' in runCommandList_0:
runCommandList_0 = runCommandList_0.replace(',RecJobTransforms/UseFrontier.py', '')
if ' --postInclude=RecJobTransforms/UseFrontier.py ' in runCommandList_0:
runCommandList_0 = runCommandList_0.replace(' --postInclude=RecJobTransforms/UseFrontier.py ', ' ')
if '--postInclude "default:RecJobTransforms/UseFrontier.py"' in runCommandList_0:
runCommandList_0 = runCommandList_0.replace('--postInclude "default:RecJobTransforms/UseFrontier.py"', ' ')
runCommandList_0 = runCommandList_0.replace('--postInclude "default:PyJobTransforms/UseFrontier.py"', ' ')
runCommandList_0 += " 1>athenaMP_stdout.txt 2>athenaMP_stderr.txt"
runCommandList_0 = runCommandList_0.replace(";;", ";")
#self.__jobs[job.jobId]['runCommandList'][0] = runCommandList_0
# 7. Token Extractor file list
# in the token extractor file list, the guid is the Event guid, not the tag guid.
if usingTokenExtractor:
tagFile_list = os.path.join(job.workdir, "TokenExtractor_filelist")
handle = open(tagFile_list, 'w')
for guid in EventFiles:
tagFile = EventFiles[guid]['TAG']
line = guid + ",PFN:" + tagFile + "\n"
handle.write(line)
handle.close()
self.__jobs[job.jobId]['tagFile_list'] = tagFile_list
else:
self.__jobs[job.jobId]['tagFile_list'] = None
# 8. Token Extractor command
if usingTokenExtractor:
setup = setupCommand
tokenExtractorCmd = setup + " TokenExtractor -v --source " + tagFile_list + " 1>tokenExtract_stdout.txt 2>tokenExtract_stderr.txt"
tokenExtractorCmd = tokenExtractorCmd.replace(";;", ";").replace("; ;", ";")
self.__jobs[job.jobId]['tokenExtractorCmd'] = tokenExtractorCmd
else:
self.__jobs[job.jobId]['tokenExtractorCmd'] = None
if self.__yoda_to_zip or self.__es_to_zip:
self.__jobs[job.jobId]['job'].outputZipName = os.path.join(self.__pilotWorkingDir, "EventService_premerge_%s.tar" % job.jobId)
self.__jobs[job.jobId]['job'].outputZipEventRangesName = os.path.join(self.__pilotWorkingDir, "EventService_premerge_eventranges_%s.txt" % job.jobId)
os.chdir(current_dir)
tolog("Switch back from job %s workdir %s to current dir %s" % (job.jobId, job.workdir, current_dir))
return 0, None, {"TokenExtractCmd": self.__jobs[job.jobId]['tokenExtractorCmd'], "AthenaMPCmd": runCommandList_0, "PreSetup": preSetup, "PostRun": postRun, 'PoolFileCatalog': poolFileCatalog, 'InputFiles': inputFilesGlobal, 'GlobalWorkingDir': job.workdir, 'zipFileName': self.__jobs[job.jobId]['job'].outputZipName, 'zipEventRangesName': self.__jobs[job.jobId]['job'].outputZipEventRangesName, 'stageout_threads': self.__stageout_threads}
def prepareHPCJobs(self):