ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.291
Committed: Wed Apr 29 13:48:48 2009 UTC (16 years ago) by slacapra
Content type: text/x-python
Branch: MAIN
Changes since 1.290: +4 -17 lines
Log Message:
minor cleanup

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     import Scram
7 spiga 1.269 from Splitter import JobSplitter
8 slacapra 1.1
9 slacapra 1.105 import os, string, glob
10 slacapra 1.1
11     class Cmssw(JobType):
12 spiga 1.208 def __init__(self, cfg_params, ncjobs,skip_blocks, isNew):
13 slacapra 1.1 JobType.__init__(self, 'CMSSW')
14     common.logger.debug(3,'CMSSW::__init__')
15 spiga 1.208 self.skip_blocks = skip_blocks
16 mcinquil 1.140 self.argsList = []
17 mcinquil 1.144
18 gutsche 1.3 self._params = {}
19     self.cfg_params = cfg_params
20 ewv 1.254
21 spiga 1.234 ### Temporary patch to automatically skip the ISB size check:
22     server=self.cfg_params.get('CRAB.server_name',None)
23 ewv 1.250 size = 9.5
24 spiga 1.249 if server or common.scheduler.name().upper() in ['LSF','CAF']: size = 99999
25 spiga 1.234 ### D.S.
26     self.MaxTarBallSize = float(self.cfg_params.get('EDG.maxtarballsize',size))
27 gutsche 1.72
28 gutsche 1.44 # number of jobs requested to be created, limit obj splitting
29 gutsche 1.38 self.ncjobs = ncjobs
30    
31 slacapra 1.1 log = common.logger
32 ewv 1.131
33 slacapra 1.1 self.scram = Scram.Scram(cfg_params)
34     self.additional_inbox_files = []
35     self.scriptExe = ''
36     self.executable = ''
37 slacapra 1.71 self.executable_arch = self.scram.getArch()
38 slacapra 1.1 self.tgz_name = 'default.tgz'
39 corvo 1.56 self.scriptName = 'CMSSW.sh'
40 ewv 1.192 self.pset = ''
41 spiga 1.187 self.datasetPath = ''
42 gutsche 1.3
43 gutsche 1.50 # set FJR file name
44     self.fjrFileName = 'crab_fjr.xml'
45    
46 slacapra 1.1 self.version = self.scram.getSWVersion()
47 slacapra 1.275 common.logger.write("CMSSW version is: "+str(self.version))
48 ewv 1.182 try:
49 slacapra 1.291 type, self.CMSSW_major, self.CMSSW_minor, self.CMSSW_patch = tuple(self.version.split('_'))
50 ewv 1.182 except:
51 ewv 1.184 msg = "Cannot parse CMSSW version string: " + self.version + " for major and minor release number!"
52 ewv 1.182 raise CrabException(msg)
53    
54 ewv 1.276 if self.CMSSW_major < 1 or (self.CMSSW_major == 1 and self.CMSSW_minor < 5):
55     msg = "CRAB supports CMSSW >= 1_5_x only. Use an older CRAB version."
56     raise CrabException(msg)
57     """
58     As CMSSW versions are dropped we can drop more code:
59     1.X dropped: drop support for running .cfg on WN
60     2.0 dropped: drop all support for cfg here and in writeCfg
61     2.0 dropped: Recheck the random number seed support
62     """
63    
64 slacapra 1.1 ### collect Data cards
65 gutsche 1.66
66 ewv 1.226
67 fanzago 1.221 ### Temporary: added to remove input file control in the case of PU
68 farinafa 1.224 self.dataset_pu = cfg_params.get('CMSSW.dataset_pu', None)
69 ewv 1.226
70 slacapra 1.153 tmp = cfg_params['CMSSW.datasetpath']
71     log.debug(6, "CMSSW::CMSSW(): datasetPath = "+tmp)
72 spiga 1.236
73     if tmp =='':
74     msg = "Error: datasetpath not defined "
75     raise CrabException(msg)
76     elif string.lower(tmp)=='none':
77 slacapra 1.153 self.datasetPath = None
78     self.selectNoInput = 1
79     else:
80     self.datasetPath = tmp
81     self.selectNoInput = 0
82 gutsche 1.5
83 slacapra 1.1 self.dataTiers = []
84 spiga 1.288
85     self.debugWrap=''
86 fanzago 1.285 self.debug_wrapper = int(cfg_params.get('USER.debug_wrapper',0))
87     if self.debug_wrapper == 1: self.debugWrap='--debug'
88 slacapra 1.291
89 slacapra 1.1 ## now the application
90 ewv 1.262 self.managedGenerators = ['madgraph','comphep']
91 ewv 1.258 self.generator = cfg_params.get('CMSSW.generator','pythia').lower()
92 slacapra 1.153 self.executable = cfg_params.get('CMSSW.executable','cmsRun')
93     log.debug(6, "CMSSW::CMSSW(): executable = "+self.executable)
94 slacapra 1.1
95 slacapra 1.153 if not cfg_params.has_key('CMSSW.pset'):
96 slacapra 1.1 raise CrabException("PSet file missing. Cannot run cmsRun ")
97 slacapra 1.153 self.pset = cfg_params['CMSSW.pset']
98     log.debug(6, "Cmssw::Cmssw(): PSet file = "+self.pset)
99     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
105     # output files
106 slacapra 1.53 ## stuff which must be returned always via sandbox
107     self.output_file_sandbox = []
108    
109     # add fjr report by default via sandbox
110     self.output_file_sandbox.append(self.fjrFileName)
111    
112     # other output files to be returned via sandbox or copied to SE
113 mcinquil 1.216 outfileflag = False
114 slacapra 1.153 self.output_file = []
115     tmp = cfg_params.get('CMSSW.output_file',None)
116     if tmp :
117 slacapra 1.207 self.output_file = [x.strip() for x in tmp.split(',')]
118 mcinquil 1.216 outfileflag = True #output found
119     #else:
120     # log.message("No output file defined: only stdout/err and the CRAB Framework Job Report will be available\n")
121 slacapra 1.1
122     # script_exe file as additional file in inputSandbox
123 slacapra 1.153 self.scriptExe = cfg_params.get('USER.script_exe',None)
124     if self.scriptExe :
125 slacapra 1.176 if not os.path.isfile(self.scriptExe):
126     msg ="ERROR. file "+self.scriptExe+" not found"
127     raise CrabException(msg)
128     self.additional_inbox_files.append(string.strip(self.scriptExe))
129 slacapra 1.70
130 spiga 1.42 if self.datasetPath == None and self.pset == None and self.scriptExe == '' :
131 slacapra 1.176 msg ="Error. script_exe not defined"
132     raise CrabException(msg)
133 spiga 1.42
134 ewv 1.226 # use parent files...
135 spiga 1.269 self.useParent = int(self.cfg_params.get('CMSSW.use_parent',0))
136 spiga 1.204
137 slacapra 1.1 ## additional input files
138 slacapra 1.153 if cfg_params.has_key('USER.additional_input_files'):
139 slacapra 1.29 tmpAddFiles = string.split(cfg_params['USER.additional_input_files'],',')
140 slacapra 1.70 for tmp in tmpAddFiles:
141     tmp = string.strip(tmp)
142     dirname = ''
143     if not tmp[0]=="/": dirname = "."
144 corvo 1.85 files = []
145     if string.find(tmp,"*")>-1:
146     files = glob.glob(os.path.join(dirname, tmp))
147     if len(files)==0:
148     raise CrabException("No additional input file found with this pattern: "+tmp)
149     else:
150     files.append(tmp)
151 slacapra 1.70 for file in files:
152     if not os.path.exists(file):
153     raise CrabException("Additional input file not found: "+file)
154 slacapra 1.45 pass
155 slacapra 1.105 self.additional_inbox_files.append(string.strip(file))
156 slacapra 1.1 pass
157     pass
158 slacapra 1.70 common.logger.debug(5,"Additional input files: "+str(self.additional_inbox_files))
159 slacapra 1.153 pass
160 gutsche 1.3
161 gutsche 1.35
162 ewv 1.160 ## New method of dealing with seeds
163     self.incrementSeeds = []
164     self.preserveSeeds = []
165     if cfg_params.has_key('CMSSW.preserve_seeds'):
166     tmpList = cfg_params['CMSSW.preserve_seeds'].split(',')
167     for tmp in tmpList:
168     tmp.strip()
169     self.preserveSeeds.append(tmp)
170     if cfg_params.has_key('CMSSW.increment_seeds'):
171     tmpList = cfg_params['CMSSW.increment_seeds'].split(',')
172     for tmp in tmpList:
173     tmp.strip()
174     self.incrementSeeds.append(tmp)
175    
176 slacapra 1.153 self.firstRun = cfg_params.get('CMSSW.first_run',None)
177 slacapra 1.90
178 ewv 1.147 # Copy/return
179 slacapra 1.153 self.copy_data = int(cfg_params.get('USER.copy_data',0))
180     self.return_data = int(cfg_params.get('USER.return_data',0))
181 ewv 1.276
182     self.conf = {}
183     self.conf['pubdata'] = None
184 spiga 1.269 # number of jobs requested to be created, limit obj splitting DD
185 slacapra 1.1 #DBSDLS-start
186 ewv 1.131 ## Initialize the variables that are extracted from DBS/DLS and needed in other places of the code
187 slacapra 1.1 self.maxEvents=0 # max events available ( --> check the requested nb. of evts in Creator.py)
188     self.DBSPaths={} # all dbs paths requested ( --> input to the site local discovery script)
189 gutsche 1.35 self.jobDestination=[] # Site destination(s) for each job (list of lists)
190 slacapra 1.1 ## Perform the data location and discovery (based on DBS/DLS)
191 slacapra 1.9 ## SL: Don't if NONE is specified as input (pythia use case)
192 gutsche 1.35 blockSites = {}
193 slacapra 1.9 if self.datasetPath:
194 gutsche 1.35 blockSites = self.DataDiscoveryAndLocation(cfg_params)
195 ewv 1.131 #DBSDLS-end
196 spiga 1.269 self.conf['blockSites']=blockSites
197    
198 slacapra 1.9 ## Select Splitting
199 spiga 1.269 splitByRun = int(cfg_params.get('CMSSW.split_by_run',0))
200    
201 ewv 1.131 if self.selectNoInput:
202 spiga 1.187 if self.pset == None:
203 ewv 1.276 self.algo = 'ForScript'
204 spiga 1.42 else:
205 spiga 1.271 self.algo = 'NoInput'
206 ewv 1.276 self.conf['managedGenerators']=self.managedGenerators
207     self.conf['generator']=self.generator
208     elif splitByRun ==1:
209     self.algo = 'RunBased'
210 spiga 1.269 else:
211 ewv 1.276 self.algo = 'EventBased'
212    
213     # self.algo = 'LumiBased'
214     splitter = JobSplitter(self.cfg_params,self.conf)
215 spiga 1.269 self.dict = splitter.Algos()[self.algo]()
216 gutsche 1.5
217 spiga 1.208 # modify Pset only the first time
218     if isNew:
219     if self.pset != None:
220     import PsetManipulator as pp
221     PsetEdit = pp.PsetManipulator(self.pset)
222     try:
223     # Add FrameworkJobReport to parameter-set, set max events.
224     # Reset later for data jobs by writeCFG which does all modifications
225 spiga 1.272 PsetEdit.maxEvent(-1)
226 ewv 1.265 PsetEdit.skipEvent(0)
227 spiga 1.208 PsetEdit.psetWriter(self.configFilename())
228 slacapra 1.215 ## If present, add TFileService to output files
229     if not int(cfg_params.get('CMSSW.skip_TFileService_output',0)):
230     tfsOutput = PsetEdit.getTFileService()
231 ewv 1.226 if tfsOutput:
232 slacapra 1.215 if tfsOutput in self.output_file:
233     common.logger.debug(5,"Output from TFileService "+tfsOutput+" already in output files")
234     else:
235 mcinquil 1.216 outfileflag = True #output found
236 slacapra 1.215 self.output_file.append(tfsOutput)
237 ewv 1.280 common.logger.message("Adding "+tfsOutput+" (from TFileService) to list of output files")
238 slacapra 1.218 pass
239     pass
240     ## If present and requested, add PoolOutputModule to output files
241 slacapra 1.219 if int(cfg_params.get('CMSSW.get_edm_output',0)):
242 slacapra 1.218 edmOutput = PsetEdit.getPoolOutputModule()
243 ewv 1.226 if edmOutput:
244 slacapra 1.218 if edmOutput in self.output_file:
245     common.logger.debug(5,"Output from PoolOutputModule "+edmOutput+" already in output files")
246     else:
247     self.output_file.append(edmOutput)
248 ewv 1.280 common.logger.message("Adding "+edmOutput+" (from PoolOutputModule) to list of output files")
249 slacapra 1.218 pass
250     pass
251 slacapra 1.215 except CrabException:
252 spiga 1.208 msg='Error while manipulating ParameterSet: exiting...'
253     raise CrabException(msg)
254 ewv 1.226 ## Prepare inputSandbox TarBall (only the first time)
255 spiga 1.208 self.tgzNameWithPath = self.getTarBall(self.executable)
256 gutsche 1.3
257 slacapra 1.1 def DataDiscoveryAndLocation(self, cfg_params):
258    
259 slacapra 1.86 import DataDiscovery
260     import DataLocation
261 gutsche 1.3 common.logger.debug(10,"CMSSW::DataDiscoveryAndLocation()")
262    
263     datasetPath=self.datasetPath
264    
265 slacapra 1.1 ## Contact the DBS
266 gutsche 1.92 common.logger.message("Contacting Data Discovery Services ...")
267 slacapra 1.1 try:
268 spiga 1.208 self.pubdata=DataDiscovery.DataDiscovery(datasetPath, cfg_params,self.skip_blocks)
269 slacapra 1.1 self.pubdata.fetchDBSInfo()
270    
271 slacapra 1.41 except DataDiscovery.NotExistingDatasetError, ex :
272 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
273     raise CrabException(msg)
274 slacapra 1.41 except DataDiscovery.NoDataTierinProvenanceError, ex :
275 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
276     raise CrabException(msg)
277 slacapra 1.41 except DataDiscovery.DataDiscoveryError, ex:
278 gutsche 1.66 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
279 slacapra 1.1 raise CrabException(msg)
280    
281 gutsche 1.35 self.filesbyblock=self.pubdata.getFiles()
282 slacapra 1.270 #print self.filesbyblock
283 spiga 1.269 self.conf['pubdata']=self.pubdata
284 gutsche 1.3
285 slacapra 1.1 ## get max number of events
286 ewv 1.192 self.maxEvents=self.pubdata.getMaxEvents()
287 slacapra 1.1
288     ## Contact the DLS and build a list of sites hosting the fileblocks
289     try:
290 slacapra 1.41 dataloc=DataLocation.DataLocation(self.filesbyblock.keys(),cfg_params)
291 gutsche 1.6 dataloc.fetchDLSInfo()
292 slacapra 1.263
293 slacapra 1.41 except DataLocation.DataLocationError , ex:
294 slacapra 1.1 msg = 'ERROR ***: failed Data Location in DLS \n %s '%ex.getErrorMessage()
295     raise CrabException(msg)
296 ewv 1.131
297 slacapra 1.1
298 slacapra 1.270 unsorted_sites = dataloc.getSites()
299     #print "Unsorted :",unsorted_sites
300     sites = self.filesbyblock.fromkeys(self.filesbyblock,'')
301     for lfn in self.filesbyblock.keys():
302     #print lfn
303     if unsorted_sites.has_key(lfn):
304     #print "Found ",lfn
305     sites[lfn]=unsorted_sites[lfn]
306     else:
307     #print "Not Found ",lfn
308     sites[lfn]=[]
309     #print sites
310    
311     #print "Sorted :",sites
312 slacapra 1.264 if len(sites)==0:
313 spiga 1.267 msg = 'ERROR ***: no location for any of the blocks of this dataset: \n\t %s \n'%datasetPath
314     msg += "\tMaybe the dataset is located only at T1's (or at T0), where analysis jobs are not allowed\n"
315     msg += "\tPlease check DataDiscovery page https://cmsweb.cern.ch/dbs_discovery/\n"
316 slacapra 1.264 raise CrabException(msg)
317    
318 gutsche 1.35 allSites = []
319     listSites = sites.values()
320 slacapra 1.63 for listSite in listSites:
321     for oneSite in listSite:
322 gutsche 1.35 allSites.append(oneSite)
323 slacapra 1.291 [allSites.append(it) for it in allSites if not allSites.count(it)]
324    
325 gutsche 1.3
326 gutsche 1.92 # screen output
327     common.logger.message("Requested dataset: " + datasetPath + " has " + str(self.maxEvents) + " events in " + str(len(self.filesbyblock.keys())) + " blocks.\n")
328    
329 gutsche 1.35 return sites
330 ewv 1.131
331 spiga 1.42
332 spiga 1.208 def split(self, jobParams,firstJobID):
333 ewv 1.276
334 spiga 1.269 arglist = self.dict['args']
335     njobs = self.dict['njobs']
336     self.jobDestination = self.dict['jobDestination']
337 ewv 1.131
338 slacapra 1.263 if njobs==0:
339     raise CrabException("Ask to split "+str(njobs)+" jobs: aborting")
340    
341 gutsche 1.3 # create the empty structure
342     for i in range(njobs):
343     jobParams.append("")
344 ewv 1.131
345 spiga 1.165 listID=[]
346     listField=[]
347 spiga 1.208 for id in range(njobs):
348     job = id + int(firstJobID)
349     jobParams[id] = arglist[id]
350 spiga 1.167 listID.append(job+1)
351 spiga 1.162 job_ToSave ={}
352 spiga 1.169 concString = ' '
353 spiga 1.165 argu=''
354 spiga 1.208 if len(jobParams[id]):
355     argu += concString.join(jobParams[id] )
356 spiga 1.187 job_ToSave['arguments']= str(job+1)+' '+argu
357 spiga 1.208 job_ToSave['dlsDestination']= self.jobDestination[id]
358 spiga 1.165 listField.append(job_ToSave)
359 spiga 1.169 msg="Job "+str(job)+" Arguments: "+str(job+1)+" "+argu+"\n" \
360 spiga 1.208 +" Destination: "+str(self.jobDestination[id])
361 spiga 1.165 common.logger.debug(5,msg)
362 spiga 1.187 common._db.updateJob_(listID,listField)
363 spiga 1.181 self.argsList = (len(jobParams[0])+1)
364 gutsche 1.3
365     return
366 ewv 1.131
367 gutsche 1.3 def numberOfJobs(self):
368 spiga 1.269 return self.dict['njobs']
369 gutsche 1.3
370 slacapra 1.1 def getTarBall(self, exe):
371     """
372     Return the TarBall with lib and exe
373     """
374 slacapra 1.242 self.tgzNameWithPath = common.work_space.pathForTgz()+self.tgz_name
375 slacapra 1.1 if os.path.exists(self.tgzNameWithPath):
376     return self.tgzNameWithPath
377    
378     # Prepare a tar gzipped file with user binaries.
379     self.buildTar_(exe)
380    
381     return string.strip(self.tgzNameWithPath)
382    
383     def buildTar_(self, executable):
384    
385     # First of all declare the user Scram area
386     swArea = self.scram.getSWArea_()
387     swReleaseTop = self.scram.getReleaseTop_()
388 ewv 1.131
389 slacapra 1.1 ## check if working area is release top
390     if swReleaseTop == '' or swArea == swReleaseTop:
391 afanfani 1.172 common.logger.debug(3,"swArea = "+swArea+" swReleaseTop ="+swReleaseTop)
392 slacapra 1.1 return
393    
394 slacapra 1.61 import tarfile
395     try: # create tar ball
396     tar = tarfile.open(self.tgzNameWithPath, "w:gz")
397     ## First find the executable
398 slacapra 1.86 if (self.executable != ''):
399 slacapra 1.61 exeWithPath = self.scram.findFile_(executable)
400     if ( not exeWithPath ):
401     raise CrabException('User executable '+executable+' not found')
402 ewv 1.131
403 slacapra 1.61 ## then check if it's private or not
404     if exeWithPath.find(swReleaseTop) == -1:
405     # the exe is private, so we must ship
406     common.logger.debug(5,"Exe "+exeWithPath+" to be tarred")
407     path = swArea+'/'
408 corvo 1.85 # distinguish case when script is in user project area or given by full path somewhere else
409     if exeWithPath.find(path) >= 0 :
410     exe = string.replace(exeWithPath, path,'')
411 slacapra 1.129 tar.add(path+exe,exe)
412 corvo 1.85 else :
413     tar.add(exeWithPath,os.path.basename(executable))
414 slacapra 1.61 pass
415     else:
416     # the exe is from release, we'll find it on WN
417     pass
418 ewv 1.131
419 slacapra 1.61 ## Now get the libraries: only those in local working area
420 slacapra 1.256 tar.dereference=True
421 slacapra 1.61 libDir = 'lib'
422     lib = swArea+'/' +libDir
423     common.logger.debug(5,"lib "+lib+" to be tarred")
424     if os.path.exists(lib):
425     tar.add(lib,libDir)
426 ewv 1.131
427 slacapra 1.61 ## Now check if module dir is present
428     moduleDir = 'module'
429     module = swArea + '/' + moduleDir
430     if os.path.isdir(module):
431     tar.add(module,moduleDir)
432 slacapra 1.256 tar.dereference=False
433 slacapra 1.61
434     ## Now check if any data dir(s) is present
435 spiga 1.179 self.dataExist = False
436 slacapra 1.212 todo_list = [(i, i) for i in os.listdir(swArea+"/src")]
437 slacapra 1.206 while len(todo_list):
438     entry, name = todo_list.pop()
439 slacapra 1.211 if name.startswith('crab_0_') or name.startswith('.') or name == 'CVS':
440 slacapra 1.206 continue
441 slacapra 1.212 if os.path.isdir(swArea+"/src/"+entry):
442 slacapra 1.206 entryPath = entry + '/'
443 slacapra 1.212 todo_list += [(entryPath + i, i) for i in os.listdir(swArea+"/src/"+entry)]
444 slacapra 1.206 if name == 'data':
445     self.dataExist=True
446     common.logger.debug(5,"data "+entry+" to be tarred")
447 slacapra 1.212 tar.add(swArea+"/src/"+entry,"src/"+entry)
448 slacapra 1.206 pass
449     pass
450 ewv 1.182
451 spiga 1.179 ### CMSSW ParameterSet
452     if not self.pset is None:
453     cfg_file = common.work_space.jobDir()+self.configFilename()
454 ewv 1.182 tar.add(cfg_file,self.configFilename())
455 slacapra 1.61
456 fanzago 1.93
457 fanzago 1.152 ## Add ProdCommon dir to tar
458 slacapra 1.211 prodcommonDir = './'
459     prodcommonPath = os.environ['CRABDIR'] + '/' + 'external/'
460 spiga 1.244 neededStuff = ['ProdCommon/__init__.py','ProdCommon/FwkJobRep', 'ProdCommon/CMSConfigTools', \
461     'ProdCommon/Core', 'ProdCommon/MCPayloads', 'IMProv', 'ProdCommon/Storage']
462 slacapra 1.214 for file in neededStuff:
463     tar.add(prodcommonPath+file,prodcommonDir+file)
464 spiga 1.179
465     ##### ML stuff
466     ML_file_list=['report.py', 'DashboardAPI.py', 'Logger.py', 'ProcInfo.py', 'apmon.py']
467     path=os.environ['CRABDIR'] + '/python/'
468     for file in ML_file_list:
469     tar.add(path+file,file)
470    
471     ##### Utils
472 spiga 1.238 Utils_file_list=['parseCrabFjr.py','writeCfg.py', 'fillCrabFjr.py','cmscp.py']
473 spiga 1.179 for file in Utils_file_list:
474     tar.add(path+file,file)
475 ewv 1.131
476 ewv 1.182 ##### AdditionalFiles
477 slacapra 1.253 tar.dereference=True
478 spiga 1.179 for file in self.additional_inbox_files:
479     tar.add(file,string.split(file,'/')[-1])
480 slacapra 1.253 tar.dereference=False
481 slacapra 1.263 common.logger.debug(5,"Files in "+self.tgzNameWithPath+" : "+str(tar.getnames()))
482 ewv 1.182
483 slacapra 1.61 tar.close()
484 mcinquil 1.241 except IOError, exc:
485     common.logger.write(str(exc))
486 slacapra 1.220 raise CrabException('Could not create tar-ball '+self.tgzNameWithPath)
487 mcinquil 1.241 except tarfile.TarError, exc:
488     common.logger.write(str(exc))
489 slacapra 1.206 raise CrabException('Could not create tar-ball '+self.tgzNameWithPath)
490 gutsche 1.72
491     ## check for tarball size
492     tarballinfo = os.stat(self.tgzNameWithPath)
493     if ( tarballinfo.st_size > self.MaxTarBallSize*1024*1024 ) :
494 spiga 1.238 msg = 'Input sandbox size of ' + str(float(tarballinfo.st_size)/1024.0/1024.0) + ' MB is larger than the allowed ' + str(self.MaxTarBallSize) \
495 ewv 1.250 +'MB input sandbox limit \n'
496 spiga 1.238 msg += ' and not supported by the direct GRID submission system.\n'
497     msg += ' Please use the CRAB server mode by setting server_name=<NAME> in section [CRAB] of your crab.cfg.\n'
498     msg += ' For further infos please see https://twiki.cern.ch/twiki/bin/view/CMS/CrabServer#CRABSERVER_for_Users'
499     raise CrabException(msg)
500 gutsche 1.72
501 slacapra 1.61 ## create tar-ball with ML stuff
502 slacapra 1.97
503 spiga 1.165 def wsSetupEnvironment(self, nj=0):
504 slacapra 1.1 """
505     Returns part of a job script which prepares
506     the execution environment for the job 'nj'.
507     """
508 ewv 1.276 # FUTURE: Drop support for .cfg when possible
509 ewv 1.184 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
510     psetName = 'pset.py'
511     else:
512     psetName = 'pset.cfg'
513 slacapra 1.1 # Prepare JobType-independent part
514 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupEnvironment\n'
515 fanzago 1.133 txt += 'echo ">>> setup environment"\n'
516 spiga 1.290 txt += 'if [ $middleware == LCG ] || [ $middleware == CAF ] || [ $middleware == LSF ]; then \n'
517 gutsche 1.3 txt += self.wsSetupCMSLCGEnvironment_()
518 ewv 1.283 txt += 'elif [ $middleware == OSG ]; then\n'
519 gutsche 1.43 txt += ' WORKING_DIR=`/bin/mktemp -d $OSG_WN_TMP/cms_XXXXXXXXXXXX`\n'
520 ewv 1.132 txt += ' if [ ! $? == 0 ] ;then\n'
521 fanzago 1.161 txt += ' echo "ERROR ==> OSG $WORKING_DIR could not be created on WN `hostname`"\n'
522     txt += ' job_exit_code=10016\n'
523     txt += ' func_exit\n'
524 gutsche 1.3 txt += ' fi\n'
525 fanzago 1.133 txt += ' echo ">>> Created working directory: $WORKING_DIR"\n'
526 gutsche 1.3 txt += '\n'
527     txt += ' echo "Change to working directory: $WORKING_DIR"\n'
528     txt += ' cd $WORKING_DIR\n'
529 fanzago 1.133 txt += ' echo ">>> current directory (WORKING_DIR): $WORKING_DIR"\n'
530 ewv 1.131 txt += self.wsSetupCMSOSGEnvironment_()
531 spiga 1.282 #Setup SGE Environment
532 ewv 1.283 txt += 'elif [ $middleware == SGE ]; then\n'
533 spiga 1.282 txt += self.wsSetupCMSLCGEnvironment_()
534    
535 edelmann 1.289 txt += 'elif [ $middleware == ARC ]; then\n'
536     txt += self.wsSetupCMSLCGEnvironment_()
537    
538 gutsche 1.3 txt += 'fi\n'
539 slacapra 1.1
540     # Prepare JobType-specific part
541     scram = self.scram.commandName()
542     txt += '\n\n'
543 fanzago 1.133 txt += 'echo ">>> specific cmssw setup environment:"\n'
544     txt += 'echo "CMSSW_VERSION = '+self.version+'"\n'
545 slacapra 1.1 txt += scram+' project CMSSW '+self.version+'\n'
546     txt += 'status=$?\n'
547     txt += 'if [ $status != 0 ] ; then\n'
548 fanzago 1.161 txt += ' echo "ERROR ==> CMSSW '+self.version+' not found on `hostname`" \n'
549     txt += ' job_exit_code=10034\n'
550 fanzago 1.163 txt += ' func_exit\n'
551 slacapra 1.1 txt += 'fi \n'
552     txt += 'cd '+self.version+'\n'
553 spiga 1.277 txt += 'SOFTWARE_DIR=`pwd`; export SOFTWARE_DIR\n'
554 fanzago 1.133 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
555 slacapra 1.1 txt += 'eval `'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME`\n'
556 fanzago 1.180 txt += 'if [ $? != 0 ] ; then\n'
557     txt += ' echo "ERROR ==> Problem with the command: "\n'
558     txt += ' echo "eval \`'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME \` at `hostname`"\n'
559     txt += ' job_exit_code=10034\n'
560     txt += ' func_exit\n'
561     txt += 'fi \n'
562 slacapra 1.1 # Handle the arguments:
563     txt += "\n"
564 gutsche 1.7 txt += "## number of arguments (first argument always jobnumber)\n"
565 slacapra 1.1 txt += "\n"
566 spiga 1.165 txt += "if [ $nargs -lt "+str(self.argsList)+" ]\n"
567 slacapra 1.1 txt += "then\n"
568 fanzago 1.161 txt += " echo 'ERROR ==> Too few arguments' +$nargs+ \n"
569     txt += ' job_exit_code=50113\n'
570     txt += " func_exit\n"
571 slacapra 1.1 txt += "fi\n"
572     txt += "\n"
573    
574     # Prepare job-specific part
575     job = common.job_list[nj]
576 ewv 1.131 if (self.datasetPath):
577 spiga 1.238 self.primaryDataset = self.datasetPath.split("/")[1]
578     DataTier = self.datasetPath.split("/")[2]
579 fanzago 1.93 txt += '\n'
580     txt += 'DatasetPath='+self.datasetPath+'\n'
581    
582 spiga 1.238 txt += 'PrimaryDataset='+self.primaryDataset +'\n'
583     txt += 'DataTier='+DataTier+'\n'
584 fanzago 1.96 txt += 'ApplicationFamily=cmsRun\n'
585 fanzago 1.93
586     else:
587 ewv 1.250 self.primaryDataset = 'null'
588 fanzago 1.93 txt += 'DatasetPath=MCDataTier\n'
589     txt += 'PrimaryDataset=null\n'
590     txt += 'DataTier=null\n'
591     txt += 'ApplicationFamily=MCDataTier\n'
592 ewv 1.170 if self.pset != None:
593 spiga 1.42 pset = os.path.basename(job.configFilename())
594     txt += '\n'
595 spiga 1.95 txt += 'cp $RUNTIME_AREA/'+pset+' .\n'
596 spiga 1.42 if (self.datasetPath): # standard job
597 ewv 1.160 txt += 'InputFiles=${args[1]}; export InputFiles\n'
598 spiga 1.269 if (self.useParent==1):
599 spiga 1.204 txt += 'ParentFiles=${args[2]}; export ParentFiles\n'
600     txt += 'MaxEvents=${args[3]}; export MaxEvents\n'
601     txt += 'SkipEvents=${args[4]}; export SkipEvents\n'
602     else:
603     txt += 'MaxEvents=${args[2]}; export MaxEvents\n'
604     txt += 'SkipEvents=${args[3]}; export SkipEvents\n'
605 spiga 1.42 txt += 'echo "Inputfiles:<$InputFiles>"\n'
606 spiga 1.269 if (self.useParent==1): txt += 'echo "ParentFiles:<$ParentFiles>"\n'
607 spiga 1.42 txt += 'echo "MaxEvents:<$MaxEvents>"\n'
608     txt += 'echo "SkipEvents:<$SkipEvents>"\n'
609     else: # pythia like job
610 ewv 1.258 argNum = 1
611 ewv 1.160 txt += 'PreserveSeeds=' + ','.join(self.preserveSeeds) + '; export PreserveSeeds\n'
612     txt += 'IncrementSeeds=' + ','.join(self.incrementSeeds) + '; export IncrementSeeds\n'
613     txt += 'echo "PreserveSeeds: <$PreserveSeeds>"\n'
614     txt += 'echo "IncrementSeeds:<$IncrementSeeds>"\n'
615 slacapra 1.90 if (self.firstRun):
616 ewv 1.258 txt += 'export FirstRun=${args[%s]}\n' % argNum
617 spiga 1.57 txt += 'echo "FirstRun: <$FirstRun>"\n'
618 ewv 1.258 argNum += 1
619 ewv 1.262 if (self.generator == 'madgraph'):
620 ewv 1.259 txt += 'export FirstEvent=${args[%s]}\n' % argNum
621     txt += 'echo "FirstEvent:<$FirstEvent>"\n'
622     argNum += 1
623 ewv 1.262 elif (self.generator == 'comphep'):
624     txt += 'export CompHEPFirstEvent=${args[%s]}\n' % argNum
625     txt += 'echo "CompHEPFirstEvent:<$CompHEPFirstEvent>"\n'
626     argNum += 1
627 spiga 1.272 txt += 'MaxEvents=${args[%s]}; export MaxEvents\n' % argNum
628 slacapra 1.90
629 ewv 1.184 txt += 'mv -f ' + pset + ' ' + psetName + '\n'
630 slacapra 1.1
631    
632 fanzago 1.163 if self.pset != None:
633 ewv 1.184 # FUTURE: Can simply for 2_1_x and higher
634 spiga 1.42 txt += '\n'
635 fanzago 1.285 if self.debug_wrapper == 1:
636 spiga 1.188 txt += 'echo "***** cat ' + psetName + ' *********"\n'
637     txt += 'cat ' + psetName + '\n'
638     txt += 'echo "****** end ' + psetName + ' ********"\n'
639     txt += '\n'
640 fanzago 1.286 txt += 'echo "***********************" \n'
641     txt += 'which edmConfigHash \n'
642     txt += 'echo "***********************" \n'
643 spiga 1.287 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
644 fanzago 1.286 txt += 'edmConfigHash ' + psetName + ' \n'
645 spiga 1.287 txt += 'PSETHASH=`edmConfigHash ' + psetName + '` \n'
646     else:
647 ewv 1.226 txt += 'PSETHASH=`edmConfigHash < ' + psetName + '` \n'
648 fanzago 1.94 txt += 'echo "PSETHASH = $PSETHASH" \n'
649 fanzago 1.93 txt += '\n'
650 gutsche 1.3 return txt
651 slacapra 1.176
652 fanzago 1.166 def wsUntarSoftware(self, nj=0):
653 gutsche 1.3 """
654     Put in the script the commands to build an executable
655     or a library.
656     """
657    
658 fanzago 1.166 txt = '\n#Written by cms_cmssw::wsUntarSoftware\n'
659 gutsche 1.3
660     if os.path.isfile(self.tgzNameWithPath):
661 fanzago 1.133 txt += 'echo ">>> tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+' :" \n'
662 slacapra 1.255 txt += 'tar xzf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
663 fanzago 1.285 if self.debug_wrapper==1 :
664 slacapra 1.255 txt += 'tar tzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
665 spiga 1.199 txt += 'ls -Al \n'
666 gutsche 1.3 txt += 'untar_status=$? \n'
667     txt += 'if [ $untar_status -ne 0 ]; then \n'
668 fanzago 1.161 txt += ' echo "ERROR ==> Untarring .tgz file failed"\n'
669     txt += ' job_exit_code=$untar_status\n'
670     txt += ' func_exit\n'
671 gutsche 1.3 txt += 'else \n'
672     txt += ' echo "Successful untar" \n'
673     txt += 'fi \n'
674 gutsche 1.50 txt += '\n'
675 slacapra 1.211 txt += 'echo ">>> Include $RUNTIME_AREA in PYTHONPATH:"\n'
676 gutsche 1.50 txt += 'if [ -z "$PYTHONPATH" ]; then\n'
677 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/\n'
678 gutsche 1.50 txt += 'else\n'
679 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/:${PYTHONPATH}\n'
680 fanzago 1.93 txt += 'echo "PYTHONPATH=$PYTHONPATH"\n'
681 gutsche 1.50 txt += 'fi\n'
682     txt += '\n'
683    
684 gutsche 1.3 pass
685 ewv 1.131
686 slacapra 1.1 return txt
687 ewv 1.170
688 fanzago 1.166 def wsBuildExe(self, nj=0):
689     """
690     Put in the script the commands to build an executable
691     or a library.
692     """
693    
694     txt = '\n#Written by cms_cmssw::wsBuildExe\n'
695     txt += 'echo ">>> moving CMSSW software directories in `pwd`" \n'
696    
697 ewv 1.170 txt += 'rm -r lib/ module/ \n'
698     txt += 'mv $RUNTIME_AREA/lib/ . \n'
699     txt += 'mv $RUNTIME_AREA/module/ . \n'
700 spiga 1.186 if self.dataExist == True:
701     txt += 'rm -r src/ \n'
702     txt += 'mv $RUNTIME_AREA/src/ . \n'
703 ewv 1.182 if len(self.additional_inbox_files)>0:
704 spiga 1.179 for file in self.additional_inbox_files:
705 spiga 1.191 txt += 'mv $RUNTIME_AREA/'+os.path.basename(file)+' . \n'
706 slacapra 1.214 # txt += 'mv $RUNTIME_AREA/ProdCommon/ . \n'
707     # txt += 'mv $RUNTIME_AREA/IMProv/ . \n'
708 ewv 1.170
709 slacapra 1.211 txt += 'echo ">>> Include $RUNTIME_AREA in PYTHONPATH:"\n'
710 fanzago 1.166 txt += 'if [ -z "$PYTHONPATH" ]; then\n'
711 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/\n'
712 fanzago 1.166 txt += 'else\n'
713 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/:${PYTHONPATH}\n'
714 fanzago 1.166 txt += 'echo "PYTHONPATH=$PYTHONPATH"\n'
715     txt += 'fi\n'
716     txt += '\n'
717    
718     return txt
719 slacapra 1.1
720 ewv 1.131
721 slacapra 1.1 def executableName(self):
722 ewv 1.192 if self.scriptExe:
723 spiga 1.42 return "sh "
724     else:
725     return self.executable
726 slacapra 1.1
727     def executableArgs(self):
728 ewv 1.160 # FUTURE: This function tests the CMSSW version. Can be simplified as we drop support for old versions
729 ewv 1.276 if self.scriptExe:
730     return self.scriptExe + " $NJob"
731 fanzago 1.115 else:
732 ewv 1.160 ex_args = ""
733 ewv 1.276 ex_args += " -j $RUNTIME_AREA/crab_fjr_$NJob.xml"
734     # Type of config file depends on CMSSW version
735 ewv 1.184 if self.CMSSW_major >= 2 :
736 ewv 1.171 ex_args += " -p pset.py"
737 fanzago 1.115 else:
738 ewv 1.160 ex_args += " -p pset.cfg"
739     return ex_args
740 slacapra 1.1
741     def inputSandbox(self, nj):
742     """
743     Returns a list of filenames to be put in JDL input sandbox.
744     """
745     inp_box = []
746     if os.path.isfile(self.tgzNameWithPath):
747     inp_box.append(self.tgzNameWithPath)
748 spiga 1.243 inp_box.append(common.work_space.jobDir() + self.scriptName)
749 slacapra 1.1 return inp_box
750    
751     def outputSandbox(self, nj):
752     """
753     Returns a list of filenames to be put in JDL output sandbox.
754     """
755     out_box = []
756    
757     ## User Declared output files
758 slacapra 1.54 for out in (self.output_file+self.output_file_sandbox):
759 ewv 1.131 n_out = nj + 1
760 slacapra 1.207 out_box.append(numberFile(out,str(n_out)))
761 slacapra 1.1 return out_box
762    
763    
764     def wsRenameOutput(self, nj):
765     """
766     Returns part of a job script which renames the produced files.
767     """
768    
769 ewv 1.160 txt = '\n#Written by cms_cmssw::wsRenameOutput\n'
770 fanzago 1.148 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
771     txt += 'echo ">>> current directory content:"\n'
772 fanzago 1.285 if self.debug_wrapper==1:
773 spiga 1.199 txt += 'ls -Al\n'
774 fanzago 1.145 txt += '\n'
775 slacapra 1.54
776 fanzago 1.128 for fileWithSuffix in (self.output_file):
777 slacapra 1.207 output_file_num = numberFile(fileWithSuffix, '$NJob')
778 slacapra 1.1 txt += '\n'
779 gutsche 1.7 txt += '# check output file\n'
780 slacapra 1.106 txt += 'if [ -e ./'+fileWithSuffix+' ] ; then\n'
781 ewv 1.147 if (self.copy_data == 1): # For OSG nodes, file is in $WORKING_DIR, should not be moved to $RUNTIME_AREA
782     txt += ' mv '+fileWithSuffix+' '+output_file_num+'\n'
783 spiga 1.209 txt += ' ln -s `pwd`/'+output_file_num+' $RUNTIME_AREA/'+fileWithSuffix+'\n'
784 ewv 1.147 else:
785     txt += ' mv '+fileWithSuffix+' $RUNTIME_AREA/'+output_file_num+'\n'
786     txt += ' ln -s $RUNTIME_AREA/'+output_file_num+' $RUNTIME_AREA/'+fileWithSuffix+'\n'
787 slacapra 1.106 txt += 'else\n'
788 fanzago 1.161 txt += ' job_exit_code=60302\n'
789     txt += ' echo "WARNING: Output file '+fileWithSuffix+' not found"\n'
790 ewv 1.156 if common.scheduler.name().upper() == 'CONDOR_G':
791 gutsche 1.7 txt += ' if [ $middleware == OSG ]; then \n'
792     txt += ' echo "prepare dummy output file"\n'
793     txt += ' echo "Processing of job output failed" > $RUNTIME_AREA/'+output_file_num+'\n'
794     txt += ' fi \n'
795 slacapra 1.1 txt += 'fi\n'
796 slacapra 1.105 file_list = []
797     for fileWithSuffix in (self.output_file):
798 spiga 1.246 file_list.append(numberFile('$SOFTWARE_DIR/'+fileWithSuffix, '$NJob'))
799 ewv 1.131
800 spiga 1.245 txt += 'file_list="'+string.join(file_list,',')+'"\n'
801 fanzago 1.149 txt += '\n'
802 fanzago 1.148 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
803     txt += 'echo ">>> current directory content:"\n'
804 fanzago 1.285 if self.debug_wrapper==1:
805 spiga 1.199 txt += 'ls -Al\n'
806 fanzago 1.148 txt += '\n'
807 gutsche 1.7 txt += 'cd $RUNTIME_AREA\n'
808 fanzago 1.133 txt += 'echo ">>> current directory (RUNTIME_AREA): $RUNTIME_AREA"\n'
809 slacapra 1.1 return txt
810    
811 slacapra 1.63 def getRequirements(self, nj=[]):
812 slacapra 1.1 """
813 ewv 1.131 return job requirements to add to jdl files
814 slacapra 1.1 """
815     req = ''
816 slacapra 1.47 if self.version:
817 slacapra 1.10 req='Member("VO-cms-' + \
818 slacapra 1.47 self.version + \
819 slacapra 1.10 '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
820 ewv 1.192 if self.executable_arch:
821 gutsche 1.107 req+=' && Member("VO-cms-' + \
822 slacapra 1.105 self.executable_arch + \
823     '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
824 gutsche 1.35
825     req = req + ' && (other.GlueHostNetworkAdapterOutboundIP)'
826 afanfani 1.229 if ( common.scheduler.name() == "glitecoll" ) or ( common.scheduler.name() == "glite"):
827 afanfani 1.158 req += ' && other.GlueCEStateStatus == "Production" '
828 gutsche 1.35
829 slacapra 1.1 return req
830 gutsche 1.3
831     def configFilename(self):
832     """ return the config filename """
833 ewv 1.182 # FUTURE: Can remove cfg mode for CMSSW >= 2_1_x
834 ewv 1.184 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
835 ewv 1.182 return self.name()+'.py'
836     else:
837     return self.name()+'.cfg'
838 gutsche 1.3
839     def wsSetupCMSOSGEnvironment_(self):
840     """
841     Returns part of a job script which is prepares
842     the execution environment and which is common for all CMS jobs.
843     """
844 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupCMSOSGEnvironment_\n'
845     txt += ' echo ">>> setup CMS OSG environment:"\n'
846 fanzago 1.133 txt += ' echo "set SCRAM ARCH to ' + self.executable_arch + '"\n'
847     txt += ' export SCRAM_ARCH='+self.executable_arch+'\n'
848 fanzago 1.136 txt += ' echo "SCRAM_ARCH = $SCRAM_ARCH"\n'
849 ewv 1.135 txt += ' if [ -f $OSG_APP/cmssoft/cms/cmsset_default.sh ] ;then\n'
850 mkirn 1.40 txt += ' # Use $OSG_APP/cmssoft/cms/cmsset_default.sh to setup cms software\n'
851 fanzago 1.133 txt += ' source $OSG_APP/cmssoft/cms/cmsset_default.sh '+self.version+'\n'
852     txt += ' else\n'
853 fanzago 1.161 txt += ' echo "ERROR ==> $OSG_APP/cmssoft/cms/cmsset_default.sh file not found"\n'
854     txt += ' job_exit_code=10020\n'
855     txt += ' func_exit\n'
856 fanzago 1.133 txt += ' fi\n'
857 gutsche 1.3 txt += '\n'
858 fanzago 1.161 txt += ' echo "==> setup cms environment ok"\n'
859 fanzago 1.136 txt += ' echo "SCRAM_ARCH = $SCRAM_ARCH"\n'
860 gutsche 1.3
861     return txt
862 ewv 1.131
863 gutsche 1.3 def wsSetupCMSLCGEnvironment_(self):
864     """
865     Returns part of a job script which is prepares
866     the execution environment and which is common for all CMS jobs.
867     """
868 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupCMSLCGEnvironment_\n'
869     txt += ' echo ">>> setup CMS LCG environment:"\n'
870 fanzago 1.133 txt += ' echo "set SCRAM ARCH and BUILD_ARCH to ' + self.executable_arch + ' ###"\n'
871     txt += ' export SCRAM_ARCH='+self.executable_arch+'\n'
872     txt += ' export BUILD_ARCH='+self.executable_arch+'\n'
873     txt += ' if [ ! $VO_CMS_SW_DIR ] ;then\n'
874 fanzago 1.161 txt += ' echo "ERROR ==> CMS software dir not found on WN `hostname`"\n'
875     txt += ' job_exit_code=10031\n'
876     txt += ' func_exit\n'
877 fanzago 1.133 txt += ' else\n'
878     txt += ' echo "Sourcing environment... "\n'
879     txt += ' if [ ! -s $VO_CMS_SW_DIR/cmsset_default.sh ] ;then\n'
880 fanzago 1.161 txt += ' echo "ERROR ==> cmsset_default.sh file not found into dir $VO_CMS_SW_DIR"\n'
881     txt += ' job_exit_code=10020\n'
882     txt += ' func_exit\n'
883 fanzago 1.133 txt += ' fi\n'
884     txt += ' echo "sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
885     txt += ' source $VO_CMS_SW_DIR/cmsset_default.sh\n'
886     txt += ' result=$?\n'
887     txt += ' if [ $result -ne 0 ]; then\n'
888 fanzago 1.161 txt += ' echo "ERROR ==> problem sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
889     txt += ' job_exit_code=10032\n'
890     txt += ' func_exit\n'
891 fanzago 1.133 txt += ' fi\n'
892     txt += ' fi\n'
893     txt += ' \n'
894 fanzago 1.161 txt += ' echo "==> setup cms environment ok"\n'
895 gutsche 1.3 return txt
896 gutsche 1.5
897 spiga 1.238 def wsModifyReport(self, nj):
898 fanzago 1.93 """
899 ewv 1.131 insert the part of the script that modifies the FrameworkJob Report
900 fanzago 1.93 """
901 ewv 1.250
902 fanzago 1.281 txt = ''
903 fanzago 1.286 publish_data = int(self.cfg_params.get('USER.publish_data',0))
904     if (publish_data == 1):
905     #if (self.copy_data == 1):
906 fanzago 1.281 txt = '\n#Written by cms_cmssw::wsModifyReport\n'
907 fanzago 1.286 #publish_data = int(self.cfg_params.get('USER.publish_data',0))
908 ewv 1.283
909 spiga 1.238
910     txt += 'if [ $StageOutExitStatus -eq 0 ]; then\n'
911 fanzago 1.248 txt += ' FOR_LFN=$LFNBaseName\n'
912 fanzago 1.175 txt += 'else\n'
913     txt += ' FOR_LFN=/copy_problems/ \n'
914     txt += 'fi\n'
915 ewv 1.182
916 fanzago 1.175 txt += 'echo ">>> Modify Job Report:" \n'
917 fanzago 1.217 txt += 'chmod a+x $RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py\n'
918 fanzago 1.175 txt += 'echo "SE = $SE"\n'
919     txt += 'echo "SE_PATH = $SE_PATH"\n'
920     txt += 'echo "FOR_LFN = $FOR_LFN" \n'
921     txt += 'echo "CMSSW_VERSION = $CMSSW_VERSION"\n\n'
922 fanzago 1.281
923    
924     args = 'fjr $RUNTIME_AREA/crab_fjr_$NJob.xml n_job $NJob for_lfn $FOR_LFN PrimaryDataset $PrimaryDataset ApplicationFamily $ApplicationFamily ApplicationName $executable cmssw_version $CMSSW_VERSION psethash $PSETHASH se_name $SE se_path $SE_PATH'
925 fanzago 1.286 #if (publish_data == 1):
926     processedDataset = self.cfg_params['USER.publish_data_name']
927     txt += 'ProcessedDataset='+processedDataset+'\n'
928     txt += 'echo "ProcessedDataset = $ProcessedDataset"\n'
929     args += ' UserProcessedDataset $USER-$ProcessedDataset-$PSETHASH'
930 fanzago 1.281
931 fanzago 1.247 txt += 'echo "$RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py '+str(args)+'"\n'
932     txt += '$RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py '+str(args)+'\n'
933 fanzago 1.175 txt += 'modifyReport_result=$?\n'
934     txt += 'if [ $modifyReport_result -ne 0 ]; then\n'
935     txt += ' modifyReport_result=70500\n'
936     txt += ' job_exit_code=$modifyReport_result\n'
937     txt += ' echo "ModifyReportResult=$modifyReport_result" | tee -a $RUNTIME_AREA/$repo\n'
938     txt += ' echo "WARNING: Problem with ModifyJobReport"\n'
939     txt += 'else\n'
940     txt += ' mv NewFrameworkJobReport.xml $RUNTIME_AREA/crab_fjr_$NJob.xml\n'
941 spiga 1.103 txt += 'fi\n'
942 fanzago 1.93 return txt
943 ewv 1.283
944 ewv 1.192 def wsParseFJR(self):
945 spiga 1.189 """
946 ewv 1.192 Parse the FrameworkJobReport to obtain useful infos
947 spiga 1.189 """
948     txt = '\n#Written by cms_cmssw::wsParseFJR\n'
949     txt += 'echo ">>> Parse FrameworkJobReport crab_fjr.xml"\n'
950     txt += 'if [ -s $RUNTIME_AREA/crab_fjr_$NJob.xml ]; then\n'
951     txt += ' if [ -s $RUNTIME_AREA/parseCrabFjr.py ]; then\n'
952 spiga 1.197 txt += ' cmd_out=`python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --dashboard $MonitorID,$MonitorJobID '+self.debugWrap+'`\n'
953 fanzago 1.285 if self.debug_wrapper==1 :
954 spiga 1.197 txt += ' echo "Result of parsing the FrameworkJobReport crab_fjr.xml: $cmd_out"\n'
955     txt += ' executable_exit_status=`python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --exitcode`\n'
956 spiga 1.189 txt += ' if [ $executable_exit_status -eq 50115 ];then\n'
957     txt += ' echo ">>> crab_fjr.xml contents: "\n'
958 spiga 1.222 txt += ' cat $RUNTIME_AREA/crab_fjr_$NJob.xml\n'
959 spiga 1.189 txt += ' echo "Wrong FrameworkJobReport --> does not contain useful info. ExitStatus: $executable_exit_status"\n'
960 spiga 1.197 txt += ' elif [ $executable_exit_status -eq -999 ];then\n'
961     txt += ' echo "ExitStatus from FrameworkJobReport not available. not available. Using exit code of executable from command line."\n'
962 spiga 1.189 txt += ' else\n'
963     txt += ' echo "Extracted ExitStatus from FrameworkJobReport parsing output: $executable_exit_status"\n'
964     txt += ' fi\n'
965     txt += ' else\n'
966     txt += ' echo "CRAB python script to parse CRAB FrameworkJobReport crab_fjr.xml is not available, using exit code of executable from command line."\n'
967     txt += ' fi\n'
968     #### Patch to check input data reading for CMSSW16x Hopefully we-ll remove it asap
969 spiga 1.232 txt += ' if [ $executable_exit_status -eq 0 ];then\n'
970 fanzago 1.273 txt += ' echo ">>> Executable succeded $executable_exit_status"\n'
971 spiga 1.269 if (self.datasetPath and not (self.dataset_pu or self.useParent==1)) :
972 spiga 1.189 # VERIFY PROCESSED DATA
973 fanzago 1.273 txt += ' echo ">>> Verify list of processed files:"\n'
974     txt += ' echo $InputFiles |tr -d \'\\\\\' |tr \',\' \'\\n\'|tr -d \'"\' > input-files.txt\n'
975     txt += ' python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --lfn > processed-files.txt\n'
976     txt += ' cat input-files.txt | sort | uniq > tmp.txt\n'
977     txt += ' mv tmp.txt input-files.txt\n'
978     txt += ' echo "cat input-files.txt"\n'
979     txt += ' echo "----------------------"\n'
980     txt += ' cat input-files.txt\n'
981     txt += ' cat processed-files.txt | sort | uniq > tmp.txt\n'
982     txt += ' mv tmp.txt processed-files.txt\n'
983     txt += ' echo "----------------------"\n'
984     txt += ' echo "cat processed-files.txt"\n'
985     txt += ' echo "----------------------"\n'
986     txt += ' cat processed-files.txt\n'
987     txt += ' echo "----------------------"\n'
988 spiga 1.278 txt += ' diff -qbB input-files.txt processed-files.txt\n'
989 fanzago 1.273 txt += ' fileverify_status=$?\n'
990     txt += ' if [ $fileverify_status -ne 0 ]; then\n'
991     txt += ' executable_exit_status=30001\n'
992     txt += ' echo "ERROR ==> not all input files processed"\n'
993     txt += ' echo " ==> list of processed files from crab_fjr.xml differs from list in pset.cfg"\n'
994     txt += ' echo " ==> diff input-files.txt processed-files.txt"\n'
995     txt += ' fi\n'
996 spiga 1.232 txt += ' fi\n'
997 spiga 1.189 txt += 'else\n'
998     txt += ' echo "CRAB FrameworkJobReport crab_fjr.xml is not available, using exit code of executable from command line."\n'
999     txt += 'fi\n'
1000     txt += '\n'
1001 fanzago 1.279 txt += 'if [ $executable_exit_status -ne 0 ] && [ $executable_exit_status -ne 50115 ] && [ $executable_exit_status -ne 50117 ] && [ $executable_exit_status -ne 30001 ];then\n'
1002 fanzago 1.273 txt += ' echo ">>> Executable failed $executable_exit_status"\n'
1003     txt += ' echo "ExeExitCode=$executable_exit_status" | tee -a $RUNTIME_AREA/$repo\n'
1004     txt += ' echo "EXECUTABLE_EXIT_STATUS = $executable_exit_status"\n'
1005     txt += ' job_exit_code=$executable_exit_status\n'
1006     txt += ' func_exit\n'
1007     txt += 'fi\n\n'
1008 spiga 1.189 txt += 'echo "ExeExitCode=$executable_exit_status" | tee -a $RUNTIME_AREA/$repo\n'
1009     txt += 'echo "EXECUTABLE_EXIT_STATUS = $executable_exit_status"\n'
1010     txt += 'job_exit_code=$executable_exit_status\n'
1011    
1012     return txt
1013    
1014 gutsche 1.5 def setParam_(self, param, value):
1015     self._params[param] = value
1016    
1017     def getParams(self):
1018     return self._params
1019 gutsche 1.8
1020 spiga 1.257 def outList(self,list=False):
1021 mcinquil 1.121 """
1022     check the dimension of the output files
1023     """
1024 spiga 1.169 txt = ''
1025     txt += 'echo ">>> list of expected files on output sandbox"\n'
1026 mcinquil 1.121 listOutFiles = []
1027 ewv 1.170 stdout = 'CMSSW_$NJob.stdout'
1028 spiga 1.169 stderr = 'CMSSW_$NJob.stderr'
1029 spiga 1.268 if len(self.output_file) <= 0:
1030     msg ="WARNING: no output files name have been defined!!\n"
1031     msg+="\tno output files will be reported back/staged\n"
1032     common.logger.message(msg)
1033 fanzago 1.148 if (self.return_data == 1):
1034 spiga 1.157 for file in (self.output_file+self.output_file_sandbox):
1035 slacapra 1.207 listOutFiles.append(numberFile(file, '$NJob'))
1036 spiga 1.169 listOutFiles.append(stdout)
1037     listOutFiles.append(stderr)
1038 ewv 1.156 else:
1039 spiga 1.157 for file in (self.output_file_sandbox):
1040 slacapra 1.207 listOutFiles.append(numberFile(file, '$NJob'))
1041 spiga 1.169 listOutFiles.append(stdout)
1042     listOutFiles.append(stderr)
1043 fanzago 1.161 txt += 'echo "output files: '+string.join(listOutFiles,' ')+'"\n'
1044 spiga 1.157 txt += 'filesToCheck="'+string.join(listOutFiles,' ')+'"\n'
1045 spiga 1.169 txt += 'export filesToCheck\n'
1046 ewv 1.276
1047 spiga 1.257 if list : return self.output_file
1048 ewv 1.170 return txt