ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.45
Committed: Fri Sep 29 10:41:52 2006 UTC (18 years, 7 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_1_3_0
Changes since 1.44: +10 -4 lines
Log Message:
allow wildcards in additional input files

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