ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.68
Committed: Thu Feb 15 20:06:41 2007 UTC (18 years, 2 months ago) by gutsche
Content type: text/x-python
Branch: MAIN
Changes since 1.67: +86 -85 lines
Log Message:
cms_cmssw.py

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