ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.66
Committed: Thu Feb 1 16:14:41 2007 UTC (18 years, 2 months ago) by gutsche
Content type: text/x-python
Branch: MAIN
Changes since 1.65: +15 -10 lines
Log Message:
Added card "use_dbs_2" to crab.cfg to steer usage of DBS-1 (default) or DBS-2

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    
291 slacapra 1.41 except DataDiscovery.NoDataTierinProvenanceError, ex :
292 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
293     raise CrabException(msg)
294 slacapra 1.41 except DataDiscovery.DataDiscoveryError, ex:
295 gutsche 1.66 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
296 slacapra 1.1 raise CrabException(msg)
297    
298     ## get list of all required data in the form of dbs paths (dbs path = /dataset/datatier/owner)
299 gutsche 1.3 common.logger.message("Required data are :"+self.datasetPath)
300    
301 gutsche 1.35 self.filesbyblock=self.pubdata.getFiles()
302 mkirn 1.37 self.eventsbyblock=self.pubdata.getEventsPerBlock()
303     self.eventsbyfile=self.pubdata.getEventsPerFile()
304 gutsche 1.3
305 slacapra 1.1 ## get max number of events
306     self.maxEvents=self.pubdata.getMaxEvents() ## self.maxEvents used in Creator.py
307 gutsche 1.44 common.logger.message("The number of available events is %s\n"%self.maxEvents)
308 slacapra 1.1
309 slacapra 1.41 common.logger.message("Contacting DLS...")
310 slacapra 1.1 ## Contact the DLS and build a list of sites hosting the fileblocks
311     try:
312 slacapra 1.41 dataloc=DataLocation.DataLocation(self.filesbyblock.keys(),cfg_params)
313 gutsche 1.6 dataloc.fetchDLSInfo()
314 slacapra 1.41 except DataLocation.DataLocationError , ex:
315 slacapra 1.1 msg = 'ERROR ***: failed Data Location in DLS \n %s '%ex.getErrorMessage()
316     raise CrabException(msg)
317    
318    
319 gutsche 1.35 sites = dataloc.getSites()
320     allSites = []
321     listSites = sites.values()
322 slacapra 1.63 for listSite in listSites:
323     for oneSite in listSite:
324 gutsche 1.35 allSites.append(oneSite)
325     allSites = self.uniquelist(allSites)
326 gutsche 1.3
327 gutsche 1.35 common.logger.message("Sites ("+str(len(allSites))+") hosting part/all of dataset: "+str(allSites))
328     common.logger.debug(6, "List of Sites: "+str(allSites))
329     return sites
330 gutsche 1.3
331 gutsche 1.35 def jobSplittingByBlocks(self, blockSites):
332 slacapra 1.9 """
333 gutsche 1.35 Perform job splitting. Jobs run over an integer number of files
334     and no more than one block.
335     ARGUMENT: blockSites: dictionary with blocks as keys and list of host sites as values
336     REQUIRES: self.selectTotalNumberEvents, self.selectEventsPerJob, self.selectNumberofJobs,
337     self.total_number_of_events, self.eventsPerJob, self.theNumberOfJobs,
338     self.maxEvents, self.filesbyblock
339     SETS: self.jobDestination - Site destination(s) for each job (a list of lists)
340     self.total_number_of_jobs - Total # of jobs
341     self.list_of_args - File(s) job will run on (a list of lists)
342     """
343    
344     # ---- Handle the possible job splitting configurations ---- #
345     if (self.selectTotalNumberEvents):
346     totalEventsRequested = self.total_number_of_events
347     if (self.selectEventsPerJob):
348     eventsPerJobRequested = self.eventsPerJob
349     if (self.selectNumberOfJobs):
350     totalEventsRequested = self.theNumberOfJobs * self.eventsPerJob
351    
352     # If user requested all the events in the dataset
353     if (totalEventsRequested == -1):
354     eventsRemaining=self.maxEvents
355     # If user requested more events than are in the dataset
356     elif (totalEventsRequested > self.maxEvents):
357     eventsRemaining = self.maxEvents
358     common.logger.message("Requested "+str(self.total_number_of_events)+ " events, but only "+str(self.maxEvents)+" events are available.")
359     # If user requested less events than are in the dataset
360     else:
361     eventsRemaining = totalEventsRequested
362 slacapra 1.22
363 slacapra 1.41 # If user requested more events per job than are in the dataset
364     if (self.selectEventsPerJob and eventsPerJobRequested > self.maxEvents):
365     eventsPerJobRequested = self.maxEvents
366    
367 gutsche 1.35 # For user info at end
368     totalEventCount = 0
369 gutsche 1.3
370 gutsche 1.35 if (self.selectTotalNumberEvents and self.selectNumberOfJobs):
371     eventsPerJobRequested = int(eventsRemaining/self.theNumberOfJobs)
372 slacapra 1.22
373 gutsche 1.35 if (self.selectNumberOfJobs):
374     common.logger.message("May not create the exact number_of_jobs requested.")
375 slacapra 1.23
376 gutsche 1.38 if ( self.ncjobs == 'all' ) :
377     totalNumberOfJobs = 999999999
378     else :
379     totalNumberOfJobs = self.ncjobs
380    
381    
382 gutsche 1.35 blocks = blockSites.keys()
383     blockCount = 0
384     # Backup variable in case self.maxEvents counted events in a non-included block
385     numBlocksInDataset = len(blocks)
386 gutsche 1.3
387 gutsche 1.35 jobCount = 0
388     list_of_lists = []
389 gutsche 1.3
390 gutsche 1.35 # ---- Iterate over the blocks in the dataset until ---- #
391     # ---- we've met the requested total # of events ---- #
392 gutsche 1.38 while ( (eventsRemaining > 0) and (blockCount < numBlocksInDataset) and (jobCount < totalNumberOfJobs)):
393 gutsche 1.35 block = blocks[blockCount]
394 gutsche 1.44 blockCount += 1
395    
396 gutsche 1.3
397 gutsche 1.44 numEventsInBlock = self.eventsbyblock[block]
398     common.logger.debug(5,'Events in Block File '+str(numEventsInBlock))
399 slacapra 1.9
400 gutsche 1.35 files = self.filesbyblock[block]
401     numFilesInBlock = len(files)
402     if (numFilesInBlock <= 0):
403     continue
404     fileCount = 0
405    
406     # ---- New block => New job ---- #
407     parString = "\\{"
408 gutsche 1.38 # counter for number of events in files currently worked on
409     filesEventCount = 0
410     # flag if next while loop should touch new file
411     newFile = 1
412     # job event counter
413     jobSkipEventCount = 0
414 slacapra 1.9
415 gutsche 1.35 # ---- Iterate over the files in the block until we've met the requested ---- #
416     # ---- total # of events or we've gone over all the files in this block ---- #
417 gutsche 1.38 while ( (eventsRemaining > 0) and (fileCount < numFilesInBlock) and (jobCount < totalNumberOfJobs) ):
418 gutsche 1.35 file = files[fileCount]
419 gutsche 1.38 if newFile :
420 slacapra 1.41 try:
421     numEventsInFile = self.eventsbyfile[file]
422     common.logger.debug(6, "File "+str(file)+" has "+str(numEventsInFile)+" events")
423     # increase filesEventCount
424     filesEventCount += numEventsInFile
425     # Add file to current job
426     parString += '\\\"' + file + '\\\"\,'
427     newFile = 0
428     except KeyError:
429 gutsche 1.44 common.logger.message("File "+str(file)+" has unknown number of events: skipping")
430 slacapra 1.41
431 gutsche 1.38
432     # if less events in file remain than eventsPerJobRequested
433     if ( filesEventCount - jobSkipEventCount < eventsPerJobRequested ) :
434     # if last file in block
435 gutsche 1.44 if ( fileCount == numFilesInBlock-1 ) :
436 gutsche 1.38 # end job using last file, use remaining events in block
437     # close job and touch new file
438     fullString = parString[:-2]
439     fullString += '\\}'
440     list_of_lists.append([fullString,str(-1),str(jobSkipEventCount)])
441 slacapra 1.41 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(filesEventCount - jobSkipEventCount)+" events (last file in block).")
442 gutsche 1.38 self.jobDestination.append(blockSites[block])
443     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
444     # reset counter
445     jobCount = jobCount + 1
446 gutsche 1.44 totalEventCount = totalEventCount + filesEventCount - jobSkipEventCount
447     eventsRemaining = eventsRemaining - filesEventCount + jobSkipEventCount
448 gutsche 1.38 jobSkipEventCount = 0
449     # reset file
450     parString = "\\{"
451     filesEventCount = 0
452     newFile = 1
453     fileCount += 1
454     else :
455     # go to next file
456     newFile = 1
457     fileCount += 1
458     # if events in file equal to eventsPerJobRequested
459     elif ( filesEventCount - jobSkipEventCount == eventsPerJobRequested ) :
460     # close job and touch new file
461 gutsche 1.35 fullString = parString[:-2]
462     fullString += '\\}'
463 gutsche 1.38 list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
464 slacapra 1.41 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
465 gutsche 1.38 self.jobDestination.append(blockSites[block])
466     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
467     # reset counter
468     jobCount = jobCount + 1
469     totalEventCount = totalEventCount + eventsPerJobRequested
470     eventsRemaining = eventsRemaining - eventsPerJobRequested
471     jobSkipEventCount = 0
472     # reset file
473     parString = "\\{"
474     filesEventCount = 0
475     newFile = 1
476     fileCount += 1
477    
478     # if more events in file remain than eventsPerJobRequested
479     else :
480     # close job but don't touch new file
481     fullString = parString[:-2]
482     fullString += '\\}'
483     list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
484 slacapra 1.41 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
485 gutsche 1.35 self.jobDestination.append(blockSites[block])
486     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
487 gutsche 1.38 # increase counter
488     jobCount = jobCount + 1
489     totalEventCount = totalEventCount + eventsPerJobRequested
490     eventsRemaining = eventsRemaining - eventsPerJobRequested
491     # calculate skip events for last file
492     # use filesEventCount (contains several files), jobSkipEventCount and eventsPerJobRequest
493     jobSkipEventCount = eventsPerJobRequested - (filesEventCount - jobSkipEventCount - self.eventsbyfile[file])
494     # remove all but the last file
495     filesEventCount = self.eventsbyfile[file]
496     parString = "\\{"
497     parString += '\\\"' + file + '\\\"\,'
498 slacapra 1.41 pass # END if
499 gutsche 1.35 pass # END while (iterate over files in the block)
500     pass # END while (iterate over blocks in the dataset)
501 slacapra 1.41 self.ncjobs = self.total_number_of_jobs = jobCount
502 gutsche 1.38 if (eventsRemaining > 0 and jobCount < totalNumberOfJobs ):
503 gutsche 1.35 common.logger.message("Could not run on all requested events because some blocks not hosted at allowed sites.")
504 mkirn 1.37 common.logger.message("\n"+str(jobCount)+" job(s) can run on "+str(totalEventCount)+" events.\n")
505 slacapra 1.22
506 slacapra 1.9 self.list_of_args = list_of_lists
507     return
508    
509 slacapra 1.21 def jobSplittingNoInput(self):
510 slacapra 1.9 """
511     Perform job splitting based on number of event per job
512     """
513     common.logger.debug(5,'Splitting per events')
514     common.logger.message('Required '+str(self.eventsPerJob)+' events per job ')
515 slacapra 1.22 common.logger.message('Required '+str(self.theNumberOfJobs)+' jobs in total ')
516 slacapra 1.9 common.logger.message('Required '+str(self.total_number_of_events)+' events in total ')
517    
518 slacapra 1.10 if (self.total_number_of_events < 0):
519     msg='Cannot split jobs per Events with "-1" as total number of events'
520     raise CrabException(msg)
521    
522 slacapra 1.22 if (self.selectEventsPerJob):
523 spiga 1.65 if (self.selectTotalNumberEvents):
524     self.total_number_of_jobs = int(self.total_number_of_events/self.eventsPerJob)
525     elif(self.selectNumberOfJobs) :
526     self.total_number_of_jobs =self.theNumberOfJobs
527     self.total_number_of_events =int(self.theNumberOfJobs*self.eventsPerJob)
528    
529 slacapra 1.22 elif (self.selectNumberOfJobs) :
530     self.total_number_of_jobs = self.theNumberOfJobs
531     self.eventsPerJob = int(self.total_number_of_events/self.total_number_of_jobs)
532 spiga 1.65
533 slacapra 1.9 common.logger.debug(5,'N jobs '+str(self.total_number_of_jobs))
534    
535     # is there any remainder?
536     check = int(self.total_number_of_events) - (int(self.total_number_of_jobs)*self.eventsPerJob)
537    
538     common.logger.debug(5,'Check '+str(check))
539    
540 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')
541 slacapra 1.9 if check > 0:
542 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))
543 slacapra 1.9
544 slacapra 1.10 # argument is seed number.$i
545 slacapra 1.9 self.list_of_args = []
546     for i in range(self.total_number_of_jobs):
547 gutsche 1.35 ## Since there is no input, any site is good
548 spiga 1.42 # self.jobDestination.append(["Any"])
549     self.jobDestination.append([""]) #must be empty to write correctly the xml
550 spiga 1.57 args=''
551     if (self.firstRun):
552     ## pythia first run
553     #self.list_of_args.append([(str(self.firstRun)+str(i))])
554     args=args+(str(self.firstRun)+str(i))
555     else:
556     ## no first run
557     #self.list_of_args.append([str(i)])
558     args=args+str(i)
559 slacapra 1.23 if (self.sourceSeed):
560 slacapra 1.28 if (self.sourceSeedVtx):
561     ## pythia + vtx random seed
562 spiga 1.57 #self.list_of_args.append([
563     # str(self.sourceSeed)+str(i),
564     # str(self.sourceSeedVtx)+str(i)
565     # ])
566     args=args+str(',')+str(self.sourceSeed)+str(i)+str(',')+str(self.sourceSeedVtx)+str(i)
567 slacapra 1.28 else:
568     ## only pythia random seed
569 spiga 1.57 #self.list_of_args.append([(str(self.sourceSeed)+str(i))])
570     args=args +str(',')+str(self.sourceSeed)+str(i)
571 slacapra 1.23 else:
572 slacapra 1.28 ## no random seed
573 spiga 1.57 if str(args)=='': args=args+(str(self.firstRun)+str(i))
574     arguments=args.split(',')
575     if len(arguments)==3:self.list_of_args.append([str(arguments[0]),str(arguments[1]),str(arguments[2])])
576     elif len(arguments)==2:self.list_of_args.append([str(arguments[0]),str(arguments[1])])
577     else :self.list_of_args.append([str(arguments[0])])
578    
579     # print self.list_of_args
580 gutsche 1.3
581     return
582    
583 spiga 1.42
584     def jobSplittingForScript(self):#CarlosDaniele
585     """
586     Perform job splitting based on number of job
587     """
588     common.logger.debug(5,'Splitting per job')
589     common.logger.message('Required '+str(self.theNumberOfJobs)+' jobs in total ')
590    
591     self.total_number_of_jobs = self.theNumberOfJobs
592    
593     common.logger.debug(5,'N jobs '+str(self.total_number_of_jobs))
594    
595     common.logger.message(str(self.total_number_of_jobs)+' jobs can be created')
596    
597     # argument is seed number.$i
598     self.list_of_args = []
599     for i in range(self.total_number_of_jobs):
600     ## Since there is no input, any site is good
601     # self.jobDestination.append(["Any"])
602     self.jobDestination.append([""])
603     ## no random seed
604     self.list_of_args.append([str(i)])
605     return
606    
607 gutsche 1.3 def split(self, jobParams):
608    
609     common.jobDB.load()
610     #### Fabio
611     njobs = self.total_number_of_jobs
612 slacapra 1.9 arglist = self.list_of_args
613 gutsche 1.3 # create the empty structure
614     for i in range(njobs):
615     jobParams.append("")
616    
617     for job in range(njobs):
618 slacapra 1.17 jobParams[job] = arglist[job]
619     # print str(arglist[job])
620     # print jobParams[job]
621 gutsche 1.3 common.jobDB.setArguments(job, jobParams[job])
622 gutsche 1.35 common.logger.debug(5,"Job "+str(job)+" Destination: "+str(self.jobDestination[job]))
623     common.jobDB.setDestination(job, self.jobDestination[job])
624 gutsche 1.3
625     common.jobDB.save()
626     return
627    
628     def getJobTypeArguments(self, nj, sched):
629 slacapra 1.17 result = ''
630     for i in common.jobDB.arguments(nj):
631     result=result+str(i)+" "
632     return result
633 gutsche 1.3
634     def numberOfJobs(self):
635     # Fabio
636     return self.total_number_of_jobs
637    
638 slacapra 1.1 def getTarBall(self, exe):
639     """
640     Return the TarBall with lib and exe
641     """
642    
643     # if it exist, just return it
644 corvo 1.56 #
645     # Marco. Let's start to use relative path for Boss XML files
646     #
647     self.tgzNameWithPath = common.work_space.pathForTgz()+'share/'+self.tgz_name
648 slacapra 1.1 if os.path.exists(self.tgzNameWithPath):
649     return self.tgzNameWithPath
650    
651     # Prepare a tar gzipped file with user binaries.
652     self.buildTar_(exe)
653    
654     return string.strip(self.tgzNameWithPath)
655    
656     def buildTar_(self, executable):
657    
658     # First of all declare the user Scram area
659     swArea = self.scram.getSWArea_()
660     #print "swArea = ", swArea
661 slacapra 1.63 # swVersion = self.scram.getSWVersion()
662     # print "swVersion = ", swVersion
663 slacapra 1.1 swReleaseTop = self.scram.getReleaseTop_()
664     #print "swReleaseTop = ", swReleaseTop
665    
666     ## check if working area is release top
667     if swReleaseTop == '' or swArea == swReleaseTop:
668     return
669    
670 slacapra 1.61 import tarfile
671     try: # create tar ball
672     tar = tarfile.open(self.tgzNameWithPath, "w:gz")
673     ## First find the executable
674     if (self.executable != ''):
675     exeWithPath = self.scram.findFile_(executable)
676     if ( not exeWithPath ):
677     raise CrabException('User executable '+executable+' not found')
678    
679     ## then check if it's private or not
680     if exeWithPath.find(swReleaseTop) == -1:
681     # the exe is private, so we must ship
682     common.logger.debug(5,"Exe "+exeWithPath+" to be tarred")
683     path = swArea+'/'
684     exe = string.replace(exeWithPath, path,'')
685     tar.add(path+exe,exe)
686     pass
687     else:
688     # the exe is from release, we'll find it on WN
689     pass
690    
691     ## Now get the libraries: only those in local working area
692     libDir = 'lib'
693     lib = swArea+'/' +libDir
694     common.logger.debug(5,"lib "+lib+" to be tarred")
695     if os.path.exists(lib):
696     tar.add(lib,libDir)
697    
698     ## Now check if module dir is present
699     moduleDir = 'module'
700     module = swArea + '/' + moduleDir
701     if os.path.isdir(module):
702     tar.add(module,moduleDir)
703    
704     ## Now check if any data dir(s) is present
705     swAreaLen=len(swArea)
706     for root, dirs, files in os.walk(swArea):
707     if "data" in dirs:
708     common.logger.debug(5,"data "+root+"/data"+" to be tarred")
709     tar.add(root+"/data",root[swAreaLen:]+"/data")
710    
711     ## Add ProdAgent dir to tar
712     paDir = 'ProdAgentApi'
713     pa = os.environ['CRABDIR'] + '/' + 'ProdAgentApi'
714     if os.path.isdir(pa):
715     tar.add(pa,paDir)
716    
717     common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
718     tar.close()
719     except :
720     raise CrabException('Could not create tar-ball')
721 corvo 1.56
722 slacapra 1.61 ## create tar-ball with ML stuff
723 corvo 1.58 self.MLtgzfile = common.work_space.pathForTgz()+'share/MLfiles.tgz'
724 slacapra 1.61 try:
725     tar = tarfile.open(self.MLtgzfile, "w:gz")
726     path=os.environ['CRABDIR'] + '/python/'
727     for file in ['report.py', 'DashboardAPI.py', 'Logger.py', 'ProcInfo.py', 'apmon.py', 'parseCrabFjr.py']:
728     tar.add(path+file,file)
729     common.logger.debug(5,"Files added to "+self.MLtgzfile+" : "+str(tar.getnames()))
730     tar.close()
731     except :
732 corvo 1.58 raise CrabException('Could not create ML files tar-ball')
733    
734 slacapra 1.1 return
735    
736     def wsSetupEnvironment(self, nj):
737     """
738     Returns part of a job script which prepares
739     the execution environment for the job 'nj'.
740     """
741     # Prepare JobType-independent part
742 gutsche 1.3 txt = ''
743    
744     ## OLI_Daniele at this level middleware already known
745    
746     txt += 'if [ $middleware == LCG ]; then \n'
747     txt += self.wsSetupCMSLCGEnvironment_()
748     txt += 'elif [ $middleware == OSG ]; then\n'
749 gutsche 1.43 txt += ' WORKING_DIR=`/bin/mktemp -d $OSG_WN_TMP/cms_XXXXXXXXXXXX`\n'
750     txt += ' echo "Created working directory: $WORKING_DIR"\n'
751 gutsche 1.3 txt += ' if [ ! -d $WORKING_DIR ] ;then\n'
752 gutsche 1.7 txt += ' echo "SET_CMS_ENV 10016 ==> OSG $WORKING_DIR could not be created on WN `hostname`"\n'
753     txt += ' echo "JOB_EXIT_STATUS = 10016"\n'
754     txt += ' echo "JobExitCode=10016" | tee -a $RUNTIME_AREA/$repo\n'
755     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
756 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
757     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
758     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
759 gutsche 1.3 txt += ' exit 1\n'
760     txt += ' fi\n'
761     txt += '\n'
762     txt += ' echo "Change to working directory: $WORKING_DIR"\n'
763     txt += ' cd $WORKING_DIR\n'
764     txt += self.wsSetupCMSOSGEnvironment_()
765     txt += 'fi\n'
766 slacapra 1.1
767     # Prepare JobType-specific part
768     scram = self.scram.commandName()
769     txt += '\n\n'
770     txt += 'echo "### SPECIFIC JOB SETUP ENVIRONMENT ###"\n'
771     txt += scram+' project CMSSW '+self.version+'\n'
772     txt += 'status=$?\n'
773     txt += 'if [ $status != 0 ] ; then\n'
774 gutsche 1.7 txt += ' echo "SET_EXE_ENV 10034 ==>ERROR CMSSW '+self.version+' not found on `hostname`" \n'
775 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 10034"\n'
776 gutsche 1.7 txt += ' echo "JobExitCode=10034" | tee -a $RUNTIME_AREA/$repo\n'
777 slacapra 1.1 txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
778 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
779     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
780     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
781 gutsche 1.3 ## OLI_Daniele
782     txt += ' if [ $middleware == OSG ]; then \n'
783     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
784     txt += ' cd $RUNTIME_AREA\n'
785     txt += ' /bin/rm -rf $WORKING_DIR\n'
786     txt += ' if [ -d $WORKING_DIR ] ;then\n'
787 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'
788     txt += ' echo "JOB_EXIT_STATUS = 10018"\n'
789     txt += ' echo "JobExitCode=10018" | tee -a $RUNTIME_AREA/$repo\n'
790     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
791 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
792     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
793     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
794 gutsche 1.3 txt += ' fi\n'
795     txt += ' fi \n'
796     txt += ' exit 1 \n'
797 slacapra 1.1 txt += 'fi \n'
798     txt += 'echo "CMSSW_VERSION = '+self.version+'"\n'
799     txt += 'cd '+self.version+'\n'
800     ### needed grep for bug in scramv1 ###
801 corvo 1.58 txt += scram+' runtime -sh\n'
802 slacapra 1.1 txt += 'eval `'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME`\n'
803 corvo 1.58 txt += 'echo $PATH\n'
804 slacapra 1.1
805     # Handle the arguments:
806     txt += "\n"
807 gutsche 1.7 txt += "## number of arguments (first argument always jobnumber)\n"
808 slacapra 1.1 txt += "\n"
809 mkirn 1.32 # txt += "narg=$#\n"
810     txt += "if [ $nargs -lt 2 ]\n"
811 slacapra 1.1 txt += "then\n"
812 mkirn 1.33 txt += " echo 'SET_EXE_ENV 1 ==> ERROR Too few arguments' +$nargs+ \n"
813 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 50113"\n'
814 gutsche 1.7 txt += ' echo "JobExitCode=50113" | tee -a $RUNTIME_AREA/$repo\n'
815 slacapra 1.1 txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
816 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
817     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
818     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
819 gutsche 1.3 ## OLI_Daniele
820     txt += ' if [ $middleware == OSG ]; then \n'
821     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
822     txt += ' cd $RUNTIME_AREA\n'
823     txt += ' /bin/rm -rf $WORKING_DIR\n'
824     txt += ' if [ -d $WORKING_DIR ] ;then\n'
825 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'
826     txt += ' echo "JOB_EXIT_STATUS = 50114"\n'
827     txt += ' echo "JobExitCode=50114" | tee -a $RUNTIME_AREA/$repo\n'
828     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
829 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
830     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
831     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
832 gutsche 1.3 txt += ' fi\n'
833     txt += ' fi \n'
834 slacapra 1.1 txt += " exit 1\n"
835     txt += "fi\n"
836     txt += "\n"
837    
838     # Prepare job-specific part
839     job = common.job_list[nj]
840 spiga 1.42 if self.pset != None: #CarlosDaniele
841     pset = os.path.basename(job.configFilename())
842     txt += '\n'
843     if (self.datasetPath): # standard job
844     #txt += 'InputFiles=$2\n'
845     txt += 'InputFiles=${args[1]}\n'
846     txt += 'MaxEvents=${args[2]}\n'
847     txt += 'SkipEvents=${args[3]}\n'
848     txt += 'echo "Inputfiles:<$InputFiles>"\n'
849     txt += 'sed "s#{\'INPUT\'}#$InputFiles#" $RUNTIME_AREA/'+pset+' > pset_tmp_1.cfg\n'
850     txt += 'echo "MaxEvents:<$MaxEvents>"\n'
851 gutsche 1.46 txt += 'sed "s#INPUTMAXEVENTS#$MaxEvents#" pset_tmp_1.cfg > pset_tmp_2.cfg\n'
852 spiga 1.42 txt += 'echo "SkipEvents:<$SkipEvents>"\n'
853 gutsche 1.46 txt += 'sed "s#INPUTSKIPEVENTS#$SkipEvents#" pset_tmp_2.cfg > pset.cfg\n'
854 spiga 1.42 else: # pythia like job
855     if (self.sourceSeed):
856 spiga 1.57 txt += 'FirstRun=${args[1]}\n'
857     txt += 'echo "FirstRun: <$FirstRun>"\n'
858     txt += 'sed "s#\<INPUTFIRSTRUN\>#$FirstRun#" $RUNTIME_AREA/'+pset+' > tmp_1.cfg\n'
859     else:
860     txt += '# Copy untouched pset\n'
861     txt += 'cp $RUNTIME_AREA/'+pset+' tmp_1.cfg\n'
862     if (self.sourceSeed):
863 spiga 1.42 # txt += 'Seed=$2\n'
864 spiga 1.57 txt += 'Seed=${args[2]}\n'
865 spiga 1.42 txt += 'echo "Seed: <$Seed>"\n'
866 spiga 1.57 txt += 'sed "s#\<INPUT\>#$Seed#" tmp_1.cfg > tmp_2.cfg\n'
867 spiga 1.42 if (self.sourceSeedVtx):
868     # txt += 'VtxSeed=$3\n'
869 spiga 1.57 txt += 'VtxSeed=${args[3]}\n'
870 spiga 1.42 txt += 'echo "VtxSeed: <$VtxSeed>"\n'
871 spiga 1.57 txt += 'sed "s#INPUTVTX#$VtxSeed#" tmp_2.cfg > pset.cfg\n'
872 spiga 1.42 else:
873 spiga 1.57 txt += 'mv tmp_2.cfg pset.cfg\n'
874 slacapra 1.28 else:
875 spiga 1.57 txt += 'mv tmp_1.cfg pset.cfg\n'
876     # txt += '# Copy untouched pset\n'
877     # txt += 'cp $RUNTIME_AREA/'+pset+' pset.cfg\n'
878 slacapra 1.24
879 slacapra 1.1
880     if len(self.additional_inbox_files) > 0:
881     for file in self.additional_inbox_files:
882 mkirn 1.31 relFile = file.split("/")[-1]
883     txt += 'if [ -e $RUNTIME_AREA/'+relFile+' ] ; then\n'
884     txt += ' cp $RUNTIME_AREA/'+relFile+' .\n'
885     txt += ' chmod +x '+relFile+'\n'
886 slacapra 1.1 txt += 'fi\n'
887     pass
888    
889 spiga 1.42 if self.pset != None: #CarlosDaniele
890     txt += 'echo "### END JOB SETUP ENVIRONMENT ###"\n\n'
891    
892     txt += '\n'
893     txt += 'echo "***** cat pset.cfg *********"\n'
894     txt += 'cat pset.cfg\n'
895     txt += 'echo "****** end pset.cfg ********"\n'
896     txt += '\n'
897     # txt += 'echo "***** cat pset1.cfg *********"\n'
898     # txt += 'cat pset1.cfg\n'
899     # txt += 'echo "****** end pset1.cfg ********"\n'
900 gutsche 1.3 return txt
901    
902 slacapra 1.63 def wsBuildExe(self, nj=0):
903 gutsche 1.3 """
904     Put in the script the commands to build an executable
905     or a library.
906     """
907    
908     txt = ""
909    
910     if os.path.isfile(self.tgzNameWithPath):
911     txt += 'echo "tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'"\n'
912     txt += 'tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
913     txt += 'untar_status=$? \n'
914     txt += 'if [ $untar_status -ne 0 ]; then \n'
915     txt += ' echo "SET_EXE 1 ==> ERROR Untarring .tgz file failed"\n'
916     txt += ' echo "JOB_EXIT_STATUS = $untar_status" \n'
917 gutsche 1.7 txt += ' echo "JobExitCode=$untar_status" | tee -a $RUNTIME_AREA/$repo\n'
918 gutsche 1.3 txt += ' if [ $middleware == OSG ]; then \n'
919     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
920     txt += ' cd $RUNTIME_AREA\n'
921     txt += ' /bin/rm -rf $WORKING_DIR\n'
922     txt += ' if [ -d $WORKING_DIR ] ;then\n'
923 gutsche 1.13 txt += ' echo "SET_EXE 50999 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after Untarring .tgz file failed"\n'
924     txt += ' echo "JOB_EXIT_STATUS = 50999"\n'
925     txt += ' echo "JobExitCode=50999" | tee -a $RUNTIME_AREA/$repo\n'
926     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
927     txt += ' rm -f $RUNTIME_AREA/$repo \n'
928     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
929     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
930 gutsche 1.3 txt += ' fi\n'
931     txt += ' fi \n'
932     txt += ' \n'
933 gutsche 1.7 txt += ' exit 1 \n'
934 gutsche 1.3 txt += 'else \n'
935     txt += ' echo "Successful untar" \n'
936     txt += 'fi \n'
937 gutsche 1.50 txt += '\n'
938     txt += 'echo "Include ProdAgentApi in PYTHONPATH"\n'
939     txt += 'if [ -z "$PYTHONPATH" ]; then\n'
940     txt += ' export PYTHONPATH=ProdAgentApi\n'
941     txt += 'else\n'
942     txt += ' export PYTHONPATH=ProdAgentApi:${PYTHONPATH}\n'
943     txt += 'fi\n'
944     txt += '\n'
945    
946 gutsche 1.3 pass
947    
948 slacapra 1.1 return txt
949    
950     def modifySteeringCards(self, nj):
951     """
952     modify the card provided by the user,
953     writing a new card into share dir
954     """
955    
956     def executableName(self):
957 spiga 1.42 if self.pset == None: #CarlosDaniele
958     return "sh "
959     else:
960     return self.executable
961 slacapra 1.1
962     def executableArgs(self):
963 spiga 1.42 if self.pset == None:#CarlosDaniele
964     return self.scriptExe + " $NJob"
965     else:
966     return " -p pset.cfg"
967 slacapra 1.1
968     def inputSandbox(self, nj):
969     """
970     Returns a list of filenames to be put in JDL input sandbox.
971     """
972     inp_box = []
973 slacapra 1.53 # # dict added to delete duplicate from input sandbox file list
974     # seen = {}
975 slacapra 1.1 ## code
976     if os.path.isfile(self.tgzNameWithPath):
977     inp_box.append(self.tgzNameWithPath)
978 corvo 1.58 if os.path.isfile(self.MLtgzfile):
979     inp_box.append(self.MLtgzfile)
980 slacapra 1.1 ## config
981 spiga 1.42 if not self.pset is None: #CarlosDaniele
982 corvo 1.56 inp_box.append(common.work_space.pathForTgz() + 'job/' + self.configFilename())
983 slacapra 1.1 ## additional input files
984 gutsche 1.3 #for file in self.additional_inbox_files:
985     # inp_box.append(common.work_space.cwdDir()+file)
986 slacapra 1.1 return inp_box
987    
988     def outputSandbox(self, nj):
989     """
990     Returns a list of filenames to be put in JDL output sandbox.
991     """
992     out_box = []
993    
994     ## User Declared output files
995 slacapra 1.54 for out in (self.output_file+self.output_file_sandbox):
996 slacapra 1.1 n_out = nj + 1
997     out_box.append(self.numberFile_(out,str(n_out)))
998     return out_box
999    
1000     def prepareSteeringCards(self):
1001     """
1002     Make initial modifications of the user's steering card file.
1003     """
1004     return
1005    
1006     def wsRenameOutput(self, nj):
1007     """
1008     Returns part of a job script which renames the produced files.
1009     """
1010    
1011     txt = '\n'
1012 gutsche 1.7 txt += '# directory content\n'
1013     txt += 'ls \n'
1014 slacapra 1.54
1015     for fileWithSuffix in (self.output_file+self.output_file_sandbox):
1016 slacapra 1.1 output_file_num = self.numberFile_(fileWithSuffix, '$NJob')
1017     txt += '\n'
1018 gutsche 1.7 txt += '# check output file\n'
1019 slacapra 1.1 txt += 'ls '+fileWithSuffix+'\n'
1020 fanzago 1.18 txt += 'ls_result=$?\n'
1021     txt += 'if [ $ls_result -ne 0 ] ; then\n'
1022     txt += ' echo "ERROR: Problem with output file"\n'
1023 gutsche 1.7 if common.scheduler.boss_scheduler_name == 'condor_g':
1024     txt += ' if [ $middleware == OSG ]; then \n'
1025     txt += ' echo "prepare dummy output file"\n'
1026     txt += ' echo "Processing of job output failed" > $RUNTIME_AREA/'+output_file_num+'\n'
1027     txt += ' fi \n'
1028 slacapra 1.1 txt += 'else\n'
1029     txt += ' cp '+fileWithSuffix+' $RUNTIME_AREA/'+output_file_num+'\n'
1030     txt += 'fi\n'
1031    
1032 gutsche 1.7 txt += 'cd $RUNTIME_AREA\n'
1033 fanzago 1.18 txt += 'cd $RUNTIME_AREA\n'
1034 gutsche 1.3 ### OLI_DANIELE
1035     txt += 'if [ $middleware == OSG ]; then\n'
1036     txt += ' cd $RUNTIME_AREA\n'
1037     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
1038     txt += ' /bin/rm -rf $WORKING_DIR\n'
1039     txt += ' if [ -d $WORKING_DIR ] ;then\n'
1040 gutsche 1.7 txt += ' echo "SET_EXE 60999 ==> OSG $WORKING_DIR could not be deleted on WN `hostname` after cleanup of WN"\n'
1041     txt += ' echo "JOB_EXIT_STATUS = 60999"\n'
1042     txt += ' echo "JobExitCode=60999" | tee -a $RUNTIME_AREA/$repo\n'
1043     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1044 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1045     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1046     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1047 gutsche 1.3 txt += ' fi\n'
1048     txt += 'fi\n'
1049     txt += '\n'
1050 slacapra 1.54
1051     file_list = ''
1052     ## Add to filelist only files to be possibly copied to SE
1053     for fileWithSuffix in self.output_file:
1054     output_file_num = self.numberFile_(fileWithSuffix, '$NJob')
1055     file_list=file_list+output_file_num+' '
1056     file_list=file_list[:-1]
1057     txt += 'file_list="'+file_list+'"\n'
1058    
1059 slacapra 1.1 return txt
1060    
1061     def numberFile_(self, file, txt):
1062     """
1063     append _'txt' before last extension of a file
1064     """
1065     p = string.split(file,".")
1066     # take away last extension
1067     name = p[0]
1068     for x in p[1:-1]:
1069     name=name+"."+x
1070     # add "_txt"
1071     if len(p)>1:
1072     ext = p[len(p)-1]
1073     result = name + '_' + txt + "." + ext
1074     else:
1075     result = name + '_' + txt
1076    
1077     return result
1078    
1079 slacapra 1.63 def getRequirements(self, nj=[]):
1080 slacapra 1.1 """
1081     return job requirements to add to jdl files
1082     """
1083     req = ''
1084 slacapra 1.47 if self.version:
1085 slacapra 1.10 req='Member("VO-cms-' + \
1086 slacapra 1.47 self.version + \
1087 slacapra 1.10 '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
1088 gutsche 1.35
1089     req = req + ' && (other.GlueHostNetworkAdapterOutboundIP)'
1090    
1091 slacapra 1.1 return req
1092 gutsche 1.3
1093     def configFilename(self):
1094     """ return the config filename """
1095     return self.name()+'.cfg'
1096    
1097     ### OLI_DANIELE
1098     def wsSetupCMSOSGEnvironment_(self):
1099     """
1100     Returns part of a job script which is prepares
1101     the execution environment and which is common for all CMS jobs.
1102     """
1103     txt = '\n'
1104     txt += ' echo "### SETUP CMS OSG ENVIRONMENT ###"\n'
1105     txt += ' if [ -f $GRID3_APP_DIR/cmssoft/cmsset_default.sh ] ;then\n'
1106     txt += ' # Use $GRID3_APP_DIR/cmssoft/cmsset_default.sh to setup cms software\n'
1107     txt += ' source $GRID3_APP_DIR/cmssoft/cmsset_default.sh '+self.version+'\n'
1108 mkirn 1.40 txt += ' elif [ -f $OSG_APP/cmssoft/cms/cmsset_default.sh ] ;then\n'
1109     txt += ' # Use $OSG_APP/cmssoft/cms/cmsset_default.sh to setup cms software\n'
1110     txt += ' source $OSG_APP/cmssoft/cms/cmsset_default.sh '+self.version+'\n'
1111 gutsche 1.3 txt += ' else\n'
1112 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'
1113 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 10020"\n'
1114     txt += ' echo "JobExitCode=10020" | tee -a $RUNTIME_AREA/$repo\n'
1115     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1116 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1117     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1118     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1119 gutsche 1.7 txt += ' exit 1\n'
1120 gutsche 1.3 txt += '\n'
1121     txt += ' echo "Remove working directory: $WORKING_DIR"\n'
1122     txt += ' cd $RUNTIME_AREA\n'
1123     txt += ' /bin/rm -rf $WORKING_DIR\n'
1124     txt += ' if [ -d $WORKING_DIR ] ;then\n'
1125 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'
1126 gutsche 1.7 txt += ' echo "JOB_EXIT_STATUS = 10017"\n'
1127     txt += ' echo "JobExitCode=10017" | tee -a $RUNTIME_AREA/$repo\n'
1128     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1129 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1130     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1131     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1132 gutsche 1.3 txt += ' fi\n'
1133     txt += '\n'
1134 gutsche 1.7 txt += ' exit 1\n'
1135 gutsche 1.3 txt += ' fi\n'
1136     txt += '\n'
1137     txt += ' echo "SET_CMS_ENV 0 ==> setup cms environment ok"\n'
1138     txt += ' echo " END SETUP CMS OSG ENVIRONMENT "\n'
1139    
1140     return txt
1141    
1142     ### OLI_DANIELE
1143     def wsSetupCMSLCGEnvironment_(self):
1144     """
1145     Returns part of a job script which is prepares
1146     the execution environment and which is common for all CMS jobs.
1147     """
1148     txt = ' \n'
1149     txt += ' echo " ### SETUP CMS LCG ENVIRONMENT ### "\n'
1150     txt += ' if [ ! $VO_CMS_SW_DIR ] ;then\n'
1151     txt += ' echo "SET_CMS_ENV 10031 ==> ERROR CMS software dir not found on WN `hostname`"\n'
1152     txt += ' echo "JOB_EXIT_STATUS = 10031" \n'
1153     txt += ' echo "JobExitCode=10031" | tee -a $RUNTIME_AREA/$repo\n'
1154     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1155 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1156     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1157     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1158 gutsche 1.7 txt += ' exit 1\n'
1159 gutsche 1.3 txt += ' else\n'
1160     txt += ' echo "Sourcing environment... "\n'
1161     txt += ' if [ ! -s $VO_CMS_SW_DIR/cmsset_default.sh ] ;then\n'
1162     txt += ' echo "SET_CMS_ENV 10020 ==> ERROR cmsset_default.sh file not found into dir $VO_CMS_SW_DIR"\n'
1163     txt += ' echo "JOB_EXIT_STATUS = 10020"\n'
1164     txt += ' echo "JobExitCode=10020" | tee -a $RUNTIME_AREA/$repo\n'
1165     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1166 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1167     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1168     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1169 gutsche 1.7 txt += ' exit 1\n'
1170 gutsche 1.3 txt += ' fi\n'
1171     txt += ' echo "sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1172     txt += ' source $VO_CMS_SW_DIR/cmsset_default.sh\n'
1173     txt += ' result=$?\n'
1174     txt += ' if [ $result -ne 0 ]; then\n'
1175     txt += ' echo "SET_CMS_ENV 10032 ==> ERROR problem sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1176     txt += ' echo "JOB_EXIT_STATUS = 10032"\n'
1177     txt += ' echo "JobExitCode=10032" | tee -a $RUNTIME_AREA/$repo\n'
1178     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1179 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1180     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1181     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1182 gutsche 1.7 txt += ' exit 1\n'
1183 gutsche 1.3 txt += ' fi\n'
1184     txt += ' fi\n'
1185     txt += ' \n'
1186     txt += ' string=`cat /etc/redhat-release`\n'
1187     txt += ' echo $string\n'
1188     txt += ' if [[ $string = *alhalla* ]]; then\n'
1189     txt += ' echo "SCRAM_ARCH= $SCRAM_ARCH"\n'
1190     txt += ' elif [[ $string = *Enterprise* ]] || [[ $string = *cientific* ]]; then\n'
1191     txt += ' export SCRAM_ARCH=slc3_ia32_gcc323\n'
1192     txt += ' echo "SCRAM_ARCH= $SCRAM_ARCH"\n'
1193     txt += ' else\n'
1194 gutsche 1.7 txt += ' echo "SET_CMS_ENV 10033 ==> ERROR OS unknown, LCG environment not initialized"\n'
1195 gutsche 1.3 txt += ' echo "JOB_EXIT_STATUS = 10033"\n'
1196     txt += ' echo "JobExitCode=10033" | tee -a $RUNTIME_AREA/$repo\n'
1197     txt += ' dumpStatus $RUNTIME_AREA/$repo\n'
1198 gutsche 1.13 txt += ' rm -f $RUNTIME_AREA/$repo \n'
1199     txt += ' echo "MonitorJobID=`echo $MonitorJobID`" | tee -a $RUNTIME_AREA/$repo \n'
1200     txt += ' echo "MonitorID=`echo $MonitorID`" | tee -a $RUNTIME_AREA/$repo\n'
1201 gutsche 1.7 txt += ' exit 1\n'
1202 gutsche 1.3 txt += ' fi\n'
1203     txt += ' echo "SET_CMS_ENV 0 ==> setup cms environment ok"\n'
1204     txt += ' echo "### END SETUP CMS LCG ENVIRONMENT ###"\n'
1205     return txt
1206 gutsche 1.5
1207     def setParam_(self, param, value):
1208     self._params[param] = value
1209    
1210     def getParams(self):
1211     return self._params
1212 gutsche 1.8
1213     def setTaskid_(self):
1214     self._taskId = self.cfg_params['taskId']
1215    
1216     def getTaskid(self):
1217     return self._taskId
1218 gutsche 1.35
1219     #######################################################################
1220     def uniquelist(self, old):
1221     """
1222     remove duplicates from a list
1223     """
1224     nd={}
1225     for e in old:
1226     nd[e]=0
1227     return nd.keys()