ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.300
Committed: Wed May 20 13:51:45 2009 UTC (15 years, 11 months ago) by spiga
Content type: text/x-python
Branch: MAIN
Changes since 1.299: +43 -29 lines
Log Message:
re-enabled -extend functionality. Revisited default.tgz preparation

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