ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.52
Committed: Tue Oct 17 11:54:02 2006 UTC (18 years, 6 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_1_4_1_pre1, CRAB_1_4_0, CRAB_1_4_0_pre4
Changes since 1.51: +0 -2 lines
Log Message:
forgot printout

File Contents

# User Rev Content
1 slacapra 1.1 from JobType import JobType
2     from crab_logger import Logger
3     from crab_exceptions import *
4     from crab_util import *
5 slacapra 1.22 import math
6 slacapra 1.1 import common
7 gutsche 1.3 import PsetManipulator
8 slacapra 1.1
9 slacapra 1.41 import DBSInfo
10     import DataDiscovery
11     import DataLocation
12 slacapra 1.1 import Scram
13    
14 slacapra 1.45 import glob, os, string, re
15 slacapra 1.1
16     class Cmssw(JobType):
17 gutsche 1.38 def __init__(self, cfg_params, ncjobs):
18 slacapra 1.1 JobType.__init__(self, 'CMSSW')
19     common.logger.debug(3,'CMSSW::__init__')
20    
21 gutsche 1.3 # Marco.
22     self._params = {}
23     self.cfg_params = cfg_params
24 gutsche 1.38
25 gutsche 1.44 # number of jobs requested to be created, limit obj splitting
26 gutsche 1.38 self.ncjobs = ncjobs
27    
28 slacapra 1.1 log = common.logger
29    
30     self.scram = Scram.Scram(cfg_params)
31     scramArea = ''
32     self.additional_inbox_files = []
33     self.scriptExe = ''
34     self.executable = ''
35     self.tgz_name = 'default.tgz'
36 spiga 1.42 self.pset = '' #scrip use case Da
37     self.datasetPath = '' #scrip use case Da
38 gutsche 1.3
39 gutsche 1.50 # set FJR file name
40     self.fjrFileName = 'crab_fjr.xml'
41    
42 slacapra 1.1 self.version = self.scram.getSWVersion()
43 gutsche 1.5 self.setParam_('application', self.version)
44 slacapra 1.47
45 slacapra 1.1 ### collect Data cards
46     try:
47 slacapra 1.9 tmp = cfg_params['CMSSW.datasetpath']
48     log.debug(6, "CMSSW::CMSSW(): datasetPath = "+tmp)
49     if string.lower(tmp)=='none':
50     self.datasetPath = None
51 slacapra 1.21 self.selectNoInput = 1
52 slacapra 1.9 else:
53     self.datasetPath = tmp
54 slacapra 1.21 self.selectNoInput = 0
55 slacapra 1.1 except KeyError:
56 gutsche 1.3 msg = "Error: datasetpath not defined "
57 slacapra 1.1 raise CrabException(msg)
58 gutsche 1.5
59     # ML monitoring
60     # split dataset path style: /PreProdR3Minbias/SIM/GEN-SIM
61 slacapra 1.9 if not self.datasetPath:
62     self.setParam_('dataset', 'None')
63     self.setParam_('owner', 'None')
64     else:
65     datasetpath_split = self.datasetPath.split("/")
66     self.setParam_('dataset', datasetpath_split[1])
67     self.setParam_('owner', datasetpath_split[-1])
68    
69 gutsche 1.8 self.setTaskid_()
70     self.setParam_('taskId', self.cfg_params['taskId'])
71 gutsche 1.5
72 slacapra 1.1 self.dataTiers = []
73    
74     ## now the application
75     try:
76     self.executable = cfg_params['CMSSW.executable']
77 gutsche 1.5 self.setParam_('exe', self.executable)
78 slacapra 1.1 log.debug(6, "CMSSW::CMSSW(): executable = "+self.executable)
79     msg = "Default executable cmsRun overridden. Switch to " + self.executable
80     log.debug(3,msg)
81     except KeyError:
82     self.executable = 'cmsRun'
83 gutsche 1.5 self.setParam_('exe', self.executable)
84 slacapra 1.1 msg = "User executable not defined. Use cmsRun"
85     log.debug(3,msg)
86     pass
87    
88     try:
89     self.pset = cfg_params['CMSSW.pset']
90     log.debug(6, "Cmssw::Cmssw(): PSet file = "+self.pset)
91 spiga 1.42 if self.pset.lower() != 'none' :
92     if (not os.path.exists(self.pset)):
93     raise CrabException("User defined PSet file "+self.pset+" does not exist")
94     else:
95     self.pset = None
96 slacapra 1.1 except KeyError:
97     raise CrabException("PSet file missing. Cannot run cmsRun ")
98    
99     # output files
100     try:
101     self.output_file = []
102    
103 gutsche 1.50 # add fjr report by default
104     self.output_file.append(self.fjrFileName)
105    
106 slacapra 1.1 tmp = cfg_params['CMSSW.output_file']
107     if tmp != '':
108     tmpOutFiles = string.split(cfg_params['CMSSW.output_file'],',')
109     log.debug(7, 'cmssw::cmssw(): output files '+str(tmpOutFiles))
110     for tmp in tmpOutFiles:
111     tmp=string.strip(tmp)
112     self.output_file.append(tmp)
113     pass
114     else:
115 gutsche 1.50 log.message("No output file defined: only stdout/err and the CRAB Framework Job Report will be available")
116 slacapra 1.1 pass
117     pass
118     except KeyError:
119 gutsche 1.50 log.message("No output file defined: only stdout/err and the CRAB Framework Job Report will be available")
120 slacapra 1.1 pass
121    
122     # script_exe file as additional file in inputSandbox
123     try:
124 slacapra 1.10 self.scriptExe = cfg_params['USER.script_exe']
125     if self.scriptExe != '':
126     if not os.path.isfile(self.scriptExe):
127     msg ="WARNING. file "+self.scriptExe+" not found"
128     raise CrabException(msg)
129 spiga 1.42 self.additional_inbox_files.append(string.strip(self.scriptExe))
130 slacapra 1.1 except KeyError:
131 spiga 1.42 self.scriptExe = ''
132     #CarlosDaniele
133     if self.datasetPath == None and self.pset == None and self.scriptExe == '' :
134     msg ="WARNING. script_exe not defined"
135     raise CrabException(msg)
136    
137 slacapra 1.1 ## additional input files
138     try:
139 slacapra 1.29 tmpAddFiles = string.split(cfg_params['USER.additional_input_files'],',')
140 slacapra 1.1 for tmp in tmpAddFiles:
141 slacapra 1.51 tmp = string.strip(tmp)
142 slacapra 1.45 dirname = ''
143     if not tmp[0]=="/": dirname = "."
144     files = glob.glob(os.path.join(dirname, tmp))
145     for file in files:
146     if not os.path.exists(file):
147     raise CrabException("Additional input file not found: "+file)
148     pass
149     self.additional_inbox_files.append(string.strip(file))
150 slacapra 1.1 pass
151     pass
152 slacapra 1.45 common.logger.debug(5,"Additional input files: "+str(self.additional_inbox_files))
153 slacapra 1.1 except KeyError:
154     pass
155    
156 slacapra 1.9 # files per job
157 slacapra 1.1 try:
158 gutsche 1.35 if (cfg_params['CMSSW.files_per_jobs']):
159     raise CrabException("files_per_jobs no longer supported. Quitting.")
160 gutsche 1.3 except KeyError:
161 gutsche 1.35 pass
162 gutsche 1.3
163 slacapra 1.9 ## Events per job
164 gutsche 1.3 try:
165 slacapra 1.10 self.eventsPerJob =int( cfg_params['CMSSW.events_per_job'])
166 slacapra 1.9 self.selectEventsPerJob = 1
167 gutsche 1.3 except KeyError:
168 slacapra 1.9 self.eventsPerJob = -1
169     self.selectEventsPerJob = 0
170    
171 slacapra 1.22 ## number of jobs
172     try:
173     self.theNumberOfJobs =int( cfg_params['CMSSW.number_of_jobs'])
174     self.selectNumberOfJobs = 1
175     except KeyError:
176     self.theNumberOfJobs = 0
177     self.selectNumberOfJobs = 0
178 slacapra 1.10
179 gutsche 1.35 try:
180     self.total_number_of_events = int(cfg_params['CMSSW.total_number_of_events'])
181     self.selectTotalNumberEvents = 1
182     except KeyError:
183     self.total_number_of_events = 0
184     self.selectTotalNumberEvents = 0
185    
186 spiga 1.42 if self.pset != None: #CarlosDaniele
187     if ( (self.selectTotalNumberEvents + self.selectEventsPerJob + self.selectNumberOfJobs) != 2 ):
188     msg = 'Must define exactly two of total_number_of_events, events_per_job, or number_of_jobs.'
189     raise CrabException(msg)
190     else:
191     if (self.selectNumberOfJobs == 0):
192     msg = 'Must specify number_of_jobs.'
193     raise CrabException(msg)
194 gutsche 1.35
195 slacapra 1.22 ## source seed for pythia
196     try:
197     self.sourceSeed = int(cfg_params['CMSSW.pythia_seed'])
198     except KeyError:
199 slacapra 1.23 self.sourceSeed = None
200     common.logger.debug(5,"No seed given")
201 slacapra 1.22
202 slacapra 1.28 try:
203     self.sourceSeedVtx = int(cfg_params['CMSSW.vtx_seed'])
204     except KeyError:
205     self.sourceSeedVtx = None
206     common.logger.debug(5,"No vertex seed given")
207 spiga 1.42 if self.pset != None: #CarlosDaniele
208     self.PsetEdit = PsetManipulator.PsetManipulator(self.pset) #Daniele Pset
209 gutsche 1.3
210 slacapra 1.1 #DBSDLS-start
211     ## Initialize the variables that are extracted from DBS/DLS and needed in other places of the code
212     self.maxEvents=0 # max events available ( --> check the requested nb. of evts in Creator.py)
213     self.DBSPaths={} # all dbs paths requested ( --> input to the site local discovery script)
214 gutsche 1.35 self.jobDestination=[] # Site destination(s) for each job (list of lists)
215 slacapra 1.1 ## Perform the data location and discovery (based on DBS/DLS)
216 slacapra 1.9 ## SL: Don't if NONE is specified as input (pythia use case)
217 gutsche 1.35 blockSites = {}
218 slacapra 1.9 if self.datasetPath:
219 gutsche 1.35 blockSites = self.DataDiscoveryAndLocation(cfg_params)
220 slacapra 1.1 #DBSDLS-end
221    
222     self.tgzNameWithPath = self.getTarBall(self.executable)
223 slacapra 1.10
224 slacapra 1.9 ## Select Splitting
225 spiga 1.42 if self.selectNoInput:
226     if self.pset == None: #CarlosDaniele
227     self.jobSplittingForScript()
228     else:
229     self.jobSplittingNoInput()
230 gutsche 1.35 else: self.jobSplittingByBlocks(blockSites)
231 gutsche 1.5
232 slacapra 1.22 # modify Pset
233 spiga 1.42 if self.pset != None: #CarlosDaniele
234     try:
235     if (self.datasetPath): # standard job
236     # allow to processa a fraction of events in a file
237     self.PsetEdit.inputModule("INPUT")
238     self.PsetEdit.maxEvent("INPUTMAXEVENTS")
239     self.PsetEdit.skipEvent("INPUTSKIPEVENTS")
240     else: # pythia like job
241     self.PsetEdit.maxEvent(self.eventsPerJob)
242     if (self.sourceSeed) :
243     self.PsetEdit.pythiaSeed("INPUT")
244     if (self.sourceSeedVtx) :
245     self.PsetEdit.pythiaSeedVtx("INPUTVTX")
246 gutsche 1.50 # add FrameworkJobReport to parameter-set
247     self.PsetEdit.addCrabFJR(self.fjrFileName)
248 spiga 1.42 self.PsetEdit.psetWriter(self.configFilename())
249     except:
250     msg='Error while manipuliating ParameterSet: exiting...'
251     raise CrabException(msg)
252 gutsche 1.3
253 slacapra 1.1 def DataDiscoveryAndLocation(self, cfg_params):
254    
255 gutsche 1.3 common.logger.debug(10,"CMSSW::DataDiscoveryAndLocation()")
256    
257     datasetPath=self.datasetPath
258    
259     ## TODO
260     dataTiersList = ""
261     dataTiers = dataTiersList.split(',')
262 slacapra 1.1
263     ## Contact the DBS
264 slacapra 1.41 common.logger.message("Contacting DBS...")
265 slacapra 1.1 try:
266 slacapra 1.41 self.pubdata=DataDiscovery.DataDiscovery(datasetPath, dataTiers, cfg_params)
267 slacapra 1.1 self.pubdata.fetchDBSInfo()
268    
269 slacapra 1.41 except DataDiscovery.NotExistingDatasetError, ex :
270 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
271     raise CrabException(msg)
272    
273 slacapra 1.41 except DataDiscovery.NoDataTierinProvenanceError, ex :
274 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
275     raise CrabException(msg)
276 slacapra 1.41 except DataDiscovery.DataDiscoveryError, ex:
277 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS %s'%ex.getErrorMessage()
278     raise CrabException(msg)
279    
280     ## get list of all required data in the form of dbs paths (dbs path = /dataset/datatier/owner)
281 gutsche 1.3 ## self.DBSPaths=self.pubdata.getDBSPaths()
282     common.logger.message("Required data are :"+self.datasetPath)
283    
284 gutsche 1.35 self.filesbyblock=self.pubdata.getFiles()
285 mkirn 1.37 self.eventsbyblock=self.pubdata.getEventsPerBlock()
286     self.eventsbyfile=self.pubdata.getEventsPerFile()
287 slacapra 1.41 # print str(self.filesbyblock)
288     # print 'self.eventsbyfile',len(self.eventsbyfile)
289     # print str(self.eventsbyfile)
290 gutsche 1.3
291 slacapra 1.1 ## get max number of events
292     self.maxEvents=self.pubdata.getMaxEvents() ## self.maxEvents used in Creator.py
293 gutsche 1.44 common.logger.message("The number of available events is %s\n"%self.maxEvents)
294 slacapra 1.1
295 slacapra 1.41 common.logger.message("Contacting DLS...")
296 slacapra 1.1 ## Contact the DLS and build a list of sites hosting the fileblocks
297     try:
298 slacapra 1.41 dataloc=DataLocation.DataLocation(self.filesbyblock.keys(),cfg_params)
299 gutsche 1.6 dataloc.fetchDLSInfo()
300 slacapra 1.41 except DataLocation.DataLocationError , ex:
301 slacapra 1.1 msg = 'ERROR ***: failed Data Location in DLS \n %s '%ex.getErrorMessage()
302     raise CrabException(msg)
303    
304    
305 gutsche 1.35 sites = dataloc.getSites()
306     allSites = []
307     listSites = sites.values()
308     for list in listSites:
309     for oneSite in list:
310     allSites.append(oneSite)
311     allSites = self.uniquelist(allSites)
312 gutsche 1.3
313 gutsche 1.35 common.logger.message("Sites ("+str(len(allSites))+") hosting part/all of dataset: "+str(allSites))
314     common.logger.debug(6, "List of Sites: "+str(allSites))
315     return sites
316 gutsche 1.3
317 gutsche 1.35 def jobSplittingByBlocks(self, blockSites):
318 slacapra 1.9 """
319 gutsche 1.35 Perform job splitting. Jobs run over an integer number of files
320     and no more than one block.
321     ARGUMENT: blockSites: dictionary with blocks as keys and list of host sites as values
322     REQUIRES: self.selectTotalNumberEvents, self.selectEventsPerJob, self.selectNumberofJobs,
323     self.total_number_of_events, self.eventsPerJob, self.theNumberOfJobs,
324     self.maxEvents, self.filesbyblock
325     SETS: self.jobDestination - Site destination(s) for each job (a list of lists)
326     self.total_number_of_jobs - Total # of jobs
327     self.list_of_args - File(s) job will run on (a list of lists)
328     """
329    
330     # ---- Handle the possible job splitting configurations ---- #
331     if (self.selectTotalNumberEvents):
332     totalEventsRequested = self.total_number_of_events
333     if (self.selectEventsPerJob):
334     eventsPerJobRequested = self.eventsPerJob
335     if (self.selectNumberOfJobs):
336     totalEventsRequested = self.theNumberOfJobs * self.eventsPerJob
337    
338     # If user requested all the events in the dataset
339     if (totalEventsRequested == -1):
340     eventsRemaining=self.maxEvents
341     # If user requested more events than are in the dataset
342     elif (totalEventsRequested > self.maxEvents):
343     eventsRemaining = self.maxEvents
344     common.logger.message("Requested "+str(self.total_number_of_events)+ " events, but only "+str(self.maxEvents)+" events are available.")
345     # If user requested less events than are in the dataset
346     else:
347     eventsRemaining = totalEventsRequested
348 slacapra 1.22
349 slacapra 1.41 # If user requested more events per job than are in the dataset
350     if (self.selectEventsPerJob and eventsPerJobRequested > self.maxEvents):
351     eventsPerJobRequested = self.maxEvents
352    
353 gutsche 1.35 # For user info at end
354     totalEventCount = 0
355 gutsche 1.3
356 gutsche 1.35 if (self.selectTotalNumberEvents and self.selectNumberOfJobs):
357     eventsPerJobRequested = int(eventsRemaining/self.theNumberOfJobs)
358 slacapra 1.22
359 gutsche 1.35 if (self.selectNumberOfJobs):
360     common.logger.message("May not create the exact number_of_jobs requested.")
361 slacapra 1.23
362 gutsche 1.38 if ( self.ncjobs == 'all' ) :
363     totalNumberOfJobs = 999999999
364     else :
365     totalNumberOfJobs = self.ncjobs
366    
367    
368 gutsche 1.35 blocks = blockSites.keys()
369     blockCount = 0
370     # Backup variable in case self.maxEvents counted events in a non-included block
371     numBlocksInDataset = len(blocks)
372 gutsche 1.3
373 gutsche 1.35 jobCount = 0
374     list_of_lists = []
375 gutsche 1.3
376 gutsche 1.35 # ---- Iterate over the blocks in the dataset until ---- #
377     # ---- we've met the requested total # of events ---- #
378 gutsche 1.38 while ( (eventsRemaining > 0) and (blockCount < numBlocksInDataset) and (jobCount < totalNumberOfJobs)):
379 gutsche 1.35 block = blocks[blockCount]
380 gutsche 1.44 blockCount += 1
381    
382 gutsche 1.3
383 gutsche 1.44 numEventsInBlock = self.eventsbyblock[block]
384     common.logger.debug(5,'Events in Block File '+str(numEventsInBlock))
385 slacapra 1.9
386 gutsche 1.35 files = self.filesbyblock[block]
387     numFilesInBlock = len(files)
388     if (numFilesInBlock <= 0):
389     continue
390     fileCount = 0
391    
392     # ---- New block => New job ---- #
393     parString = "\\{"
394 gutsche 1.38 # counter for number of events in files currently worked on
395     filesEventCount = 0
396     # flag if next while loop should touch new file
397     newFile = 1
398     # job event counter
399     jobSkipEventCount = 0
400 slacapra 1.9
401 gutsche 1.35 # ---- Iterate over the files in the block until we've met the requested ---- #
402     # ---- total # of events or we've gone over all the files in this block ---- #
403 gutsche 1.38 while ( (eventsRemaining > 0) and (fileCount < numFilesInBlock) and (jobCount < totalNumberOfJobs) ):
404 gutsche 1.35 file = files[fileCount]
405 gutsche 1.38 if newFile :
406 slacapra 1.41 try:
407     numEventsInFile = self.eventsbyfile[file]
408     common.logger.debug(6, "File "+str(file)+" has "+str(numEventsInFile)+" events")
409     # increase filesEventCount
410     filesEventCount += numEventsInFile
411     # Add file to current job
412     parString += '\\\"' + file + '\\\"\,'
413     newFile = 0
414     except KeyError:
415 gutsche 1.44 common.logger.message("File "+str(file)+" has unknown number of events: skipping")
416 slacapra 1.41
417 gutsche 1.38
418     # if less events in file remain than eventsPerJobRequested
419     if ( filesEventCount - jobSkipEventCount < eventsPerJobRequested ) :
420     # if last file in block
421 gutsche 1.44 if ( fileCount == numFilesInBlock-1 ) :
422 gutsche 1.38 # end job using last file, use remaining events in block
423     # close job and touch new file
424     fullString = parString[:-2]
425     fullString += '\\}'
426     list_of_lists.append([fullString,str(-1),str(jobSkipEventCount)])
427 slacapra 1.41 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(filesEventCount - jobSkipEventCount)+" events (last file in block).")
428 gutsche 1.38 self.jobDestination.append(blockSites[block])
429     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
430     # reset counter
431     jobCount = jobCount + 1
432 gutsche 1.44 totalEventCount = totalEventCount + filesEventCount - jobSkipEventCount
433     eventsRemaining = eventsRemaining - filesEventCount + jobSkipEventCount
434 gutsche 1.38 jobSkipEventCount = 0
435     # reset file
436     parString = "\\{"
437     filesEventCount = 0
438     newFile = 1
439     fileCount += 1
440     else :
441     # go to next file
442     newFile = 1
443     fileCount += 1
444     # if events in file equal to eventsPerJobRequested
445     elif ( filesEventCount - jobSkipEventCount == eventsPerJobRequested ) :
446     # close job and touch new file
447 gutsche 1.35 fullString = parString[:-2]
448     fullString += '\\}'
449 gutsche 1.38 list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
450 slacapra 1.41 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
451 gutsche 1.38 self.jobDestination.append(blockSites[block])
452     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
453     # reset counter
454     jobCount = jobCount + 1
455     totalEventCount = totalEventCount + eventsPerJobRequested
456     eventsRemaining = eventsRemaining - eventsPerJobRequested
457     jobSkipEventCount = 0
458     # reset file
459     parString = "\\{"
460     filesEventCount = 0
461     newFile = 1
462     fileCount += 1
463    
464     # if more events in file remain than eventsPerJobRequested
465     else :
466     # close job but don't touch new file
467     fullString = parString[:-2]
468     fullString += '\\}'
469     list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
470 slacapra 1.41 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
471 gutsche 1.35 self.jobDestination.append(blockSites[block])
472     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
473 gutsche 1.38 # increase counter
474     jobCount = jobCount + 1
475     totalEventCount = totalEventCount + eventsPerJobRequested
476     eventsRemaining = eventsRemaining - eventsPerJobRequested
477     # calculate skip events for last file
478     # use filesEventCount (contains several files), jobSkipEventCount and eventsPerJobRequest
479     jobSkipEventCount = eventsPerJobRequested - (filesEventCount - jobSkipEventCount - self.eventsbyfile[file])
480     # remove all but the last file
481     filesEventCount = self.eventsbyfile[file]
482     parString = "\\{"
483     parString += '\\\"' + file + '\\\"\,'
484 slacapra 1.41 pass # END if
485 gutsche 1.35 pass # END while (iterate over files in the block)
486     pass # END while (iterate over blocks in the dataset)
487 slacapra 1.41 self.ncjobs = self.total_number_of_jobs = jobCount
488 gutsche 1.38 if (eventsRemaining > 0 and jobCount < totalNumberOfJobs ):
489 gutsche 1.35 common.logger.message("Could not run on all requested events because some blocks not hosted at allowed sites.")
490 mkirn 1.37 common.logger.message("\n"+str(jobCount)+" job(s) can run on "+str(totalEventCount)+" events.\n")
491 slacapra 1.22
492 slacapra 1.9 self.list_of_args = list_of_lists
493     return
494    
495 slacapra 1.21 def jobSplittingNoInput(self):
496 slacapra 1.9 """
497     Perform job splitting based on number of event per job
498     """
499     common.logger.debug(5,'Splitting per events')
500     common.logger.message('Required '+str(self.eventsPerJob)+' events per job ')
501 slacapra 1.22 common.logger.message('Required '+str(self.theNumberOfJobs)+' jobs in total ')
502 slacapra 1.9 common.logger.message('Required '+str(self.total_number_of_events)+' events in total ')
503    
504 slacapra 1.10 if (self.total_number_of_events < 0):
505     msg='Cannot split jobs per Events with "-1" as total number of events'
506     raise CrabException(msg)
507    
508 slacapra 1.22 if (self.selectEventsPerJob):
509     self.total_number_of_jobs = int(self.total_number_of_events/self.eventsPerJob)
510     elif (self.selectNumberOfJobs) :
511     self.total_number_of_jobs = self.theNumberOfJobs
512     self.eventsPerJob = int(self.total_number_of_events/self.total_number_of_jobs)
513 fanzago 1.12
514 slacapra 1.9 common.logger.debug(5,'N jobs '+str(self.total_number_of_jobs))
515    
516     # is there any remainder?
517     check = int(self.total_number_of_events) - (int(self.total_number_of_jobs)*self.eventsPerJob)
518    
519     common.logger.debug(5,'Check '+str(check))
520    
521 gutsche 1.35 common.logger.message(str(self.total_number_of_jobs)+' jobs can be created, each for '+str(self.eventsPerJob)+' for a total of '+str(self.total_number_of_jobs*self.eventsPerJob)+' events')
522 slacapra 1.9 if check > 0:
523 gutsche 1.35 common.logger.message('Warning: asked '+str(self.total_number_of_events)+' but can do only '+str(int(self.total_number_of_jobs)*self.eventsPerJob))
524 slacapra 1.9
525 slacapra 1.10 # argument is seed number.$i
526 slacapra 1.9 self.list_of_args = []
527     for i in range(self.total_number_of_jobs):
528 gutsche 1.35 ## Since there is no input, any site is good
529 spiga 1.42 # self.jobDestination.append(["Any"])
530     self.jobDestination.append([""]) #must be empty to write correctly the xml
531 slacapra 1.23 if (self.sourceSeed):
532 slacapra 1.28 if (self.sourceSeedVtx):
533     ## pythia + vtx random seed
534     self.list_of_args.append([
535     str(self.sourceSeed)+str(i),
536     str(self.sourceSeedVtx)+str(i)
537     ])
538     else:
539     ## only pythia random seed
540     self.list_of_args.append([(str(self.sourceSeed)+str(i))])
541 slacapra 1.23 else:
542 slacapra 1.28 ## no random seed
543 slacapra 1.23 self.list_of_args.append([str(i)])
544 slacapra 1.17 #print self.list_of_args
545 gutsche 1.3
546     return
547    
548 spiga 1.42
549     def jobSplittingForScript(self):#CarlosDaniele
550     """
551     Perform job splitting based on number of job
552     """
553     common.logger.debug(5,'Splitting per job')
554     common.logger.message('Required '+str(self.theNumberOfJobs)+' jobs in total ')
555    
556     self.total_number_of_jobs = self.theNumberOfJobs
557    
558     common.logger.debug(5,'N jobs '+str(self.total_number_of_jobs))
559    
560     common.logger.message(str(self.total_number_of_jobs)+' jobs can be created')
561    
562     # argument is seed number.$i
563     self.list_of_args = []
564     for i in range(self.total_number_of_jobs):
565     ## Since there is no input, any site is good
566     # self.jobDestination.append(["Any"])
567     self.jobDestination.append([""])
568     ## no random seed
569     self.list_of_args.append([str(i)])
570     return
571    
572 gutsche 1.3 def split(self, jobParams):
573    
574     common.jobDB.load()
575     #### Fabio
576     njobs = self.total_number_of_jobs
577 slacapra 1.9 arglist = self.list_of_args
578 gutsche 1.3 # create the empty structure
579     for i in range(njobs):
580     jobParams.append("")
581    
582     for job in range(njobs):
583 slacapra 1.17 jobParams[job] = arglist[job]
584     # print str(arglist[job])
585     # print jobParams[job]
586 gutsche 1.3 common.jobDB.setArguments(job, jobParams[job])
587 gutsche 1.35 common.logger.debug(5,"Job "+str(job)+" Destination: "+str(self.jobDestination[job]))
588     common.jobDB.setDestination(job, self.jobDestination[job])
589 gutsche 1.3
590     common.jobDB.save()
591     return
592    
593     def getJobTypeArguments(self, nj, sched):
594 slacapra 1.17 result = ''
595     for i in common.jobDB.arguments(nj):
596     result=result+str(i)+" "
597     return result
598 gutsche 1.3
599     def numberOfJobs(self):
600     # Fabio
601     return self.total_number_of_jobs
602    
603 slacapra 1.1 def getTarBall(self, exe):
604     """
605     Return the TarBall with lib and exe
606     """
607    
608     # if it exist, just return it
609     self.tgzNameWithPath = common.work_space.shareDir()+self.tgz_name
610     if os.path.exists(self.tgzNameWithPath):
611     return self.tgzNameWithPath
612    
613     # Prepare a tar gzipped file with user binaries.
614     self.buildTar_(exe)
615    
616     return string.strip(self.tgzNameWithPath)
617    
618     def buildTar_(self, executable):
619    
620     # First of all declare the user Scram area
621     swArea = self.scram.getSWArea_()
622     #print "swArea = ", swArea
623     swVersion = self.scram.getSWVersion()
624     #print "swVersion = ", swVersion
625     swReleaseTop = self.scram.getReleaseTop_()
626     #print "swReleaseTop = ", swReleaseTop
627    
628     ## check if working area is release top
629     if swReleaseTop == '' or swArea == swReleaseTop:
630     return
631    
632     filesToBeTarred = []
633     ## First find the executable
634     if (self.executable != ''):
635     exeWithPath = self.scram.findFile_(executable)
636     # print exeWithPath
637     if ( not exeWithPath ):
638     raise CrabException('User executable '+executable+' not found')
639    
640     ## then check if it's private or not
641     if exeWithPath.find(swReleaseTop) == -1:
642     # the exe is private, so we must ship
643     common.logger.debug(5,"Exe "+exeWithPath+" to be tarred")
644     path = swArea+'/'
645     exe = string.replace(exeWithPath, path,'')
646     filesToBeTarred.append(exe)
647     pass
648     else:
649     # the exe is from release, we'll find it on WN
650     pass
651    
652     ## Now get the libraries: only those in local working area
653     libDir = 'lib'
654     lib = swArea+'/' +libDir
655     common.logger.debug(5,"lib "+lib+" to be tarred")
656     if os.path.exists(lib):
657     filesToBeTarred.append(libDir)
658    
659 gutsche 1.3 ## Now check if module dir is present
660     moduleDir = 'module'
661     if os.path.isdir(swArea+'/'+moduleDir):
662     filesToBeTarred.append(moduleDir)
663    
664 slacapra 1.1 ## Now check if the Data dir is present
665     dataDir = 'src/Data/'
666     if os.path.isdir(swArea+'/'+dataDir):
667     filesToBeTarred.append(dataDir)
668 gutsche 1.50
669     ## copy ProdAgent dir to swArea
670     cmd = '\cp -rf ' + os.environ['CRABDIR'] + '/ProdAgentApi ' + swArea
671     cmd_out = runCommand(cmd)
672     if cmd_out != '':
673     common.logger.message('ProdAgentApi directory could not be copied to local CMSSW project directory.')
674     common.logger.message('No FrameworkJobreport parsing is possible on the WorkerNode.')
675    
676     ## Now check if the Data dir is present
677     paDir = 'ProdAgentApi'
678     if os.path.isdir(swArea+'/'+paDir):
679     filesToBeTarred.append(paDir)
680    
681 slacapra 1.1 ## Create the tar-ball
682     if len(filesToBeTarred)>0:
683     cwd = os.getcwd()
684     os.chdir(swArea)
685     tarcmd = 'tar zcvf ' + self.tgzNameWithPath + ' '
686     for line in filesToBeTarred:
687     tarcmd = tarcmd + line + ' '
688     cout = runCommand(tarcmd)
689     if not cout:
690     raise CrabException('Could not create tar-ball')
691     os.chdir(cwd)
692     else:
693     common.logger.debug(5,"No files to be to be tarred")
694    
695     return
696    
697     def wsSetupEnvironment(self, nj):
698     """
699     Returns part of a job script which prepares
700     the execution environment for the job 'nj'.
701     """
702     # Prepare JobType-independent part
703 gutsche 1.3 txt = ''
704    
705     ## OLI_Daniele at this level middleware already known
706    
707     txt += 'if [ $middleware == LCG ]; then \n'
708     txt += self.wsSetupCMSLCGEnvironment_()
709     txt += 'elif [ $middleware == OSG ]; then\n'
710 gutsche 1.43 txt += ' WORKING_DIR=`/bin/mktemp -d $OSG_WN_TMP/cms_XXXXXXXXXXXX`\n'
711     txt += ' echo "Created working directory: $WORKING_DIR"\n'
712 gutsche 1.3 txt += ' if [ ! -d $WORKING_DIR ] ;then\n'
713 gutsche 1.7 txt += ' echo "SET_CMS_ENV 10016 ==> OSG $WORKING_DIR could not be created on WN `hostname`"\n'
714     txt += ' echo "JOB_EXIT_STATUS = 10016"\n'
715     txt += ' echo "JobExitCode=10016" | tee -a $RUNTIME_AREA/$repo\n'
716     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
717 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
718     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
719     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
720 gutsche 1.3 txt += ' exit 1\n'
721     txt += ' fi\n'
722     txt += '\n'
723     txt += ' echo "Change to working directory: $WORKING_DIR"\n'
724     txt += ' cd $WORKING_DIR\n'
725     txt += self.wsSetupCMSOSGEnvironment_()
726     txt += 'fi\n'
727 slacapra 1.1
728     # Prepare JobType-specific part
729     scram = self.scram.commandName()
730     txt += '\n\n'
731     txt += 'echo "### SPECIFIC JOB SETUP ENVIRONMENT ###"\n'
732     txt += scram+' project CMSSW '+self.version+'\n'
733     txt += 'status=$?\n'
734     txt += 'if [ $status != 0 ] ; then\n'
735 gutsche 1.7 txt += ' echo "SET_EXE_ENV 10034 ==>ERROR CMSSW '+self.version+' not found on `hostname`" \n'
736 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 10034"\n'
737 gutsche 1.7 txt += ' echo "JobExitCode=10034" | tee -a $RUNTIME_AREA/$repo\n'
738 slacapra 1.1 txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
739 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
740     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
741     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
742 gutsche 1.3 ## OLI_Daniele
743     txt += ' if [ $middleware == OSG ]; then \n'
744     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
745     txt += ' cd $RUNTIME_AREA\n'
746     txt += ' /bin/rm -rf $WORKING_DIR\n'
747     txt += ' if [ -d $WORKING_DIR ] ;then\n'
748 gutsche 1.7 txt += ' echo "SET_CMS_ENV 10018 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after CMSSW CMSSW_0_6_1 not found on `hostname`"\n'
749     txt += ' echo "JOB_EXIT_STATUS = 10018"\n'
750     txt += ' echo "JobExitCode=10018" | tee -a $RUNTIME_AREA/$repo\n'
751     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
752 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
753     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
754     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
755 gutsche 1.3 txt += ' fi\n'
756     txt += ' fi \n'
757     txt += ' exit 1 \n'
758 slacapra 1.1 txt += 'fi \n'
759     txt += 'echo "CMSSW_VERSION = '+self.version+'"\n'
760     txt += 'cd '+self.version+'\n'
761     ### needed grep for bug in scramv1 ###
762     txt += 'eval `'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME`\n'
763    
764     # Handle the arguments:
765     txt += "\n"
766 gutsche 1.7 txt += "## number of arguments (first argument always jobnumber)\n"
767 slacapra 1.1 txt += "\n"
768 mkirn 1.32 # txt += "narg=$#\n"
769     txt += "if [ $nargs -lt 2 ]\n"
770 slacapra 1.1 txt += "then\n"
771 mkirn 1.33 txt += " echo 'SET_EXE_ENV 1 ==> ERROR Too few arguments' +$nargs+ \n"
772 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 50113"\n'
773 gutsche 1.7 txt += ' echo "JobExitCode=50113" | tee -a $RUNTIME_AREA/$repo\n'
774 slacapra 1.1 txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
775 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
776     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
777     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
778 gutsche 1.3 ## OLI_Daniele
779     txt += ' if [ $middleware == OSG ]; then \n'
780     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
781     txt += ' cd $RUNTIME_AREA\n'
782     txt += ' /bin/rm -rf $WORKING_DIR\n'
783     txt += ' if [ -d $WORKING_DIR ] ;then\n'
784 gutsche 1.7 txt += ' echo "SET_EXE_ENV 50114 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after Too few arguments for CRAB job wrapper"\n'
785     txt += ' echo "JOB_EXIT_STATUS = 50114"\n'
786     txt += ' echo "JobExitCode=50114" | tee -a $RUNTIME_AREA/$repo\n'
787     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
788 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
789     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
790     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
791 gutsche 1.3 txt += ' fi\n'
792     txt += ' fi \n'
793 slacapra 1.1 txt += " exit 1\n"
794     txt += "fi\n"
795     txt += "\n"
796    
797     # Prepare job-specific part
798     job = common.job_list[nj]
799 spiga 1.42 if self.pset != None: #CarlosDaniele
800     pset = os.path.basename(job.configFilename())
801     txt += '\n'
802     if (self.datasetPath): # standard job
803     #txt += 'InputFiles=$2\n'
804     txt += 'InputFiles=${args[1]}\n'
805     txt += 'MaxEvents=${args[2]}\n'
806     txt += 'SkipEvents=${args[3]}\n'
807     txt += 'echo "Inputfiles:<$InputFiles>"\n'
808     txt += 'sed "s#{\'INPUT\'}#$InputFiles#" $RUNTIME_AREA/'+pset+' > pset_tmp_1.cfg\n'
809     txt += 'echo "MaxEvents:<$MaxEvents>"\n'
810 gutsche 1.46 txt += 'sed "s#INPUTMAXEVENTS#$MaxEvents#" pset_tmp_1.cfg > pset_tmp_2.cfg\n'
811 spiga 1.42 txt += 'echo "SkipEvents:<$SkipEvents>"\n'
812 gutsche 1.46 txt += 'sed "s#INPUTSKIPEVENTS#$SkipEvents#" pset_tmp_2.cfg > pset.cfg\n'
813 spiga 1.42 else: # pythia like job
814     if (self.sourceSeed):
815     # txt += 'Seed=$2\n'
816     txt += 'Seed=${args[1]}\n'
817     txt += 'echo "Seed: <$Seed>"\n'
818     txt += 'sed "s#\<INPUT\>#$Seed#" $RUNTIME_AREA/'+pset+' > tmp.cfg\n'
819     if (self.sourceSeedVtx):
820     # txt += 'VtxSeed=$3\n'
821     txt += 'VtxSeed=${args[2]}\n'
822     txt += 'echo "VtxSeed: <$VtxSeed>"\n'
823     txt += 'sed "s#INPUTVTX#$VtxSeed#" tmp.cfg > pset.cfg\n'
824     else:
825     txt += 'mv tmp.cfg pset.cfg\n'
826 slacapra 1.28 else:
827 spiga 1.42 txt += '# Copy untouched pset\n'
828     txt += 'cp $RUNTIME_AREA/'+pset+' pset.cfg\n'
829 slacapra 1.24
830 slacapra 1.1
831     if len(self.additional_inbox_files) > 0:
832     for file in self.additional_inbox_files:
833 mkirn 1.31 relFile = file.split("/")[-1]
834     txt += 'if [ -e $RUNTIME_AREA/'+relFile+' ] ; then\n'
835     txt += ' cp $RUNTIME_AREA/'+relFile+' .\n'
836     txt += ' chmod +x '+relFile+'\n'
837 slacapra 1.1 txt += 'fi\n'
838     pass
839    
840 spiga 1.42 if self.pset != None: #CarlosDaniele
841     txt += 'echo "### END JOB SETUP ENVIRONMENT ###"\n\n'
842    
843     txt += '\n'
844     txt += 'echo "***** cat pset.cfg *********"\n'
845     txt += 'cat pset.cfg\n'
846     txt += 'echo "****** end pset.cfg ********"\n'
847     txt += '\n'
848     # txt += 'echo "***** cat pset1.cfg *********"\n'
849     # txt += 'cat pset1.cfg\n'
850     # txt += 'echo "****** end pset1.cfg ********"\n'
851 gutsche 1.3 return txt
852    
853     def wsBuildExe(self, nj):
854     """
855     Put in the script the commands to build an executable
856     or a library.
857     """
858    
859     txt = ""
860    
861     if os.path.isfile(self.tgzNameWithPath):
862     txt += 'echo "tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'"\n'
863     txt += 'tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
864     txt += 'untar_status=$? \n'
865     txt += 'if [ $untar_status -ne 0 ]; then \n'
866     txt += ' echo "SET_EXE 1 ==> ERROR Untarring .tgz file failed"\n'
867     txt += ' echo "JOB_EXIT_STATUS = $untar_status" \n'
868 gutsche 1.7 txt += ' echo "JobExitCode=$untar_status" | tee -a $RUNTIME_AREA/$repo\n'
869 gutsche 1.3 txt += ' if [ $middleware == OSG ]; then \n'
870     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
871     txt += ' cd $RUNTIME_AREA\n'
872     txt += ' /bin/rm -rf $WORKING_DIR\n'
873     txt += ' if [ -d $WORKING_DIR ] ;then\n'
874 gutsche 1.13 txt += ' echo "SET_EXE 50999 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after Untarring .tgz file failed"\n'
875     txt += ' echo "JOB_EXIT_STATUS = 50999"\n'
876     txt += ' echo "JobExitCode=50999" | tee -a $RUNTIME_AREA/$repo\n'
877     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
878     txt += ' rm -f $RUNTIME_AREA/$repo \n'
879     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
880     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
881 gutsche 1.3 txt += ' fi\n'
882     txt += ' fi \n'
883     txt += ' \n'
884 gutsche 1.7 txt += ' exit 1 \n'
885 gutsche 1.3 txt += 'else \n'
886     txt += ' echo "Successful untar" \n'
887     txt += 'fi \n'
888 gutsche 1.50 txt += '\n'
889     txt += 'echo "Include ProdAgentApi in PYTHONPATH"\n'
890     txt += 'if [ -z "$PYTHONPATH" ]; then\n'
891     txt += ' export PYTHONPATH=ProdAgentApi\n'
892     txt += 'else\n'
893     txt += ' export PYTHONPATH=ProdAgentApi:${PYTHONPATH}\n'
894     txt += 'fi\n'
895     txt += '\n'
896    
897 gutsche 1.3 pass
898    
899 slacapra 1.1 return txt
900    
901     def modifySteeringCards(self, nj):
902     """
903     modify the card provided by the user,
904     writing a new card into share dir
905     """
906    
907     def executableName(self):
908 spiga 1.42 if self.pset == None: #CarlosDaniele
909     return "sh "
910     else:
911     return self.executable
912 slacapra 1.1
913     def executableArgs(self):
914 spiga 1.42 if self.pset == None:#CarlosDaniele
915     return self.scriptExe + " $NJob"
916     else:
917     return " -p pset.cfg"
918 slacapra 1.1
919     def inputSandbox(self, nj):
920     """
921     Returns a list of filenames to be put in JDL input sandbox.
922     """
923     inp_box = []
924     # dict added to delete duplicate from input sandbox file list
925     seen = {}
926     ## code
927     if os.path.isfile(self.tgzNameWithPath):
928     inp_box.append(self.tgzNameWithPath)
929     ## config
930 spiga 1.42 if not self.pset is None: #CarlosDaniele
931     inp_box.append(common.job_list[nj].configFilename())
932 slacapra 1.1 ## additional input files
933 gutsche 1.3 #for file in self.additional_inbox_files:
934     # inp_box.append(common.work_space.cwdDir()+file)
935 slacapra 1.1 return inp_box
936    
937     def outputSandbox(self, nj):
938     """
939     Returns a list of filenames to be put in JDL output sandbox.
940     """
941     out_box = []
942    
943     stdout=common.job_list[nj].stdout()
944     stderr=common.job_list[nj].stderr()
945    
946     ## User Declared output files
947     for out in self.output_file:
948     n_out = nj + 1
949     out_box.append(self.numberFile_(out,str(n_out)))
950     return out_box
951     return []
952    
953     def prepareSteeringCards(self):
954     """
955     Make initial modifications of the user's steering card file.
956     """
957     return
958    
959     def wsRenameOutput(self, nj):
960     """
961     Returns part of a job script which renames the produced files.
962     """
963    
964     txt = '\n'
965 gutsche 1.7 txt += '# directory content\n'
966     txt += 'ls \n'
967 slacapra 1.1 file_list = ''
968     for fileWithSuffix in self.output_file:
969     output_file_num = self.numberFile_(fileWithSuffix, '$NJob')
970 gutsche 1.7 file_list=file_list+output_file_num+' '
971 slacapra 1.1 txt += '\n'
972 gutsche 1.7 txt += '# check output file\n'
973 slacapra 1.1 txt += 'ls '+fileWithSuffix+'\n'
974 fanzago 1.18 txt += 'ls_result=$?\n'
975     #txt += 'exe_result=$?\n'
976     txt += 'if [ $ls_result -ne 0 ] ; then\n'
977     txt += ' echo "ERROR: Problem with output file"\n'
978     #txt += ' echo "JOB_EXIT_STATUS = $exe_result"\n'
979     #txt += ' echo "JobExitCode=60302" | tee -a $RUNTIME_AREA/$repo\n'
980     #txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
981 gutsche 1.3 ### OLI_DANIELE
982 gutsche 1.7 if common.scheduler.boss_scheduler_name == 'condor_g':
983     txt += ' if [ $middleware == OSG ]; then \n'
984     txt += ' echo "prepare dummy output file"\n'
985     txt += ' echo "Processing of job output failed" > $RUNTIME_AREA/'+output_file_num+'\n'
986     txt += ' fi \n'
987 slacapra 1.1 txt += 'else\n'
988     txt += ' cp '+fileWithSuffix+' $RUNTIME_AREA/'+output_file_num+'\n'
989     txt += 'fi\n'
990    
991 gutsche 1.7 txt += 'cd $RUNTIME_AREA\n'
992 slacapra 1.1 file_list=file_list[:-1]
993 slacapra 1.2 txt += 'file_list="'+file_list+'"\n'
994 fanzago 1.18 txt += 'cd $RUNTIME_AREA\n'
995 gutsche 1.3 ### OLI_DANIELE
996     txt += 'if [ $middleware == OSG ]; then\n'
997     txt += ' cd $RUNTIME_AREA\n'
998     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
999     txt += ' /bin/rm -rf $WORKING_DIR\n'
1000     txt += ' if [ -d $WORKING_DIR ] ;then\n'
1001 gutsche 1.7 txt += ' echo "SET_EXE 60999 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after cleanup of WN"\n'
1002     txt += ' echo "JOB_EXIT_STATUS = 60999"\n'
1003     txt += ' echo "JobExitCode=60999" | tee -a $RUNTIME_AREA/$repo\n'
1004     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1005 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1006     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1007     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1008 gutsche 1.3 txt += ' fi\n'
1009     txt += 'fi\n'
1010     txt += '\n'
1011 slacapra 1.1 return txt
1012    
1013     def numberFile_(self, file, txt):
1014     """
1015     append _'txt' before last extension of a file
1016     """
1017     p = string.split(file,".")
1018     # take away last extension
1019     name = p[0]
1020     for x in p[1:-1]:
1021     name=name+"."+x
1022     # add "_txt"
1023     if len(p)>1:
1024     ext = p[len(p)-1]
1025     result = name + '_' + txt + "." + ext
1026     else:
1027     result = name + '_' + txt
1028    
1029     return result
1030    
1031 slacapra 1.41 def getRequirements(self):
1032 slacapra 1.1 """
1033     return job requirements to add to jdl files
1034     """
1035     req = ''
1036 slacapra 1.47 if self.version:
1037 slacapra 1.10 req='Member("VO-cms-' + \
1038 slacapra 1.47 self.version + \
1039 slacapra 1.10 '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
1040 gutsche 1.35
1041     req = req + ' && (other.GlueHostNetworkAdapterOutboundIP)'
1042    
1043 slacapra 1.1 return req
1044 gutsche 1.3
1045     def configFilename(self):
1046     """ return the config filename """
1047     return self.name()+'.cfg'
1048    
1049     ### OLI_DANIELE
1050     def wsSetupCMSOSGEnvironment_(self):
1051     """
1052     Returns part of a job script which is prepares
1053     the execution environment and which is common for all CMS jobs.
1054     """
1055     txt = '\n'
1056     txt += ' echo "### SETUP CMS OSG ENVIRONMENT ###"\n'
1057     txt += ' if [ -f $GRID3_APP_DIR/cmssoft/cmsset_default.sh ] ;then\n'
1058     txt += ' # Use $GRID3_APP_DIR/cmssoft/cmsset_default.sh to setup cms software\n'
1059     txt += ' source $GRID3_APP_DIR/cmssoft/cmsset_default.sh '+self.version+'\n'
1060 mkirn 1.40 txt += ' elif [ -f $OSG_APP/cmssoft/cms/cmsset_default.sh ] ;then\n'
1061     txt += ' # Use $OSG_APP/cmssoft/cms/cmsset_default.sh to setup cms software\n'
1062     txt += ' source $OSG_APP/cmssoft/cms/cmsset_default.sh '+self.version+'\n'
1063 gutsche 1.3 txt += ' else\n'
1064 mkirn 1.40 txt += ' echo "SET_CMS_ENV 10020 ==> ERROR $GRID3_APP_DIR/cmssoft/cmsset_default.sh and $OSG_APP/cmssoft/cms/cmsset_default.sh file not found"\n'
1065 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 10020"\n'
1066     txt += ' echo "JobExitCode=10020" | tee -a $RUNTIME_AREA/$repo\n'
1067     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1068 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1069     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1070     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1071 gutsche 1.7 txt += ' exit 1\n'
1072 gutsche 1.3 txt += '\n'
1073     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
1074     txt += ' cd $RUNTIME_AREA\n'
1075     txt += ' /bin/rm -rf $WORKING_DIR\n'
1076     txt += ' if [ -d $WORKING_DIR ] ;then\n'
1077 mkirn 1.40 txt += ' echo "SET_CMS_ENV 10017 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after $GRID3_APP_DIR/cmssoft/cmsset_default.sh and $OSG_APP/cmssoft/cms/cmsset_default.sh file not found"\n'
1078 gutsche 1.7 txt += ' echo "JOB_EXIT_STATUS = 10017"\n'
1079     txt += ' echo "JobExitCode=10017" | tee -a $RUNTIME_AREA/$repo\n'
1080     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1081 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1082     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1083     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1084 gutsche 1.3 txt += ' fi\n'
1085     txt += '\n'
1086 gutsche 1.7 txt += ' exit 1\n'
1087 gutsche 1.3 txt += ' fi\n'
1088     txt += '\n'
1089     txt += ' echo "SET_CMS_ENV 0 ==> setup cms environment ok"\n'
1090     txt += ' echo " END SETUP CMS OSG ENVIRONMENT "\n'
1091    
1092     return txt
1093    
1094     ### OLI_DANIELE
1095     def wsSetupCMSLCGEnvironment_(self):
1096     """
1097     Returns part of a job script which is prepares
1098     the execution environment and which is common for all CMS jobs.
1099     """
1100     txt = ' \n'
1101     txt += ' echo " ### SETUP CMS LCG ENVIRONMENT ### "\n'
1102     txt += ' if [ ! $VO_CMS_SW_DIR ] ;then\n'
1103     txt += ' echo "SET_CMS_ENV 10031 ==> ERROR CMS software dir not found on WN `hostname`"\n'
1104     txt += ' echo "JOB_EXIT_STATUS = 10031" \n'
1105     txt += ' echo "JobExitCode=10031" | tee -a $RUNTIME_AREA/$repo\n'
1106     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1107 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1108     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1109     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1110 gutsche 1.7 txt += ' exit 1\n'
1111 gutsche 1.3 txt += ' else\n'
1112     txt += ' echo "Sourcing environment... "\n'
1113     txt += ' if [ ! -s $VO_CMS_SW_DIR/cmsset_default.sh ] ;then\n'
1114     txt += ' echo "SET_CMS_ENV 10020 ==> ERROR cmsset_default.sh file not found into dir $VO_CMS_SW_DIR"\n'
1115     txt += ' echo "JOB_EXIT_STATUS = 10020"\n'
1116     txt += ' echo "JobExitCode=10020" | tee -a $RUNTIME_AREA/$repo\n'
1117     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1118 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1119     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1120     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1121 gutsche 1.7 txt += ' exit 1\n'
1122 gutsche 1.3 txt += ' fi\n'
1123     txt += ' echo "sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1124     txt += ' source $VO_CMS_SW_DIR/cmsset_default.sh\n'
1125     txt += ' result=$?\n'
1126     txt += ' if [ $result -ne 0 ]; then\n'
1127     txt += ' echo "SET_CMS_ENV 10032 ==> ERROR problem sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1128     txt += ' echo "JOB_EXIT_STATUS = 10032"\n'
1129     txt += ' echo "JobExitCode=10032" | tee -a $RUNTIME_AREA/$repo\n'
1130     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1131 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1132     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1133     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1134 gutsche 1.7 txt += ' exit 1\n'
1135 gutsche 1.3 txt += ' fi\n'
1136     txt += ' fi\n'
1137     txt += ' \n'
1138     txt += ' string=`cat /etc/redhat-release`\n'
1139     txt += ' echo $string\n'
1140     txt += ' if [[ $string = *alhalla* ]]; then\n'
1141     txt += ' echo "SCRAM_ARCH= $SCRAM_ARCH"\n'
1142     txt += ' elif [[ $string = *Enterprise* ]] || [[ $string = *cientific* ]]; then\n'
1143     txt += ' export SCRAM_ARCH=slc3_ia32_gcc323\n'
1144     txt += ' echo "SCRAM_ARCH= $SCRAM_ARCH"\n'
1145     txt += ' else\n'
1146 gutsche 1.7 txt += ' echo "SET_CMS_ENV 10033 ==> ERROR OS unknown, LCG environment not initialized"\n'
1147 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 10033"\n'
1148     txt += ' echo "JobExitCode=10033" | tee -a $RUNTIME_AREA/$repo\n'
1149     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1150 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1151     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1152     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1153 gutsche 1.7 txt += ' exit 1\n'
1154 gutsche 1.3 txt += ' fi\n'
1155     txt += ' echo "SET_CMS_ENV 0 ==> setup cms environment ok"\n'
1156     txt += ' echo "### END SETUP CMS LCG ENVIRONMENT ###"\n'
1157     return txt
1158 gutsche 1.5
1159     def setParam_(self, param, value):
1160     self._params[param] = value
1161    
1162     def getParams(self):
1163     return self._params
1164 gutsche 1.8
1165     def setTaskid_(self):
1166     self._taskId = self.cfg_params['taskId']
1167    
1168     def getTaskid(self):
1169     return self._taskId
1170 gutsche 1.35
1171     #######################################################################
1172     def uniquelist(self, old):
1173     """
1174     remove duplicates from a list
1175     """
1176     nd={}
1177     for e in old:
1178     nd[e]=0
1179     return nd.keys()