ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.64
Committed: Thu Jan 18 18:29:51 2007 UTC (18 years, 3 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_1_5_0_pre5
Changes since 1.63: +10 -9 lines
Log Message:
fix check existence of additional input files before doing anything with them

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