ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.53
Committed: Wed Oct 25 17:53:51 2006 UTC (18 years, 6 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
Changes since 1.52: +11 -7 lines
Log Message:
The FJR produced by each jobs is always returned via output sandbox even if the ouput is copied to a SE, as already happens for stdout and err

File Contents

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