ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.255
Committed: Fri Oct 31 11:04:06 2008 UTC (16 years, 5 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_4_3_pre3, CRAB_2_4_3_pre2, CRAB_2_4_3_pre1, CRAB_2_4_2, CRAB_2_4_2_pre3, CRAB_2_4_2_pre2
Changes since 1.254: +2 -1 lines
Log Message:
print tar-ball content on WN only if debug_wrapper is set

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 ewv 1.250 from WMCore.SiteScreening.BlackWhiteListParser import SEBlackWhiteListParser
6 slacapra 1.1 import common
7     import Scram
8    
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 ewv 1.226
17 mcinquil 1.140 self.argsList = []
18 mcinquil 1.144
19 gutsche 1.3 self._params = {}
20     self.cfg_params = cfg_params
21 ewv 1.254
22 fanzago 1.115 # init BlackWhiteListParser
23 ewv 1.254 seWhiteList = cfg_params.get('EDG.se_white_list',[])
24     seBlackList = cfg_params.get('EDG.se_black_list',[])
25     self.blackWhiteListParser = SEBlackWhiteListParser(seWhiteList, seBlackList, common.logger)
26 fanzago 1.115
27 spiga 1.234 ### Temporary patch to automatically skip the ISB size check:
28     server=self.cfg_params.get('CRAB.server_name',None)
29 ewv 1.250 size = 9.5
30 spiga 1.249 if server or common.scheduler.name().upper() in ['LSF','CAF']: size = 99999
31 spiga 1.234 ### D.S.
32     self.MaxTarBallSize = float(self.cfg_params.get('EDG.maxtarballsize',size))
33 gutsche 1.72
34 gutsche 1.44 # number of jobs requested to be created, limit obj splitting
35 gutsche 1.38 self.ncjobs = ncjobs
36    
37 slacapra 1.1 log = common.logger
38 ewv 1.131
39 slacapra 1.1 self.scram = Scram.Scram(cfg_params)
40     self.additional_inbox_files = []
41     self.scriptExe = ''
42     self.executable = ''
43 slacapra 1.71 self.executable_arch = self.scram.getArch()
44 slacapra 1.1 self.tgz_name = 'default.tgz'
45 corvo 1.56 self.scriptName = 'CMSSW.sh'
46 ewv 1.192 self.pset = ''
47 spiga 1.187 self.datasetPath = ''
48 gutsche 1.3
49 gutsche 1.50 # set FJR file name
50     self.fjrFileName = 'crab_fjr.xml'
51    
52 slacapra 1.1 self.version = self.scram.getSWVersion()
53 ewv 1.182 version_array = self.version.split('_')
54 ewv 1.184 self.CMSSW_major = 0
55     self.CMSSW_minor = 0
56     self.CMSSW_patch = 0
57 ewv 1.182 try:
58 ewv 1.184 self.CMSSW_major = int(version_array[1])
59     self.CMSSW_minor = int(version_array[2])
60     self.CMSSW_patch = int(version_array[3])
61 ewv 1.182 except:
62 ewv 1.184 msg = "Cannot parse CMSSW version string: " + self.version + " for major and minor release number!"
63 ewv 1.182 raise CrabException(msg)
64    
65 slacapra 1.1 ### collect Data cards
66 gutsche 1.66
67 slacapra 1.153 if not cfg_params.has_key('CMSSW.datasetpath'):
68 ewv 1.131 msg = "Error: datasetpath not defined "
69 slacapra 1.1 raise CrabException(msg)
70 ewv 1.226
71 fanzago 1.221 ### Temporary: added to remove input file control in the case of PU
72 farinafa 1.224 self.dataset_pu = cfg_params.get('CMSSW.dataset_pu', None)
73 ewv 1.226
74 slacapra 1.153 tmp = cfg_params['CMSSW.datasetpath']
75     log.debug(6, "CMSSW::CMSSW(): datasetPath = "+tmp)
76 spiga 1.236
77     if tmp =='':
78     msg = "Error: datasetpath not defined "
79     raise CrabException(msg)
80     elif string.lower(tmp)=='none':
81 slacapra 1.153 self.datasetPath = None
82     self.selectNoInput = 1
83     else:
84     self.datasetPath = tmp
85     self.selectNoInput = 0
86 gutsche 1.5
87 slacapra 1.1 self.dataTiers = []
88 spiga 1.197 self.debugWrap = ''
89     self.debug_wrapper = cfg_params.get('USER.debug_wrapper',False)
90     if self.debug_wrapper: self.debugWrap='--debug'
91 slacapra 1.1 ## now the application
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.204 self.useParent = self.cfg_params.get('CMSSW.use_parent',False)
136    
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 slacapra 1.9 ## Events per job
162 slacapra 1.153 if cfg_params.has_key('CMSSW.events_per_job'):
163 slacapra 1.10 self.eventsPerJob =int( cfg_params['CMSSW.events_per_job'])
164 slacapra 1.9 self.selectEventsPerJob = 1
165 slacapra 1.153 else:
166 slacapra 1.9 self.eventsPerJob = -1
167     self.selectEventsPerJob = 0
168 ewv 1.131
169 slacapra 1.22 ## number of jobs
170 slacapra 1.153 if cfg_params.has_key('CMSSW.number_of_jobs'):
171 slacapra 1.22 self.theNumberOfJobs =int( cfg_params['CMSSW.number_of_jobs'])
172     self.selectNumberOfJobs = 1
173 slacapra 1.153 else:
174 slacapra 1.22 self.theNumberOfJobs = 0
175     self.selectNumberOfJobs = 0
176 slacapra 1.10
177 slacapra 1.153 if cfg_params.has_key('CMSSW.total_number_of_events'):
178 gutsche 1.35 self.total_number_of_events = int(cfg_params['CMSSW.total_number_of_events'])
179     self.selectTotalNumberEvents = 1
180 spiga 1.193 if self.selectNumberOfJobs == 1:
181 spiga 1.202 if (self.total_number_of_events != -1) and int(self.total_number_of_events) < int(self.theNumberOfJobs):
182 spiga 1.193 msg = 'Must specify at least one event per job. total_number_of_events > number_of_jobs '
183     raise CrabException(msg)
184 slacapra 1.153 else:
185 gutsche 1.35 self.total_number_of_events = 0
186     self.selectTotalNumberEvents = 0
187    
188 spiga 1.187 if self.pset != None:
189 spiga 1.42 if ( (self.selectTotalNumberEvents + self.selectEventsPerJob + self.selectNumberOfJobs) != 2 ):
190     msg = 'Must define exactly two of total_number_of_events, events_per_job, or number_of_jobs.'
191     raise CrabException(msg)
192     else:
193     if (self.selectNumberOfJobs == 0):
194     msg = 'Must specify number_of_jobs.'
195     raise CrabException(msg)
196 gutsche 1.35
197 ewv 1.160 ## New method of dealing with seeds
198     self.incrementSeeds = []
199     self.preserveSeeds = []
200     if cfg_params.has_key('CMSSW.preserve_seeds'):
201     tmpList = cfg_params['CMSSW.preserve_seeds'].split(',')
202     for tmp in tmpList:
203     tmp.strip()
204     self.preserveSeeds.append(tmp)
205     if cfg_params.has_key('CMSSW.increment_seeds'):
206     tmpList = cfg_params['CMSSW.increment_seeds'].split(',')
207     for tmp in tmpList:
208     tmp.strip()
209     self.incrementSeeds.append(tmp)
210    
211 ewv 1.227 ## FUTURE: Can remove in CRAB 2.4.0
212     self.sourceSeed = cfg_params.get('CMSSW.pythia_seed',None)
213 slacapra 1.153 self.sourceSeedVtx = cfg_params.get('CMSSW.vtx_seed',None)
214 ewv 1.227 self.sourceSeedG4 = cfg_params.get('CMSSW.g4_seed',None)
215 slacapra 1.153 self.sourceSeedMix = cfg_params.get('CMSSW.mix_seed',None)
216 ewv 1.227 if self.sourceSeed or self.sourceSeedVtx or self.sourceSeedG4 or self.sourceSeedMix:
217     msg = 'pythia_seed, vtx_seed, g4_seed, and mix_seed are no longer valid settings. You must use increment_seeds or preserve_seeds'
218     raise CrabException(msg)
219 slacapra 1.90
220 slacapra 1.153 self.firstRun = cfg_params.get('CMSSW.first_run',None)
221 slacapra 1.90
222 ewv 1.147 # Copy/return
223 slacapra 1.153 self.copy_data = int(cfg_params.get('USER.copy_data',0))
224     self.return_data = int(cfg_params.get('USER.return_data',0))
225 ewv 1.147
226 slacapra 1.1 #DBSDLS-start
227 ewv 1.131 ## Initialize the variables that are extracted from DBS/DLS and needed in other places of the code
228 slacapra 1.1 self.maxEvents=0 # max events available ( --> check the requested nb. of evts in Creator.py)
229     self.DBSPaths={} # all dbs paths requested ( --> input to the site local discovery script)
230 gutsche 1.35 self.jobDestination=[] # Site destination(s) for each job (list of lists)
231 slacapra 1.1 ## Perform the data location and discovery (based on DBS/DLS)
232 slacapra 1.9 ## SL: Don't if NONE is specified as input (pythia use case)
233 gutsche 1.35 blockSites = {}
234 slacapra 1.9 if self.datasetPath:
235 gutsche 1.35 blockSites = self.DataDiscoveryAndLocation(cfg_params)
236 ewv 1.131 #DBSDLS-end
237 slacapra 1.1
238 slacapra 1.9 ## Select Splitting
239 ewv 1.131 if self.selectNoInput:
240 spiga 1.187 if self.pset == None:
241 spiga 1.42 self.jobSplittingForScript()
242     else:
243     self.jobSplittingNoInput()
244 afanfani 1.237 elif (cfg_params.get('CMSSW.noblockboundary',0)):
245     self.jobSplittingNoBlockBoundary(blockSites)
246 gutsche 1.92 else:
247 corvo 1.56 self.jobSplittingByBlocks(blockSites)
248 gutsche 1.5
249 spiga 1.208 # modify Pset only the first time
250     if isNew:
251     if self.pset != None:
252     import PsetManipulator as pp
253     PsetEdit = pp.PsetManipulator(self.pset)
254     try:
255     # Add FrameworkJobReport to parameter-set, set max events.
256     # Reset later for data jobs by writeCFG which does all modifications
257     PsetEdit.addCrabFJR(self.fjrFileName) # FUTURE: Job report addition not needed by CMSSW>1.5
258     PsetEdit.maxEvent(self.eventsPerJob)
259     PsetEdit.psetWriter(self.configFilename())
260 slacapra 1.215 ## If present, add TFileService to output files
261     if not int(cfg_params.get('CMSSW.skip_TFileService_output',0)):
262     tfsOutput = PsetEdit.getTFileService()
263 ewv 1.226 if tfsOutput:
264 slacapra 1.215 if tfsOutput in self.output_file:
265     common.logger.debug(5,"Output from TFileService "+tfsOutput+" already in output files")
266     else:
267 mcinquil 1.216 outfileflag = True #output found
268 slacapra 1.215 self.output_file.append(tfsOutput)
269     common.logger.message("Adding "+tfsOutput+" to output files (from TFileService)")
270 slacapra 1.218 pass
271     pass
272     ## If present and requested, add PoolOutputModule to output files
273 slacapra 1.219 if int(cfg_params.get('CMSSW.get_edm_output',0)):
274 slacapra 1.218 edmOutput = PsetEdit.getPoolOutputModule()
275 ewv 1.226 if edmOutput:
276 slacapra 1.218 if edmOutput in self.output_file:
277     common.logger.debug(5,"Output from PoolOutputModule "+edmOutput+" already in output files")
278     else:
279     self.output_file.append(edmOutput)
280     common.logger.message("Adding "+edmOutput+" to output files (from PoolOutputModule)")
281     pass
282     pass
283 slacapra 1.215 except CrabException:
284 spiga 1.208 msg='Error while manipulating ParameterSet: exiting...'
285     raise CrabException(msg)
286 ewv 1.226 ## Prepare inputSandbox TarBall (only the first time)
287 spiga 1.208 self.tgzNameWithPath = self.getTarBall(self.executable)
288 gutsche 1.3
289 slacapra 1.1 def DataDiscoveryAndLocation(self, cfg_params):
290    
291 slacapra 1.86 import DataDiscovery
292     import DataLocation
293 gutsche 1.3 common.logger.debug(10,"CMSSW::DataDiscoveryAndLocation()")
294    
295     datasetPath=self.datasetPath
296    
297 slacapra 1.1 ## Contact the DBS
298 gutsche 1.92 common.logger.message("Contacting Data Discovery Services ...")
299 slacapra 1.1 try:
300 spiga 1.208 self.pubdata=DataDiscovery.DataDiscovery(datasetPath, cfg_params,self.skip_blocks)
301 slacapra 1.1 self.pubdata.fetchDBSInfo()
302    
303 slacapra 1.41 except DataDiscovery.NotExistingDatasetError, ex :
304 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
305     raise CrabException(msg)
306 slacapra 1.41 except DataDiscovery.NoDataTierinProvenanceError, ex :
307 slacapra 1.1 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
308     raise CrabException(msg)
309 slacapra 1.41 except DataDiscovery.DataDiscoveryError, ex:
310 gutsche 1.66 msg = 'ERROR ***: failed Data Discovery in DBS : %s'%ex.getErrorMessage()
311 slacapra 1.1 raise CrabException(msg)
312    
313 gutsche 1.35 self.filesbyblock=self.pubdata.getFiles()
314 mkirn 1.37 self.eventsbyblock=self.pubdata.getEventsPerBlock()
315     self.eventsbyfile=self.pubdata.getEventsPerFile()
316 spiga 1.204 self.parentFiles=self.pubdata.getParent()
317 gutsche 1.3
318 slacapra 1.1 ## get max number of events
319 ewv 1.192 self.maxEvents=self.pubdata.getMaxEvents()
320 slacapra 1.1
321     ## Contact the DLS and build a list of sites hosting the fileblocks
322     try:
323 slacapra 1.41 dataloc=DataLocation.DataLocation(self.filesbyblock.keys(),cfg_params)
324 gutsche 1.6 dataloc.fetchDLSInfo()
325 slacapra 1.41 except DataLocation.DataLocationError , ex:
326 slacapra 1.1 msg = 'ERROR ***: failed Data Location in DLS \n %s '%ex.getErrorMessage()
327     raise CrabException(msg)
328 ewv 1.131
329 slacapra 1.1
330 gutsche 1.35 sites = dataloc.getSites()
331     allSites = []
332     listSites = sites.values()
333 slacapra 1.63 for listSite in listSites:
334     for oneSite in listSite:
335 gutsche 1.35 allSites.append(oneSite)
336     allSites = self.uniquelist(allSites)
337 gutsche 1.3
338 gutsche 1.92 # screen output
339     common.logger.message("Requested dataset: " + datasetPath + " has " + str(self.maxEvents) + " events in " + str(len(self.filesbyblock.keys())) + " blocks.\n")
340    
341 gutsche 1.35 return sites
342 ewv 1.131
343 gutsche 1.35 def jobSplittingByBlocks(self, blockSites):
344 slacapra 1.9 """
345 gutsche 1.35 Perform job splitting. Jobs run over an integer number of files
346     and no more than one block.
347     ARGUMENT: blockSites: dictionary with blocks as keys and list of host sites as values
348     REQUIRES: self.selectTotalNumberEvents, self.selectEventsPerJob, self.selectNumberofJobs,
349     self.total_number_of_events, self.eventsPerJob, self.theNumberOfJobs,
350     self.maxEvents, self.filesbyblock
351     SETS: self.jobDestination - Site destination(s) for each job (a list of lists)
352     self.total_number_of_jobs - Total # of jobs
353     self.list_of_args - File(s) job will run on (a list of lists)
354     """
355    
356     # ---- Handle the possible job splitting configurations ---- #
357     if (self.selectTotalNumberEvents):
358     totalEventsRequested = self.total_number_of_events
359     if (self.selectEventsPerJob):
360     eventsPerJobRequested = self.eventsPerJob
361     if (self.selectNumberOfJobs):
362     totalEventsRequested = self.theNumberOfJobs * self.eventsPerJob
363    
364     # If user requested all the events in the dataset
365     if (totalEventsRequested == -1):
366     eventsRemaining=self.maxEvents
367     # If user requested more events than are in the dataset
368     elif (totalEventsRequested > self.maxEvents):
369     eventsRemaining = self.maxEvents
370     common.logger.message("Requested "+str(self.total_number_of_events)+ " events, but only "+str(self.maxEvents)+" events are available.")
371     # If user requested less events than are in the dataset
372     else:
373     eventsRemaining = totalEventsRequested
374 slacapra 1.22
375 slacapra 1.41 # If user requested more events per job than are in the dataset
376     if (self.selectEventsPerJob and eventsPerJobRequested > self.maxEvents):
377     eventsPerJobRequested = self.maxEvents
378    
379 gutsche 1.35 # For user info at end
380     totalEventCount = 0
381 gutsche 1.3
382 gutsche 1.35 if (self.selectTotalNumberEvents and self.selectNumberOfJobs):
383     eventsPerJobRequested = int(eventsRemaining/self.theNumberOfJobs)
384 slacapra 1.22
385 gutsche 1.35 if (self.selectNumberOfJobs):
386     common.logger.message("May not create the exact number_of_jobs requested.")
387 slacapra 1.23
388 gutsche 1.38 if ( self.ncjobs == 'all' ) :
389     totalNumberOfJobs = 999999999
390     else :
391     totalNumberOfJobs = self.ncjobs
392 ewv 1.131
393 gutsche 1.35 blocks = blockSites.keys()
394     blockCount = 0
395     # Backup variable in case self.maxEvents counted events in a non-included block
396     numBlocksInDataset = len(blocks)
397 gutsche 1.3
398 gutsche 1.35 jobCount = 0
399     list_of_lists = []
400 gutsche 1.3
401 gutsche 1.92 # list tracking which jobs are in which jobs belong to which block
402     jobsOfBlock = {}
403    
404 gutsche 1.35 # ---- Iterate over the blocks in the dataset until ---- #
405     # ---- we've met the requested total # of events ---- #
406 gutsche 1.38 while ( (eventsRemaining > 0) and (blockCount < numBlocksInDataset) and (jobCount < totalNumberOfJobs)):
407 gutsche 1.35 block = blocks[blockCount]
408 gutsche 1.44 blockCount += 1
409 gutsche 1.104 if block not in jobsOfBlock.keys() :
410     jobsOfBlock[block] = []
411 ewv 1.131
412 gutsche 1.68 if self.eventsbyblock.has_key(block) :
413     numEventsInBlock = self.eventsbyblock[block]
414     common.logger.debug(5,'Events in Block File '+str(numEventsInBlock))
415 ewv 1.131
416 gutsche 1.68 files = self.filesbyblock[block]
417     numFilesInBlock = len(files)
418     if (numFilesInBlock <= 0):
419     continue
420     fileCount = 0
421    
422     # ---- New block => New job ---- #
423 ewv 1.131 parString = ""
424 gutsche 1.68 # counter for number of events in files currently worked on
425     filesEventCount = 0
426     # flag if next while loop should touch new file
427     newFile = 1
428     # job event counter
429     jobSkipEventCount = 0
430 ewv 1.131
431 gutsche 1.68 # ---- Iterate over the files in the block until we've met the requested ---- #
432     # ---- total # of events or we've gone over all the files in this block ---- #
433 spiga 1.204 pString=''
434 gutsche 1.68 while ( (eventsRemaining > 0) and (fileCount < numFilesInBlock) and (jobCount < totalNumberOfJobs) ):
435     file = files[fileCount]
436 spiga 1.204 if self.useParent:
437     parent = self.parentFiles[file]
438     for f in parent :
439     pString += '\\\"' + f + '\\\"\,'
440     common.logger.debug(6, "File "+str(file)+" has the following parents: "+str(parent))
441     common.logger.write("File "+str(file)+" has the following parents: "+str(parent))
442 gutsche 1.68 if newFile :
443     try:
444     numEventsInFile = self.eventsbyfile[file]
445     common.logger.debug(6, "File "+str(file)+" has "+str(numEventsInFile)+" events")
446     # increase filesEventCount
447     filesEventCount += numEventsInFile
448     # Add file to current job
449     parString += '\\\"' + file + '\\\"\,'
450     newFile = 0
451     except KeyError:
452     common.logger.message("File "+str(file)+" has unknown number of events: skipping")
453 ewv 1.131
454 slacapra 1.177 eventsPerJobRequested = min(eventsPerJobRequested, eventsRemaining)
455 gutsche 1.68 # if less events in file remain than eventsPerJobRequested
456 slacapra 1.177 if ( filesEventCount - jobSkipEventCount < eventsPerJobRequested):
457 gutsche 1.68 # if last file in block
458     if ( fileCount == numFilesInBlock-1 ) :
459     # end job using last file, use remaining events in block
460     # close job and touch new file
461     fullString = parString[:-2]
462 spiga 1.204 if self.useParent:
463     fullParentString = pString[:-2]
464     list_of_lists.append([fullString,fullParentString,str(-1),str(jobSkipEventCount)])
465     else:
466     list_of_lists.append([fullString,str(-1),str(jobSkipEventCount)])
467 gutsche 1.68 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(filesEventCount - jobSkipEventCount)+" events (last file in block).")
468     self.jobDestination.append(blockSites[block])
469     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
470 gutsche 1.92 # fill jobs of block dictionary
471 gutsche 1.104 jobsOfBlock[block].append(jobCount+1)
472 gutsche 1.68 # reset counter
473     jobCount = jobCount + 1
474     totalEventCount = totalEventCount + filesEventCount - jobSkipEventCount
475     eventsRemaining = eventsRemaining - filesEventCount + jobSkipEventCount
476     jobSkipEventCount = 0
477     # reset file
478 spiga 1.204 pString = ""
479 ewv 1.131 parString = ""
480 gutsche 1.68 filesEventCount = 0
481     newFile = 1
482     fileCount += 1
483     else :
484     # go to next file
485     newFile = 1
486     fileCount += 1
487     # if events in file equal to eventsPerJobRequested
488     elif ( filesEventCount - jobSkipEventCount == eventsPerJobRequested ) :
489 gutsche 1.38 # close job and touch new file
490     fullString = parString[:-2]
491 spiga 1.204 if self.useParent:
492     fullParentString = pString[:-2]
493     list_of_lists.append([fullString,fullParentString,str(eventsPerJobRequested),str(jobSkipEventCount)])
494 ewv 1.226 else:
495 spiga 1.204 list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
496 gutsche 1.68 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
497 gutsche 1.38 self.jobDestination.append(blockSites[block])
498     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
499 gutsche 1.104 jobsOfBlock[block].append(jobCount+1)
500 gutsche 1.38 # reset counter
501     jobCount = jobCount + 1
502 gutsche 1.68 totalEventCount = totalEventCount + eventsPerJobRequested
503     eventsRemaining = eventsRemaining - eventsPerJobRequested
504 gutsche 1.38 jobSkipEventCount = 0
505     # reset file
506 spiga 1.204 pString = ""
507 ewv 1.131 parString = ""
508 gutsche 1.38 filesEventCount = 0
509     newFile = 1
510     fileCount += 1
511 ewv 1.131
512 gutsche 1.68 # if more events in file remain than eventsPerJobRequested
513 gutsche 1.38 else :
514 gutsche 1.68 # close job but don't touch new file
515     fullString = parString[:-2]
516 spiga 1.204 if self.useParent:
517     fullParentString = pString[:-2]
518     list_of_lists.append([fullString,fullParentString,str(eventsPerJobRequested),str(jobSkipEventCount)])
519     else:
520     list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
521 gutsche 1.68 common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
522     self.jobDestination.append(blockSites[block])
523     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
524 gutsche 1.104 jobsOfBlock[block].append(jobCount+1)
525 gutsche 1.68 # increase counter
526     jobCount = jobCount + 1
527     totalEventCount = totalEventCount + eventsPerJobRequested
528     eventsRemaining = eventsRemaining - eventsPerJobRequested
529     # calculate skip events for last file
530     # use filesEventCount (contains several files), jobSkipEventCount and eventsPerJobRequest
531     jobSkipEventCount = eventsPerJobRequested - (filesEventCount - jobSkipEventCount - self.eventsbyfile[file])
532     # remove all but the last file
533     filesEventCount = self.eventsbyfile[file]
534 spiga 1.204 if self.useParent:
535     for f in parent : pString += '\\\"' + f + '\\\"\,'
536 ewv 1.160 parString = '\\\"' + file + '\\\"\,'
537 gutsche 1.68 pass # END if
538     pass # END while (iterate over files in the block)
539 gutsche 1.35 pass # END while (iterate over blocks in the dataset)
540 slacapra 1.41 self.ncjobs = self.total_number_of_jobs = jobCount
541 gutsche 1.38 if (eventsRemaining > 0 and jobCount < totalNumberOfJobs ):
542 gutsche 1.35 common.logger.message("Could not run on all requested events because some blocks not hosted at allowed sites.")
543 gutsche 1.92 common.logger.message(str(jobCount)+" job(s) can run on "+str(totalEventCount)+" events.\n")
544 ewv 1.131
545 gutsche 1.92 # screen output
546     screenOutput = "List of jobs and available destination sites:\n\n"
547    
548 mcinquil 1.124 # keep trace of block with no sites to print a warning at the end
549     noSiteBlock = []
550     bloskNoSite = []
551    
552 gutsche 1.92 blockCounter = 0
553 gutsche 1.104 for block in blocks:
554     if block in jobsOfBlock.keys() :
555     blockCounter += 1
556 slacapra 1.176 screenOutput += "Block %5i: jobs %20s: sites: %s\n" % (blockCounter,spanRanges(jobsOfBlock[block]),
557     ','.join(self.blackWhiteListParser.checkWhiteList(self.blackWhiteListParser.checkBlackList(blockSites[block],block),block)))
558 mcinquil 1.124 if len(self.blackWhiteListParser.checkWhiteList(self.blackWhiteListParser.checkBlackList(blockSites[block],block),block)) == 0:
559 ewv 1.131 noSiteBlock.append( spanRanges(jobsOfBlock[block]) )
560 mcinquil 1.124 bloskNoSite.append( blockCounter )
561 ewv 1.131
562 mcinquil 1.124 common.logger.message(screenOutput)
563 fanzago 1.127 if len(noSiteBlock) > 0 and len(bloskNoSite) > 0:
564 mcinquil 1.126 msg = 'WARNING: No sites are hosting any part of data for block:\n '
565     virgola = ""
566     if len(bloskNoSite) > 1:
567     virgola = ","
568     for block in bloskNoSite:
569     msg += ' ' + str(block) + virgola
570     msg += '\n Related jobs:\n '
571     virgola = ""
572     if len(noSiteBlock) > 1:
573     virgola = ","
574     for range_jobs in noSiteBlock:
575     msg += str(range_jobs) + virgola
576     msg += '\n will not be submitted and this block of data can not be analyzed!\n'
577 slacapra 1.155 if self.cfg_params.has_key('EDG.se_white_list'):
578     msg += 'WARNING: SE White List: '+self.cfg_params['EDG.se_white_list']+'\n'
579     msg += '(Hint: By whitelisting you force the job to run at this particular site(s).\n'
580     msg += 'Please check if the dataset is available at this site!)\n'
581     if self.cfg_params.has_key('EDG.ce_white_list'):
582     msg += 'WARNING: CE White List: '+self.cfg_params['EDG.ce_white_list']+'\n'
583     msg += '(Hint: By whitelisting you force the job to run at this particular site(s).\n'
584     msg += 'Please check if the dataset is available at this site!)\n'
585    
586 mcinquil 1.126 common.logger.message(msg)
587 gutsche 1.92
588 slacapra 1.9 self.list_of_args = list_of_lists
589     return
590    
591 afanfani 1.237 def jobSplittingNoBlockBoundary(self,blockSites):
592     """
593     """
594     # ---- Handle the possible job splitting configurations ---- #
595     if (self.selectTotalNumberEvents):
596     totalEventsRequested = self.total_number_of_events
597     if (self.selectEventsPerJob):
598     eventsPerJobRequested = self.eventsPerJob
599     if (self.selectNumberOfJobs):
600     totalEventsRequested = self.theNumberOfJobs * self.eventsPerJob
601 ewv 1.250
602 afanfani 1.237 # If user requested all the events in the dataset
603     if (totalEventsRequested == -1):
604     eventsRemaining=self.maxEvents
605     # If user requested more events than are in the dataset
606     elif (totalEventsRequested > self.maxEvents):
607     eventsRemaining = self.maxEvents
608     common.logger.message("Requested "+str(self.total_number_of_events)+ " events, but only "+str(self.maxEvents)+" events are available.")
609     # If user requested less events than are in the dataset
610     else:
611     eventsRemaining = totalEventsRequested
612 ewv 1.250
613 afanfani 1.237 # If user requested more events per job than are in the dataset
614     if (self.selectEventsPerJob and eventsPerJobRequested > self.maxEvents):
615     eventsPerJobRequested = self.maxEvents
616 ewv 1.250
617 afanfani 1.237 # For user info at end
618     totalEventCount = 0
619    
620     if (self.selectTotalNumberEvents and self.selectNumberOfJobs):
621     eventsPerJobRequested = int(eventsRemaining/self.theNumberOfJobs)
622 ewv 1.250
623 afanfani 1.237 if (self.selectNumberOfJobs):
624     common.logger.message("May not create the exact number_of_jobs requested.")
625 ewv 1.250
626 afanfani 1.237 if ( self.ncjobs == 'all' ) :
627     totalNumberOfJobs = 999999999
628     else :
629     totalNumberOfJobs = self.ncjobs
630 ewv 1.250
631 afanfani 1.237 blocks = blockSites.keys()
632     blockCount = 0
633     # Backup variable in case self.maxEvents counted events in a non-included block
634     numBlocksInDataset = len(blocks)
635 ewv 1.250
636 afanfani 1.237 jobCount = 0
637     list_of_lists = []
638    
639     #AF
640     #AF do not reset input files and event count on block boundary
641     #AF
642     parString=""
643     filesEventCount = 0
644     #AF
645    
646     # list tracking which jobs are in which jobs belong to which block
647     jobsOfBlock = {}
648     while ( (eventsRemaining > 0) and (blockCount < numBlocksInDataset) and (jobCount < totalNumberOfJobs)):
649     block = blocks[blockCount]
650     blockCount += 1
651     if block not in jobsOfBlock.keys() :
652     jobsOfBlock[block] = []
653    
654     if self.eventsbyblock.has_key(block) :
655     numEventsInBlock = self.eventsbyblock[block]
656     common.logger.debug(5,'Events in Block File '+str(numEventsInBlock))
657     files = self.filesbyblock[block]
658     numFilesInBlock = len(files)
659     if (numFilesInBlock <= 0):
660     continue
661     fileCount = 0
662     #AF
663     #AF do not reset input files and event count of block boundary
664     #AF
665     ## ---- New block => New job ---- #
666     #parString = ""
667     # counter for number of events in files currently worked on
668     #filesEventCount = 0
669     #AF
670     # flag if next while loop should touch new file
671     newFile = 1
672     # job event counter
673     jobSkipEventCount = 0
674    
675     # ---- Iterate over the files in the block until we've met the requested ---- #
676     # ---- total # of events or we've gone over all the files in this block ---- #
677     pString=''
678     while ( (eventsRemaining > 0) and (fileCount < numFilesInBlock) and (jobCount < totalNumberOfJobs) ):
679     file = files[fileCount]
680     if self.useParent:
681     parent = self.parentFiles[file]
682     for f in parent :
683     pString += '\\\"' + f + '\\\"\,'
684     common.logger.debug(6, "File "+str(file)+" has the following parents: "+str(parent))
685     common.logger.write("File "+str(file)+" has the following parents: "+str(parent))
686     if newFile :
687     try:
688     numEventsInFile = self.eventsbyfile[file]
689     common.logger.debug(6, "File "+str(file)+" has "+str(numEventsInFile)+" events")
690     # increase filesEventCount
691 ewv 1.250 filesEventCount += numEventsInFile
692 afanfani 1.237 # Add file to current job
693     parString += '\\\"' + file + '\\\"\,'
694     newFile = 0
695     except KeyError:
696     common.logger.message("File "+str(file)+" has unknown number of events: skipping")
697     eventsPerJobRequested = min(eventsPerJobRequested, eventsRemaining)
698 ewv 1.250 #common.logger.message("AF filesEventCount %s - jobSkipEventCount %s "%(filesEventCount,jobSkipEventCount))
699 afanfani 1.237 # if less events in file remain than eventsPerJobRequested
700     if ( filesEventCount - jobSkipEventCount < eventsPerJobRequested):
701     #AF
702     #AF skip fileboundary part
703     #AF
704     # go to next file
705     newFile = 1
706     fileCount += 1
707     # if events in file equal to eventsPerJobRequested
708     elif ( filesEventCount - jobSkipEventCount == eventsPerJobRequested ) :
709     # close job and touch new file
710     fullString = parString[:-2]
711     if self.useParent:
712     fullParentString = pString[:-2]
713     list_of_lists.append([fullString,fullParentString,str(eventsPerJobRequested),str(jobSkipEventCount)])
714     else:
715     list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
716     common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
717     self.jobDestination.append(blockSites[block])
718     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
719     jobsOfBlock[block].append(jobCount+1)
720     # reset counter
721     jobCount = jobCount + 1
722     totalEventCount = totalEventCount + eventsPerJobRequested
723     eventsRemaining = eventsRemaining - eventsPerJobRequested
724     jobSkipEventCount = 0
725     # reset file
726     pString = ""
727     parString = ""
728     filesEventCount = 0
729     newFile = 1
730     fileCount += 1
731    
732     # if more events in file remain than eventsPerJobRequested
733     else :
734     # close job but don't touch new file
735     fullString = parString[:-2]
736     if self.useParent:
737     fullParentString = pString[:-2]
738     list_of_lists.append([fullString,fullParentString,str(eventsPerJobRequested),str(jobSkipEventCount)])
739     else:
740     list_of_lists.append([fullString,str(eventsPerJobRequested),str(jobSkipEventCount)])
741     common.logger.debug(3,"Job "+str(jobCount+1)+" can run over "+str(eventsPerJobRequested)+" events.")
742     self.jobDestination.append(blockSites[block])
743     common.logger.debug(5,"Job "+str(jobCount+1)+" Destination: "+str(self.jobDestination[jobCount]))
744     jobsOfBlock[block].append(jobCount+1)
745     # increase counter
746     jobCount = jobCount + 1
747     totalEventCount = totalEventCount + eventsPerJobRequested
748     eventsRemaining = eventsRemaining - eventsPerJobRequested
749     # calculate skip events for last file
750     # use filesEventCount (contains several files), jobSkipEventCount and eventsPerJobRequest
751     jobSkipEventCount = eventsPerJobRequested - (filesEventCount - jobSkipEventCount - self.eventsbyfile[file])
752     # remove all but the last file
753     filesEventCount = self.eventsbyfile[file]
754     if self.useParent:
755     for f in parent : pString += '\\\"' + f + '\\\"\,'
756     parString = '\\\"' + file + '\\\"\,'
757     pass # END if
758     pass # END while (iterate over files in the block)
759     pass # END while (iterate over blocks in the dataset)
760     self.ncjobs = self.total_number_of_jobs = jobCount
761     if (eventsRemaining > 0 and jobCount < totalNumberOfJobs ):
762     common.logger.message("eventsRemaining "+str(eventsRemaining))
763     common.logger.message("jobCount "+str(jobCount))
764     common.logger.message(" totalNumberOfJobs "+str(totalNumberOfJobs))
765     common.logger.message("Could not run on all requested events because some blocks not hosted at allowed sites.")
766     common.logger.message(str(jobCount)+" job(s) can run on "+str(totalEventCount)+" events.\n")
767    
768     # screen output
769     screenOutput = "List of jobs and available destination sites:\n\n"
770    
771     #AF
772 ewv 1.250 #AF skip check on block with no sites
773     #AF
774 afanfani 1.237 self.list_of_args = list_of_lists
775    
776     return
777    
778    
779    
780 slacapra 1.21 def jobSplittingNoInput(self):
781 slacapra 1.9 """
782     Perform job splitting based on number of event per job
783     """
784     common.logger.debug(5,'Splitting per events')
785 fanzago 1.130
786 ewv 1.131 if (self.selectEventsPerJob):
787 fanzago 1.130 common.logger.message('Required '+str(self.eventsPerJob)+' events per job ')
788     if (self.selectNumberOfJobs):
789     common.logger.message('Required '+str(self.theNumberOfJobs)+' jobs in total ')
790     if (self.selectTotalNumberEvents):
791     common.logger.message('Required '+str(self.total_number_of_events)+' events in total ')
792 slacapra 1.9
793 slacapra 1.10 if (self.total_number_of_events < 0):
794     msg='Cannot split jobs per Events with "-1" as total number of events'
795     raise CrabException(msg)
796    
797 slacapra 1.22 if (self.selectEventsPerJob):
798 spiga 1.65 if (self.selectTotalNumberEvents):
799     self.total_number_of_jobs = int(self.total_number_of_events/self.eventsPerJob)
800 ewv 1.131 elif(self.selectNumberOfJobs) :
801 spiga 1.65 self.total_number_of_jobs =self.theNumberOfJobs
802 ewv 1.131 self.total_number_of_events =int(self.theNumberOfJobs*self.eventsPerJob)
803 spiga 1.65
804 slacapra 1.22 elif (self.selectNumberOfJobs) :
805     self.total_number_of_jobs = self.theNumberOfJobs
806     self.eventsPerJob = int(self.total_number_of_events/self.total_number_of_jobs)
807 ewv 1.131
808 slacapra 1.9 common.logger.debug(5,'N jobs '+str(self.total_number_of_jobs))
809    
810     # is there any remainder?
811     check = int(self.total_number_of_events) - (int(self.total_number_of_jobs)*self.eventsPerJob)
812    
813     common.logger.debug(5,'Check '+str(check))
814    
815 gutsche 1.35 common.logger.message(str(self.total_number_of_jobs)+' jobs can be created, each for '+str(self.eventsPerJob)+' for a total of '+str(self.total_number_of_jobs*self.eventsPerJob)+' events')
816 slacapra 1.9 if check > 0:
817 gutsche 1.35 common.logger.message('Warning: asked '+str(self.total_number_of_events)+' but can do only '+str(int(self.total_number_of_jobs)*self.eventsPerJob))
818 slacapra 1.9
819 slacapra 1.10 # argument is seed number.$i
820 slacapra 1.9 self.list_of_args = []
821     for i in range(self.total_number_of_jobs):
822 gutsche 1.35 ## Since there is no input, any site is good
823 ewv 1.131 self.jobDestination.append([""]) #must be empty to write correctly the xml
824 slacapra 1.90 args=[]
825 spiga 1.57 if (self.firstRun):
826 slacapra 1.138 ## pythia first run
827 slacapra 1.90 args.append(str(self.firstRun)+str(i))
828     self.list_of_args.append(args)
829 ewv 1.131
830 gutsche 1.3 return
831    
832 spiga 1.42
833 spiga 1.187 def jobSplittingForScript(self):
834 spiga 1.42 """
835     Perform job splitting based on number of job
836     """
837     common.logger.debug(5,'Splitting per job')
838     common.logger.message('Required '+str(self.theNumberOfJobs)+' jobs in total ')
839    
840     self.total_number_of_jobs = self.theNumberOfJobs
841    
842     common.logger.debug(5,'N jobs '+str(self.total_number_of_jobs))
843    
844     common.logger.message(str(self.total_number_of_jobs)+' jobs can be created')
845    
846     # argument is seed number.$i
847     self.list_of_args = []
848     for i in range(self.total_number_of_jobs):
849     self.jobDestination.append([""])
850     self.list_of_args.append([str(i)])
851     return
852    
853 spiga 1.208 def split(self, jobParams,firstJobID):
854 ewv 1.131
855 gutsche 1.3 njobs = self.total_number_of_jobs
856 slacapra 1.9 arglist = self.list_of_args
857 gutsche 1.3 # create the empty structure
858     for i in range(njobs):
859     jobParams.append("")
860 ewv 1.131
861 spiga 1.165 listID=[]
862     listField=[]
863 spiga 1.208 for id in range(njobs):
864     job = id + int(firstJobID)
865     jobParams[id] = arglist[id]
866 spiga 1.167 listID.append(job+1)
867 spiga 1.162 job_ToSave ={}
868 spiga 1.169 concString = ' '
869 spiga 1.165 argu=''
870 spiga 1.208 if len(jobParams[id]):
871     argu += concString.join(jobParams[id] )
872 spiga 1.187 job_ToSave['arguments']= str(job+1)+' '+argu
873 spiga 1.208 job_ToSave['dlsDestination']= self.jobDestination[id]
874 spiga 1.165 listField.append(job_ToSave)
875 spiga 1.169 msg="Job "+str(job)+" Arguments: "+str(job+1)+" "+argu+"\n" \
876 spiga 1.208 +" Destination: "+str(self.jobDestination[id])
877 spiga 1.165 common.logger.debug(5,msg)
878 spiga 1.187 common._db.updateJob_(listID,listField)
879 spiga 1.181 self.argsList = (len(jobParams[0])+1)
880 gutsche 1.3
881     return
882 ewv 1.131
883 gutsche 1.3 def numberOfJobs(self):
884     return self.total_number_of_jobs
885    
886 slacapra 1.1 def getTarBall(self, exe):
887     """
888     Return the TarBall with lib and exe
889     """
890 slacapra 1.242 self.tgzNameWithPath = common.work_space.pathForTgz()+self.tgz_name
891 slacapra 1.1 if os.path.exists(self.tgzNameWithPath):
892     return self.tgzNameWithPath
893    
894     # Prepare a tar gzipped file with user binaries.
895     self.buildTar_(exe)
896    
897     return string.strip(self.tgzNameWithPath)
898    
899     def buildTar_(self, executable):
900    
901     # First of all declare the user Scram area
902     swArea = self.scram.getSWArea_()
903     swReleaseTop = self.scram.getReleaseTop_()
904 ewv 1.131
905 slacapra 1.1 ## check if working area is release top
906     if swReleaseTop == '' or swArea == swReleaseTop:
907 afanfani 1.172 common.logger.debug(3,"swArea = "+swArea+" swReleaseTop ="+swReleaseTop)
908 slacapra 1.1 return
909    
910 slacapra 1.61 import tarfile
911     try: # create tar ball
912     tar = tarfile.open(self.tgzNameWithPath, "w:gz")
913     ## First find the executable
914 slacapra 1.86 if (self.executable != ''):
915 slacapra 1.61 exeWithPath = self.scram.findFile_(executable)
916     if ( not exeWithPath ):
917     raise CrabException('User executable '+executable+' not found')
918 ewv 1.131
919 slacapra 1.61 ## then check if it's private or not
920     if exeWithPath.find(swReleaseTop) == -1:
921     # the exe is private, so we must ship
922     common.logger.debug(5,"Exe "+exeWithPath+" to be tarred")
923     path = swArea+'/'
924 corvo 1.85 # distinguish case when script is in user project area or given by full path somewhere else
925     if exeWithPath.find(path) >= 0 :
926     exe = string.replace(exeWithPath, path,'')
927 slacapra 1.129 tar.add(path+exe,exe)
928 corvo 1.85 else :
929     tar.add(exeWithPath,os.path.basename(executable))
930 slacapra 1.61 pass
931     else:
932     # the exe is from release, we'll find it on WN
933     pass
934 ewv 1.131
935 slacapra 1.61 ## Now get the libraries: only those in local working area
936     libDir = 'lib'
937     lib = swArea+'/' +libDir
938     common.logger.debug(5,"lib "+lib+" to be tarred")
939     if os.path.exists(lib):
940     tar.add(lib,libDir)
941 ewv 1.131
942 slacapra 1.61 ## Now check if module dir is present
943     moduleDir = 'module'
944     module = swArea + '/' + moduleDir
945     if os.path.isdir(module):
946     tar.add(module,moduleDir)
947    
948     ## Now check if any data dir(s) is present
949 spiga 1.179 self.dataExist = False
950 slacapra 1.212 todo_list = [(i, i) for i in os.listdir(swArea+"/src")]
951 slacapra 1.206 while len(todo_list):
952     entry, name = todo_list.pop()
953 slacapra 1.211 if name.startswith('crab_0_') or name.startswith('.') or name == 'CVS':
954 slacapra 1.206 continue
955 slacapra 1.212 if os.path.isdir(swArea+"/src/"+entry):
956 slacapra 1.206 entryPath = entry + '/'
957 slacapra 1.212 todo_list += [(entryPath + i, i) for i in os.listdir(swArea+"/src/"+entry)]
958 slacapra 1.206 if name == 'data':
959     self.dataExist=True
960     common.logger.debug(5,"data "+entry+" to be tarred")
961 slacapra 1.212 tar.add(swArea+"/src/"+entry,"src/"+entry)
962 slacapra 1.206 pass
963     pass
964 ewv 1.182
965 spiga 1.179 ### CMSSW ParameterSet
966     if not self.pset is None:
967     cfg_file = common.work_space.jobDir()+self.configFilename()
968 ewv 1.182 tar.add(cfg_file,self.configFilename())
969 spiga 1.179 common.logger.debug(5,"File added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
970 slacapra 1.61
971 fanzago 1.93
972 fanzago 1.152 ## Add ProdCommon dir to tar
973 slacapra 1.211 prodcommonDir = './'
974     prodcommonPath = os.environ['CRABDIR'] + '/' + 'external/'
975 spiga 1.244 neededStuff = ['ProdCommon/__init__.py','ProdCommon/FwkJobRep', 'ProdCommon/CMSConfigTools', \
976     'ProdCommon/Core', 'ProdCommon/MCPayloads', 'IMProv', 'ProdCommon/Storage']
977 slacapra 1.214 for file in neededStuff:
978     tar.add(prodcommonPath+file,prodcommonDir+file)
979 spiga 1.179 common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
980    
981     ##### ML stuff
982     ML_file_list=['report.py', 'DashboardAPI.py', 'Logger.py', 'ProcInfo.py', 'apmon.py']
983     path=os.environ['CRABDIR'] + '/python/'
984     for file in ML_file_list:
985     tar.add(path+file,file)
986     common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
987    
988     ##### Utils
989 spiga 1.238 Utils_file_list=['parseCrabFjr.py','writeCfg.py', 'fillCrabFjr.py','cmscp.py']
990 spiga 1.179 for file in Utils_file_list:
991     tar.add(path+file,file)
992     common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
993 ewv 1.131
994 ewv 1.182 ##### AdditionalFiles
995 slacapra 1.253 tar.dereference=True
996 spiga 1.179 for file in self.additional_inbox_files:
997     tar.add(file,string.split(file,'/')[-1])
998 slacapra 1.253 tar.dereference=False
999 slacapra 1.61 common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
1000 ewv 1.182
1001 slacapra 1.61 tar.close()
1002 mcinquil 1.241 except IOError, exc:
1003     common.logger.write(str(exc))
1004 slacapra 1.220 raise CrabException('Could not create tar-ball '+self.tgzNameWithPath)
1005 mcinquil 1.241 except tarfile.TarError, exc:
1006     common.logger.write(str(exc))
1007 slacapra 1.206 raise CrabException('Could not create tar-ball '+self.tgzNameWithPath)
1008 gutsche 1.72
1009     ## check for tarball size
1010     tarballinfo = os.stat(self.tgzNameWithPath)
1011     if ( tarballinfo.st_size > self.MaxTarBallSize*1024*1024 ) :
1012 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) \
1013 ewv 1.250 +'MB input sandbox limit \n'
1014 spiga 1.238 msg += ' and not supported by the direct GRID submission system.\n'
1015     msg += ' Please use the CRAB server mode by setting server_name=<NAME> in section [CRAB] of your crab.cfg.\n'
1016     msg += ' For further infos please see https://twiki.cern.ch/twiki/bin/view/CMS/CrabServer#CRABSERVER_for_Users'
1017     raise CrabException(msg)
1018 gutsche 1.72
1019 slacapra 1.61 ## create tar-ball with ML stuff
1020 slacapra 1.97
1021 spiga 1.165 def wsSetupEnvironment(self, nj=0):
1022 slacapra 1.1 """
1023     Returns part of a job script which prepares
1024     the execution environment for the job 'nj'.
1025     """
1026 ewv 1.184 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
1027     psetName = 'pset.py'
1028     else:
1029     psetName = 'pset.cfg'
1030 slacapra 1.1 # Prepare JobType-independent part
1031 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupEnvironment\n'
1032 fanzago 1.133 txt += 'echo ">>> setup environment"\n'
1033 ewv 1.131 txt += 'if [ $middleware == LCG ]; then \n'
1034 gutsche 1.3 txt += self.wsSetupCMSLCGEnvironment_()
1035     txt += 'elif [ $middleware == OSG ]; then\n'
1036 gutsche 1.43 txt += ' WORKING_DIR=`/bin/mktemp -d $OSG_WN_TMP/cms_XXXXXXXXXXXX`\n'
1037 ewv 1.132 txt += ' if [ ! $? == 0 ] ;then\n'
1038 fanzago 1.161 txt += ' echo "ERROR ==> OSG $WORKING_DIR could not be created on WN `hostname`"\n'
1039     txt += ' job_exit_code=10016\n'
1040     txt += ' func_exit\n'
1041 gutsche 1.3 txt += ' fi\n'
1042 fanzago 1.133 txt += ' echo ">>> Created working directory: $WORKING_DIR"\n'
1043 gutsche 1.3 txt += '\n'
1044     txt += ' echo "Change to working directory: $WORKING_DIR"\n'
1045     txt += ' cd $WORKING_DIR\n'
1046 fanzago 1.133 txt += ' echo ">>> current directory (WORKING_DIR): $WORKING_DIR"\n'
1047 ewv 1.131 txt += self.wsSetupCMSOSGEnvironment_()
1048 gutsche 1.3 txt += 'fi\n'
1049 slacapra 1.1
1050     # Prepare JobType-specific part
1051     scram = self.scram.commandName()
1052     txt += '\n\n'
1053 fanzago 1.133 txt += 'echo ">>> specific cmssw setup environment:"\n'
1054     txt += 'echo "CMSSW_VERSION = '+self.version+'"\n'
1055 slacapra 1.1 txt += scram+' project CMSSW '+self.version+'\n'
1056     txt += 'status=$?\n'
1057     txt += 'if [ $status != 0 ] ; then\n'
1058 fanzago 1.161 txt += ' echo "ERROR ==> CMSSW '+self.version+' not found on `hostname`" \n'
1059     txt += ' job_exit_code=10034\n'
1060 fanzago 1.163 txt += ' func_exit\n'
1061 slacapra 1.1 txt += 'fi \n'
1062     txt += 'cd '+self.version+'\n'
1063 fanzago 1.99 txt += 'SOFTWARE_DIR=`pwd`\n'
1064 fanzago 1.133 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
1065 slacapra 1.1 txt += 'eval `'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME`\n'
1066 fanzago 1.180 txt += 'if [ $? != 0 ] ; then\n'
1067     txt += ' echo "ERROR ==> Problem with the command: "\n'
1068     txt += ' echo "eval \`'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME \` at `hostname`"\n'
1069     txt += ' job_exit_code=10034\n'
1070     txt += ' func_exit\n'
1071     txt += 'fi \n'
1072 slacapra 1.1 # Handle the arguments:
1073     txt += "\n"
1074 gutsche 1.7 txt += "## number of arguments (first argument always jobnumber)\n"
1075 slacapra 1.1 txt += "\n"
1076 spiga 1.165 txt += "if [ $nargs -lt "+str(self.argsList)+" ]\n"
1077 slacapra 1.1 txt += "then\n"
1078 fanzago 1.161 txt += " echo 'ERROR ==> Too few arguments' +$nargs+ \n"
1079     txt += ' job_exit_code=50113\n'
1080     txt += " func_exit\n"
1081 slacapra 1.1 txt += "fi\n"
1082     txt += "\n"
1083    
1084     # Prepare job-specific part
1085     job = common.job_list[nj]
1086 ewv 1.131 if (self.datasetPath):
1087 spiga 1.238 self.primaryDataset = self.datasetPath.split("/")[1]
1088     DataTier = self.datasetPath.split("/")[2]
1089 fanzago 1.93 txt += '\n'
1090     txt += 'DatasetPath='+self.datasetPath+'\n'
1091    
1092 spiga 1.238 txt += 'PrimaryDataset='+self.primaryDataset +'\n'
1093     txt += 'DataTier='+DataTier+'\n'
1094 fanzago 1.96 txt += 'ApplicationFamily=cmsRun\n'
1095 fanzago 1.93
1096     else:
1097 ewv 1.250 self.primaryDataset = 'null'
1098 fanzago 1.93 txt += 'DatasetPath=MCDataTier\n'
1099     txt += 'PrimaryDataset=null\n'
1100     txt += 'DataTier=null\n'
1101     txt += 'ApplicationFamily=MCDataTier\n'
1102 ewv 1.170 if self.pset != None:
1103 spiga 1.42 pset = os.path.basename(job.configFilename())
1104     txt += '\n'
1105 spiga 1.95 txt += 'cp $RUNTIME_AREA/'+pset+' .\n'
1106 spiga 1.42 if (self.datasetPath): # standard job
1107 ewv 1.160 txt += 'InputFiles=${args[1]}; export InputFiles\n'
1108 ewv 1.226 if (self.useParent):
1109 spiga 1.204 txt += 'ParentFiles=${args[2]}; export ParentFiles\n'
1110     txt += 'MaxEvents=${args[3]}; export MaxEvents\n'
1111     txt += 'SkipEvents=${args[4]}; export SkipEvents\n'
1112     else:
1113     txt += 'MaxEvents=${args[2]}; export MaxEvents\n'
1114     txt += 'SkipEvents=${args[3]}; export SkipEvents\n'
1115 spiga 1.42 txt += 'echo "Inputfiles:<$InputFiles>"\n'
1116 spiga 1.204 if (self.useParent): txt += 'echo "ParentFiles:<$ParentFiles>"\n'
1117 spiga 1.42 txt += 'echo "MaxEvents:<$MaxEvents>"\n'
1118     txt += 'echo "SkipEvents:<$SkipEvents>"\n'
1119     else: # pythia like job
1120 ewv 1.160 txt += 'PreserveSeeds=' + ','.join(self.preserveSeeds) + '; export PreserveSeeds\n'
1121     txt += 'IncrementSeeds=' + ','.join(self.incrementSeeds) + '; export IncrementSeeds\n'
1122     txt += 'echo "PreserveSeeds: <$PreserveSeeds>"\n'
1123     txt += 'echo "IncrementSeeds:<$IncrementSeeds>"\n'
1124 slacapra 1.90 if (self.firstRun):
1125 ewv 1.160 txt += 'FirstRun=${args[1]}; export FirstRun\n'
1126 spiga 1.57 txt += 'echo "FirstRun: <$FirstRun>"\n'
1127 slacapra 1.90
1128 ewv 1.184 txt += 'mv -f ' + pset + ' ' + psetName + '\n'
1129 slacapra 1.1
1130    
1131 fanzago 1.163 if self.pset != None:
1132 ewv 1.184 # FUTURE: Can simply for 2_1_x and higher
1133 spiga 1.42 txt += '\n'
1134 spiga 1.197 if self.debug_wrapper==True:
1135 spiga 1.188 txt += 'echo "***** cat ' + psetName + ' *********"\n'
1136     txt += 'cat ' + psetName + '\n'
1137     txt += 'echo "****** end ' + psetName + ' ********"\n'
1138     txt += '\n'
1139 ewv 1.226 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
1140     txt += 'PSETHASH=`edmConfigHash ' + psetName + '` \n'
1141     else:
1142     txt += 'PSETHASH=`edmConfigHash < ' + psetName + '` \n'
1143 fanzago 1.94 txt += 'echo "PSETHASH = $PSETHASH" \n'
1144 fanzago 1.93 txt += '\n'
1145 gutsche 1.3 return txt
1146 slacapra 1.176
1147 fanzago 1.166 def wsUntarSoftware(self, nj=0):
1148 gutsche 1.3 """
1149     Put in the script the commands to build an executable
1150     or a library.
1151     """
1152    
1153 fanzago 1.166 txt = '\n#Written by cms_cmssw::wsUntarSoftware\n'
1154 gutsche 1.3
1155     if os.path.isfile(self.tgzNameWithPath):
1156 fanzago 1.133 txt += 'echo ">>> tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+' :" \n'
1157 slacapra 1.255 txt += 'tar xzf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
1158 spiga 1.199 if self.debug_wrapper:
1159 slacapra 1.255 txt += 'tar tzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
1160 spiga 1.199 txt += 'ls -Al \n'
1161 gutsche 1.3 txt += 'untar_status=$? \n'
1162     txt += 'if [ $untar_status -ne 0 ]; then \n'
1163 fanzago 1.161 txt += ' echo "ERROR ==> Untarring .tgz file failed"\n'
1164     txt += ' job_exit_code=$untar_status\n'
1165     txt += ' func_exit\n'
1166 gutsche 1.3 txt += 'else \n'
1167     txt += ' echo "Successful untar" \n'
1168     txt += 'fi \n'
1169 gutsche 1.50 txt += '\n'
1170 slacapra 1.211 txt += 'echo ">>> Include $RUNTIME_AREA in PYTHONPATH:"\n'
1171 gutsche 1.50 txt += 'if [ -z "$PYTHONPATH" ]; then\n'
1172 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/\n'
1173 gutsche 1.50 txt += 'else\n'
1174 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/:${PYTHONPATH}\n'
1175 fanzago 1.93 txt += 'echo "PYTHONPATH=$PYTHONPATH"\n'
1176 gutsche 1.50 txt += 'fi\n'
1177     txt += '\n'
1178    
1179 gutsche 1.3 pass
1180 ewv 1.131
1181 slacapra 1.1 return txt
1182 ewv 1.170
1183 fanzago 1.166 def wsBuildExe(self, nj=0):
1184     """
1185     Put in the script the commands to build an executable
1186     or a library.
1187     """
1188    
1189     txt = '\n#Written by cms_cmssw::wsBuildExe\n'
1190     txt += 'echo ">>> moving CMSSW software directories in `pwd`" \n'
1191    
1192 ewv 1.170 txt += 'rm -r lib/ module/ \n'
1193     txt += 'mv $RUNTIME_AREA/lib/ . \n'
1194     txt += 'mv $RUNTIME_AREA/module/ . \n'
1195 spiga 1.186 if self.dataExist == True:
1196     txt += 'rm -r src/ \n'
1197     txt += 'mv $RUNTIME_AREA/src/ . \n'
1198 ewv 1.182 if len(self.additional_inbox_files)>0:
1199 spiga 1.179 for file in self.additional_inbox_files:
1200 spiga 1.191 txt += 'mv $RUNTIME_AREA/'+os.path.basename(file)+' . \n'
1201 slacapra 1.214 # txt += 'mv $RUNTIME_AREA/ProdCommon/ . \n'
1202     # txt += 'mv $RUNTIME_AREA/IMProv/ . \n'
1203 ewv 1.170
1204 slacapra 1.211 txt += 'echo ">>> Include $RUNTIME_AREA in PYTHONPATH:"\n'
1205 fanzago 1.166 txt += 'if [ -z "$PYTHONPATH" ]; then\n'
1206 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/\n'
1207 fanzago 1.166 txt += 'else\n'
1208 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/:${PYTHONPATH}\n'
1209 fanzago 1.166 txt += 'echo "PYTHONPATH=$PYTHONPATH"\n'
1210     txt += 'fi\n'
1211     txt += '\n'
1212    
1213     return txt
1214 slacapra 1.1
1215 ewv 1.131
1216 slacapra 1.1 def executableName(self):
1217 ewv 1.192 if self.scriptExe:
1218 spiga 1.42 return "sh "
1219     else:
1220     return self.executable
1221 slacapra 1.1
1222     def executableArgs(self):
1223 ewv 1.160 # FUTURE: This function tests the CMSSW version. Can be simplified as we drop support for old versions
1224 slacapra 1.70 if self.scriptExe:#CarlosDaniele
1225 spiga 1.42 return self.scriptExe + " $NJob"
1226 fanzago 1.115 else:
1227 ewv 1.160 ex_args = ""
1228 ewv 1.171 # FUTURE: This tests the CMSSW version. Can remove code as versions deprecated
1229 ewv 1.160 # Framework job report
1230 ewv 1.184 if (self.CMSSW_major >= 1 and self.CMSSW_minor >= 5) or (self.CMSSW_major >= 2):
1231 fanzago 1.166 ex_args += " -j $RUNTIME_AREA/crab_fjr_$NJob.xml"
1232 ewv 1.184 # Type of config file
1233     if self.CMSSW_major >= 2 :
1234 ewv 1.171 ex_args += " -p pset.py"
1235 fanzago 1.115 else:
1236 ewv 1.160 ex_args += " -p pset.cfg"
1237     return ex_args
1238 slacapra 1.1
1239     def inputSandbox(self, nj):
1240     """
1241     Returns a list of filenames to be put in JDL input sandbox.
1242     """
1243     inp_box = []
1244     if os.path.isfile(self.tgzNameWithPath):
1245     inp_box.append(self.tgzNameWithPath)
1246 spiga 1.243 inp_box.append(common.work_space.jobDir() + self.scriptName)
1247 slacapra 1.1 return inp_box
1248    
1249     def outputSandbox(self, nj):
1250     """
1251     Returns a list of filenames to be put in JDL output sandbox.
1252     """
1253     out_box = []
1254    
1255     ## User Declared output files
1256 slacapra 1.54 for out in (self.output_file+self.output_file_sandbox):
1257 ewv 1.131 n_out = nj + 1
1258 slacapra 1.207 out_box.append(numberFile(out,str(n_out)))
1259 slacapra 1.1 return out_box
1260    
1261    
1262     def wsRenameOutput(self, nj):
1263     """
1264     Returns part of a job script which renames the produced files.
1265     """
1266    
1267 ewv 1.160 txt = '\n#Written by cms_cmssw::wsRenameOutput\n'
1268 fanzago 1.148 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
1269     txt += 'echo ">>> current directory content:"\n'
1270 ewv 1.226 if self.debug_wrapper:
1271 spiga 1.199 txt += 'ls -Al\n'
1272 fanzago 1.145 txt += '\n'
1273 slacapra 1.54
1274 fanzago 1.128 for fileWithSuffix in (self.output_file):
1275 slacapra 1.207 output_file_num = numberFile(fileWithSuffix, '$NJob')
1276 slacapra 1.1 txt += '\n'
1277 gutsche 1.7 txt += '# check output file\n'
1278 slacapra 1.106 txt += 'if [ -e ./'+fileWithSuffix+' ] ; then\n'
1279 ewv 1.147 if (self.copy_data == 1): # For OSG nodes, file is in $WORKING_DIR, should not be moved to $RUNTIME_AREA
1280     txt += ' mv '+fileWithSuffix+' '+output_file_num+'\n'
1281 spiga 1.209 txt += ' ln -s `pwd`/'+output_file_num+' $RUNTIME_AREA/'+fileWithSuffix+'\n'
1282 ewv 1.147 else:
1283     txt += ' mv '+fileWithSuffix+' $RUNTIME_AREA/'+output_file_num+'\n'
1284     txt += ' ln -s $RUNTIME_AREA/'+output_file_num+' $RUNTIME_AREA/'+fileWithSuffix+'\n'
1285 slacapra 1.106 txt += 'else\n'
1286 fanzago 1.161 txt += ' job_exit_code=60302\n'
1287     txt += ' echo "WARNING: Output file '+fileWithSuffix+' not found"\n'
1288 ewv 1.156 if common.scheduler.name().upper() == 'CONDOR_G':
1289 gutsche 1.7 txt += ' if [ $middleware == OSG ]; then \n'
1290     txt += ' echo "prepare dummy output file"\n'
1291     txt += ' echo "Processing of job output failed" > $RUNTIME_AREA/'+output_file_num+'\n'
1292     txt += ' fi \n'
1293 slacapra 1.1 txt += 'fi\n'
1294 slacapra 1.105 file_list = []
1295     for fileWithSuffix in (self.output_file):
1296 spiga 1.246 file_list.append(numberFile('$SOFTWARE_DIR/'+fileWithSuffix, '$NJob'))
1297 ewv 1.131
1298 spiga 1.245 txt += 'file_list="'+string.join(file_list,',')+'"\n'
1299 fanzago 1.149 txt += '\n'
1300 fanzago 1.148 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
1301     txt += 'echo ">>> current directory content:"\n'
1302 ewv 1.226 if self.debug_wrapper:
1303 spiga 1.199 txt += 'ls -Al\n'
1304 fanzago 1.148 txt += '\n'
1305 gutsche 1.7 txt += 'cd $RUNTIME_AREA\n'
1306 fanzago 1.133 txt += 'echo ">>> current directory (RUNTIME_AREA): $RUNTIME_AREA"\n'
1307 slacapra 1.1 return txt
1308    
1309 slacapra 1.63 def getRequirements(self, nj=[]):
1310 slacapra 1.1 """
1311 ewv 1.131 return job requirements to add to jdl files
1312 slacapra 1.1 """
1313     req = ''
1314 slacapra 1.47 if self.version:
1315 slacapra 1.10 req='Member("VO-cms-' + \
1316 slacapra 1.47 self.version + \
1317 slacapra 1.10 '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
1318 ewv 1.192 if self.executable_arch:
1319 gutsche 1.107 req+=' && Member("VO-cms-' + \
1320 slacapra 1.105 self.executable_arch + \
1321     '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
1322 gutsche 1.35
1323     req = req + ' && (other.GlueHostNetworkAdapterOutboundIP)'
1324 afanfani 1.229 if ( common.scheduler.name() == "glitecoll" ) or ( common.scheduler.name() == "glite"):
1325 afanfani 1.158 req += ' && other.GlueCEStateStatus == "Production" '
1326 gutsche 1.35
1327 slacapra 1.1 return req
1328 gutsche 1.3
1329     def configFilename(self):
1330     """ return the config filename """
1331 ewv 1.182 # FUTURE: Can remove cfg mode for CMSSW >= 2_1_x
1332 ewv 1.184 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
1333 ewv 1.182 return self.name()+'.py'
1334     else:
1335     return self.name()+'.cfg'
1336 gutsche 1.3
1337     def wsSetupCMSOSGEnvironment_(self):
1338     """
1339     Returns part of a job script which is prepares
1340     the execution environment and which is common for all CMS jobs.
1341     """
1342 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupCMSOSGEnvironment_\n'
1343     txt += ' echo ">>> setup CMS OSG environment:"\n'
1344 fanzago 1.133 txt += ' echo "set SCRAM ARCH to ' + self.executable_arch + '"\n'
1345     txt += ' export SCRAM_ARCH='+self.executable_arch+'\n'
1346 fanzago 1.136 txt += ' echo "SCRAM_ARCH = $SCRAM_ARCH"\n'
1347 ewv 1.135 txt += ' if [ -f $OSG_APP/cmssoft/cms/cmsset_default.sh ] ;then\n'
1348 mkirn 1.40 txt += ' # Use $OSG_APP/cmssoft/cms/cmsset_default.sh to setup cms software\n'
1349 fanzago 1.133 txt += ' source $OSG_APP/cmssoft/cms/cmsset_default.sh '+self.version+'\n'
1350     txt += ' else\n'
1351 fanzago 1.161 txt += ' echo "ERROR ==> $OSG_APP/cmssoft/cms/cmsset_default.sh file not found"\n'
1352     txt += ' job_exit_code=10020\n'
1353     txt += ' func_exit\n'
1354 fanzago 1.133 txt += ' fi\n'
1355 gutsche 1.3 txt += '\n'
1356 fanzago 1.161 txt += ' echo "==> setup cms environment ok"\n'
1357 fanzago 1.136 txt += ' echo "SCRAM_ARCH = $SCRAM_ARCH"\n'
1358 gutsche 1.3
1359     return txt
1360 ewv 1.131
1361 gutsche 1.3 def wsSetupCMSLCGEnvironment_(self):
1362     """
1363     Returns part of a job script which is prepares
1364     the execution environment and which is common for all CMS jobs.
1365     """
1366 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupCMSLCGEnvironment_\n'
1367     txt += ' echo ">>> setup CMS LCG environment:"\n'
1368 fanzago 1.133 txt += ' echo "set SCRAM ARCH and BUILD_ARCH to ' + self.executable_arch + ' ###"\n'
1369     txt += ' export SCRAM_ARCH='+self.executable_arch+'\n'
1370     txt += ' export BUILD_ARCH='+self.executable_arch+'\n'
1371     txt += ' if [ ! $VO_CMS_SW_DIR ] ;then\n'
1372 fanzago 1.161 txt += ' echo "ERROR ==> CMS software dir not found on WN `hostname`"\n'
1373     txt += ' job_exit_code=10031\n'
1374     txt += ' func_exit\n'
1375 fanzago 1.133 txt += ' else\n'
1376     txt += ' echo "Sourcing environment... "\n'
1377     txt += ' if [ ! -s $VO_CMS_SW_DIR/cmsset_default.sh ] ;then\n'
1378 fanzago 1.161 txt += ' echo "ERROR ==> cmsset_default.sh file not found into dir $VO_CMS_SW_DIR"\n'
1379     txt += ' job_exit_code=10020\n'
1380     txt += ' func_exit\n'
1381 fanzago 1.133 txt += ' fi\n'
1382     txt += ' echo "sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1383     txt += ' source $VO_CMS_SW_DIR/cmsset_default.sh\n'
1384     txt += ' result=$?\n'
1385     txt += ' if [ $result -ne 0 ]; then\n'
1386 fanzago 1.161 txt += ' echo "ERROR ==> problem sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1387     txt += ' job_exit_code=10032\n'
1388     txt += ' func_exit\n'
1389 fanzago 1.133 txt += ' fi\n'
1390     txt += ' fi\n'
1391     txt += ' \n'
1392 fanzago 1.161 txt += ' echo "==> setup cms environment ok"\n'
1393 gutsche 1.3 return txt
1394 gutsche 1.5
1395 spiga 1.238 def wsModifyReport(self, nj):
1396 fanzago 1.93 """
1397 ewv 1.131 insert the part of the script that modifies the FrameworkJob Report
1398 fanzago 1.93 """
1399 spiga 1.238 txt = '\n#Written by cms_cmssw::wsModifyReport\n'
1400 slacapra 1.176 publish_data = int(self.cfg_params.get('USER.publish_data',0))
1401 ewv 1.131 if (publish_data == 1):
1402 ewv 1.250
1403 fanzago 1.248 processedDataset = self.cfg_params['USER.publish_data_name']
1404 spiga 1.238
1405     txt += 'if [ $StageOutExitStatus -eq 0 ]; then\n'
1406 fanzago 1.248 txt += ' FOR_LFN=$LFNBaseName\n'
1407 fanzago 1.175 txt += 'else\n'
1408     txt += ' FOR_LFN=/copy_problems/ \n'
1409     txt += ' SE=""\n'
1410     txt += ' SE_PATH=""\n'
1411     txt += 'fi\n'
1412 ewv 1.182
1413 fanzago 1.175 txt += 'echo ">>> Modify Job Report:" \n'
1414 fanzago 1.217 txt += 'chmod a+x $RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py\n'
1415 fanzago 1.248 txt += 'ProcessedDataset='+processedDataset+'\n'
1416     #txt += 'ProcessedDataset=$procDataset \n'
1417 fanzago 1.175 txt += 'echo "ProcessedDataset = $ProcessedDataset"\n'
1418     txt += 'echo "SE = $SE"\n'
1419     txt += 'echo "SE_PATH = $SE_PATH"\n'
1420     txt += 'echo "FOR_LFN = $FOR_LFN" \n'
1421     txt += 'echo "CMSSW_VERSION = $CMSSW_VERSION"\n\n'
1422 spiga 1.238 args = '$RUNTIME_AREA/crab_fjr_$NJob.xml $NJob $FOR_LFN $PrimaryDataset $DataTier ' \
1423 fanzago 1.248 '$USER-$ProcessedDataset-$PSETHASH $ApplicationFamily '+ \
1424 fanzago 1.247 ' $executable $CMSSW_VERSION $PSETHASH $SE $SE_PATH'
1425     txt += 'echo "$RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py '+str(args)+'"\n'
1426     txt += '$RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py '+str(args)+'\n'
1427 fanzago 1.175 txt += 'modifyReport_result=$?\n'
1428     txt += 'if [ $modifyReport_result -ne 0 ]; then\n'
1429     txt += ' modifyReport_result=70500\n'
1430     txt += ' job_exit_code=$modifyReport_result\n'
1431     txt += ' echo "ModifyReportResult=$modifyReport_result" | tee -a $RUNTIME_AREA/$repo\n'
1432     txt += ' echo "WARNING: Problem with ModifyJobReport"\n'
1433     txt += 'else\n'
1434     txt += ' mv NewFrameworkJobReport.xml $RUNTIME_AREA/crab_fjr_$NJob.xml\n'
1435 spiga 1.103 txt += 'fi\n'
1436 fanzago 1.93 return txt
1437 fanzago 1.99
1438 ewv 1.192 def wsParseFJR(self):
1439 spiga 1.189 """
1440 ewv 1.192 Parse the FrameworkJobReport to obtain useful infos
1441 spiga 1.189 """
1442     txt = '\n#Written by cms_cmssw::wsParseFJR\n'
1443     txt += 'echo ">>> Parse FrameworkJobReport crab_fjr.xml"\n'
1444     txt += 'if [ -s $RUNTIME_AREA/crab_fjr_$NJob.xml ]; then\n'
1445     txt += ' if [ -s $RUNTIME_AREA/parseCrabFjr.py ]; then\n'
1446 spiga 1.197 txt += ' cmd_out=`python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --dashboard $MonitorID,$MonitorJobID '+self.debugWrap+'`\n'
1447     if self.debug_wrapper :
1448     txt += ' echo "Result of parsing the FrameworkJobReport crab_fjr.xml: $cmd_out"\n'
1449     txt += ' executable_exit_status=`python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --exitcode`\n'
1450 spiga 1.189 txt += ' if [ $executable_exit_status -eq 50115 ];then\n'
1451     txt += ' echo ">>> crab_fjr.xml contents: "\n'
1452 spiga 1.222 txt += ' cat $RUNTIME_AREA/crab_fjr_$NJob.xml\n'
1453 spiga 1.189 txt += ' echo "Wrong FrameworkJobReport --> does not contain useful info. ExitStatus: $executable_exit_status"\n'
1454 spiga 1.197 txt += ' elif [ $executable_exit_status -eq -999 ];then\n'
1455     txt += ' echo "ExitStatus from FrameworkJobReport not available. not available. Using exit code of executable from command line."\n'
1456 spiga 1.189 txt += ' else\n'
1457     txt += ' echo "Extracted ExitStatus from FrameworkJobReport parsing output: $executable_exit_status"\n'
1458     txt += ' fi\n'
1459     txt += ' else\n'
1460     txt += ' echo "CRAB python script to parse CRAB FrameworkJobReport crab_fjr.xml is not available, using exit code of executable from command line."\n'
1461     txt += ' fi\n'
1462     #### Patch to check input data reading for CMSSW16x Hopefully we-ll remove it asap
1463 spiga 1.232 txt += ' if [ $executable_exit_status -eq 0 ];then\n'
1464     txt += ' echo ">>> Executable succeded $executable_exit_status"\n'
1465 spiga 1.233 if (self.datasetPath and not (self.dataset_pu or self.useParent)) :
1466 spiga 1.189 # VERIFY PROCESSED DATA
1467     txt += ' echo ">>> Verify list of processed files:"\n'
1468 ewv 1.196 txt += ' echo $InputFiles |tr -d \'\\\\\' |tr \',\' \'\\n\'|tr -d \'"\' > input-files.txt\n'
1469 spiga 1.200 txt += ' python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --lfn > processed-files.txt\n'
1470 spiga 1.189 txt += ' cat input-files.txt | sort | uniq > tmp.txt\n'
1471     txt += ' mv tmp.txt input-files.txt\n'
1472     txt += ' echo "cat input-files.txt"\n'
1473     txt += ' echo "----------------------"\n'
1474     txt += ' cat input-files.txt\n'
1475     txt += ' cat processed-files.txt | sort | uniq > tmp.txt\n'
1476     txt += ' mv tmp.txt processed-files.txt\n'
1477     txt += ' echo "----------------------"\n'
1478     txt += ' echo "cat processed-files.txt"\n'
1479     txt += ' echo "----------------------"\n'
1480     txt += ' cat processed-files.txt\n'
1481     txt += ' echo "----------------------"\n'
1482     txt += ' diff -q input-files.txt processed-files.txt\n'
1483     txt += ' fileverify_status=$?\n'
1484     txt += ' if [ $fileverify_status -ne 0 ]; then\n'
1485     txt += ' executable_exit_status=30001\n'
1486     txt += ' echo "ERROR ==> not all input files processed"\n'
1487     txt += ' echo " ==> list of processed files from crab_fjr.xml differs from list in pset.cfg"\n'
1488     txt += ' echo " ==> diff input-files.txt processed-files.txt"\n'
1489     txt += ' fi\n'
1490 spiga 1.232 txt += ' elif [ $executable_exit_status -ne 0 ] || [ $executable_exit_status -ne 50015 ] || [ $executable_exit_status -ne 50017 ];then\n'
1491     txt += ' echo ">>> Executable failed $executable_exit_status"\n'
1492 spiga 1.251 txt += ' echo "ExeExitCode=$executable_exit_status" | tee -a $RUNTIME_AREA/$repo\n'
1493     txt += ' echo "EXECUTABLE_EXIT_STATUS = $executable_exit_status"\n'
1494     txt += ' job_exit_code=$executable_exit_status\n'
1495 spiga 1.232 txt += ' func_exit\n'
1496     txt += ' fi\n'
1497     txt += '\n'
1498 spiga 1.189 txt += 'else\n'
1499     txt += ' echo "CRAB FrameworkJobReport crab_fjr.xml is not available, using exit code of executable from command line."\n'
1500     txt += 'fi\n'
1501     txt += '\n'
1502     txt += 'echo "ExeExitCode=$executable_exit_status" | tee -a $RUNTIME_AREA/$repo\n'
1503     txt += 'echo "EXECUTABLE_EXIT_STATUS = $executable_exit_status"\n'
1504     txt += 'job_exit_code=$executable_exit_status\n'
1505    
1506     return txt
1507    
1508 gutsche 1.5 def setParam_(self, param, value):
1509     self._params[param] = value
1510    
1511     def getParams(self):
1512     return self._params
1513 gutsche 1.8
1514 gutsche 1.35 def uniquelist(self, old):
1515     """
1516     remove duplicates from a list
1517     """
1518     nd={}
1519     for e in old:
1520     nd[e]=0
1521     return nd.keys()
1522 mcinquil 1.121
1523 spiga 1.169 def outList(self):
1524 mcinquil 1.121 """
1525     check the dimension of the output files
1526     """
1527 spiga 1.169 txt = ''
1528     txt += 'echo ">>> list of expected files on output sandbox"\n'
1529 mcinquil 1.121 listOutFiles = []
1530 ewv 1.170 stdout = 'CMSSW_$NJob.stdout'
1531 spiga 1.169 stderr = 'CMSSW_$NJob.stderr'
1532 fanzago 1.148 if (self.return_data == 1):
1533 spiga 1.157 for file in (self.output_file+self.output_file_sandbox):
1534 slacapra 1.207 listOutFiles.append(numberFile(file, '$NJob'))
1535 spiga 1.169 listOutFiles.append(stdout)
1536     listOutFiles.append(stderr)
1537 ewv 1.156 else:
1538 spiga 1.157 for file in (self.output_file_sandbox):
1539 slacapra 1.207 listOutFiles.append(numberFile(file, '$NJob'))
1540 spiga 1.169 listOutFiles.append(stdout)
1541     listOutFiles.append(stderr)
1542 fanzago 1.161 txt += 'echo "output files: '+string.join(listOutFiles,' ')+'"\n'
1543 spiga 1.157 txt += 'filesToCheck="'+string.join(listOutFiles,' ')+'"\n'
1544 spiga 1.169 txt += 'export filesToCheck\n'
1545 ewv 1.170 return txt