ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.71
Committed: Mon Mar 5 11:45:29 2007 UTC (18 years, 1 month ago) by slacapra
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_1_5_0_pre8, CRAB_1_5_0_pre7
Changes since 1.70: +2 -17 lines
Log Message:
set SCRAM_ARCH on WN to the one got from user environment

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