ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.257
Committed: Tue Dec 2 15:01:29 2008 UTC (16 years, 4 months ago) by spiga
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_4_3_pre5
Changes since 1.256: +2 -1 lines
Log Message:
added first part of code to support remote dir check at creation time. (not finished)

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 slacapra 1.256 tar.dereference=True
937 slacapra 1.61 libDir = 'lib'
938     lib = swArea+'/' +libDir
939     common.logger.debug(5,"lib "+lib+" to be tarred")
940     if os.path.exists(lib):
941     tar.add(lib,libDir)
942 ewv 1.131
943 slacapra 1.61 ## Now check if module dir is present
944     moduleDir = 'module'
945     module = swArea + '/' + moduleDir
946     if os.path.isdir(module):
947     tar.add(module,moduleDir)
948 slacapra 1.256 tar.dereference=False
949 slacapra 1.61
950     ## Now check if any data dir(s) is present
951 spiga 1.179 self.dataExist = False
952 slacapra 1.212 todo_list = [(i, i) for i in os.listdir(swArea+"/src")]
953 slacapra 1.206 while len(todo_list):
954     entry, name = todo_list.pop()
955 slacapra 1.211 if name.startswith('crab_0_') or name.startswith('.') or name == 'CVS':
956 slacapra 1.206 continue
957 slacapra 1.212 if os.path.isdir(swArea+"/src/"+entry):
958 slacapra 1.206 entryPath = entry + '/'
959 slacapra 1.212 todo_list += [(entryPath + i, i) for i in os.listdir(swArea+"/src/"+entry)]
960 slacapra 1.206 if name == 'data':
961     self.dataExist=True
962     common.logger.debug(5,"data "+entry+" to be tarred")
963 slacapra 1.212 tar.add(swArea+"/src/"+entry,"src/"+entry)
964 slacapra 1.206 pass
965     pass
966 ewv 1.182
967 spiga 1.179 ### CMSSW ParameterSet
968     if not self.pset is None:
969     cfg_file = common.work_space.jobDir()+self.configFilename()
970 ewv 1.182 tar.add(cfg_file,self.configFilename())
971 spiga 1.179 common.logger.debug(5,"File added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
972 slacapra 1.61
973 fanzago 1.93
974 fanzago 1.152 ## Add ProdCommon dir to tar
975 slacapra 1.211 prodcommonDir = './'
976     prodcommonPath = os.environ['CRABDIR'] + '/' + 'external/'
977 spiga 1.244 neededStuff = ['ProdCommon/__init__.py','ProdCommon/FwkJobRep', 'ProdCommon/CMSConfigTools', \
978     'ProdCommon/Core', 'ProdCommon/MCPayloads', 'IMProv', 'ProdCommon/Storage']
979 slacapra 1.214 for file in neededStuff:
980     tar.add(prodcommonPath+file,prodcommonDir+file)
981 spiga 1.179 common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
982    
983     ##### ML stuff
984     ML_file_list=['report.py', 'DashboardAPI.py', 'Logger.py', 'ProcInfo.py', 'apmon.py']
985     path=os.environ['CRABDIR'] + '/python/'
986     for file in ML_file_list:
987     tar.add(path+file,file)
988     common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
989    
990     ##### Utils
991 spiga 1.238 Utils_file_list=['parseCrabFjr.py','writeCfg.py', 'fillCrabFjr.py','cmscp.py']
992 spiga 1.179 for file in Utils_file_list:
993     tar.add(path+file,file)
994     common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
995 ewv 1.131
996 ewv 1.182 ##### AdditionalFiles
997 slacapra 1.253 tar.dereference=True
998 spiga 1.179 for file in self.additional_inbox_files:
999     tar.add(file,string.split(file,'/')[-1])
1000 slacapra 1.253 tar.dereference=False
1001 slacapra 1.61 common.logger.debug(5,"Files added to "+self.tgzNameWithPath+" : "+str(tar.getnames()))
1002 ewv 1.182
1003 slacapra 1.61 tar.close()
1004 mcinquil 1.241 except IOError, exc:
1005     common.logger.write(str(exc))
1006 slacapra 1.220 raise CrabException('Could not create tar-ball '+self.tgzNameWithPath)
1007 mcinquil 1.241 except tarfile.TarError, exc:
1008     common.logger.write(str(exc))
1009 slacapra 1.206 raise CrabException('Could not create tar-ball '+self.tgzNameWithPath)
1010 gutsche 1.72
1011     ## check for tarball size
1012     tarballinfo = os.stat(self.tgzNameWithPath)
1013     if ( tarballinfo.st_size > self.MaxTarBallSize*1024*1024 ) :
1014 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) \
1015 ewv 1.250 +'MB input sandbox limit \n'
1016 spiga 1.238 msg += ' and not supported by the direct GRID submission system.\n'
1017     msg += ' Please use the CRAB server mode by setting server_name=<NAME> in section [CRAB] of your crab.cfg.\n'
1018     msg += ' For further infos please see https://twiki.cern.ch/twiki/bin/view/CMS/CrabServer#CRABSERVER_for_Users'
1019     raise CrabException(msg)
1020 gutsche 1.72
1021 slacapra 1.61 ## create tar-ball with ML stuff
1022 slacapra 1.97
1023 spiga 1.165 def wsSetupEnvironment(self, nj=0):
1024 slacapra 1.1 """
1025     Returns part of a job script which prepares
1026     the execution environment for the job 'nj'.
1027     """
1028 ewv 1.184 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
1029     psetName = 'pset.py'
1030     else:
1031     psetName = 'pset.cfg'
1032 slacapra 1.1 # Prepare JobType-independent part
1033 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupEnvironment\n'
1034 fanzago 1.133 txt += 'echo ">>> setup environment"\n'
1035 ewv 1.131 txt += 'if [ $middleware == LCG ]; then \n'
1036 gutsche 1.3 txt += self.wsSetupCMSLCGEnvironment_()
1037     txt += 'elif [ $middleware == OSG ]; then\n'
1038 gutsche 1.43 txt += ' WORKING_DIR=`/bin/mktemp -d $OSG_WN_TMP/cms_XXXXXXXXXXXX`\n'
1039 ewv 1.132 txt += ' if [ ! $? == 0 ] ;then\n'
1040 fanzago 1.161 txt += ' echo "ERROR ==> OSG $WORKING_DIR could not be created on WN `hostname`"\n'
1041     txt += ' job_exit_code=10016\n'
1042     txt += ' func_exit\n'
1043 gutsche 1.3 txt += ' fi\n'
1044 fanzago 1.133 txt += ' echo ">>> Created working directory: $WORKING_DIR"\n'
1045 gutsche 1.3 txt += '\n'
1046     txt += ' echo "Change to working directory: $WORKING_DIR"\n'
1047     txt += ' cd $WORKING_DIR\n'
1048 fanzago 1.133 txt += ' echo ">>> current directory (WORKING_DIR): $WORKING_DIR"\n'
1049 ewv 1.131 txt += self.wsSetupCMSOSGEnvironment_()
1050 gutsche 1.3 txt += 'fi\n'
1051 slacapra 1.1
1052     # Prepare JobType-specific part
1053     scram = self.scram.commandName()
1054     txt += '\n\n'
1055 fanzago 1.133 txt += 'echo ">>> specific cmssw setup environment:"\n'
1056     txt += 'echo "CMSSW_VERSION = '+self.version+'"\n'
1057 slacapra 1.1 txt += scram+' project CMSSW '+self.version+'\n'
1058     txt += 'status=$?\n'
1059     txt += 'if [ $status != 0 ] ; then\n'
1060 fanzago 1.161 txt += ' echo "ERROR ==> CMSSW '+self.version+' not found on `hostname`" \n'
1061     txt += ' job_exit_code=10034\n'
1062 fanzago 1.163 txt += ' func_exit\n'
1063 slacapra 1.1 txt += 'fi \n'
1064     txt += 'cd '+self.version+'\n'
1065 fanzago 1.99 txt += 'SOFTWARE_DIR=`pwd`\n'
1066 fanzago 1.133 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
1067 slacapra 1.1 txt += 'eval `'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME`\n'
1068 fanzago 1.180 txt += 'if [ $? != 0 ] ; then\n'
1069     txt += ' echo "ERROR ==> Problem with the command: "\n'
1070     txt += ' echo "eval \`'+scram+' runtime -sh | grep -v SCRAMRT_LSB_JOBNAME \` at `hostname`"\n'
1071     txt += ' job_exit_code=10034\n'
1072     txt += ' func_exit\n'
1073     txt += 'fi \n'
1074 slacapra 1.1 # Handle the arguments:
1075     txt += "\n"
1076 gutsche 1.7 txt += "## number of arguments (first argument always jobnumber)\n"
1077 slacapra 1.1 txt += "\n"
1078 spiga 1.165 txt += "if [ $nargs -lt "+str(self.argsList)+" ]\n"
1079 slacapra 1.1 txt += "then\n"
1080 fanzago 1.161 txt += " echo 'ERROR ==> Too few arguments' +$nargs+ \n"
1081     txt += ' job_exit_code=50113\n'
1082     txt += " func_exit\n"
1083 slacapra 1.1 txt += "fi\n"
1084     txt += "\n"
1085    
1086     # Prepare job-specific part
1087     job = common.job_list[nj]
1088 ewv 1.131 if (self.datasetPath):
1089 spiga 1.238 self.primaryDataset = self.datasetPath.split("/")[1]
1090     DataTier = self.datasetPath.split("/")[2]
1091 fanzago 1.93 txt += '\n'
1092     txt += 'DatasetPath='+self.datasetPath+'\n'
1093    
1094 spiga 1.238 txt += 'PrimaryDataset='+self.primaryDataset +'\n'
1095     txt += 'DataTier='+DataTier+'\n'
1096 fanzago 1.96 txt += 'ApplicationFamily=cmsRun\n'
1097 fanzago 1.93
1098     else:
1099 ewv 1.250 self.primaryDataset = 'null'
1100 fanzago 1.93 txt += 'DatasetPath=MCDataTier\n'
1101     txt += 'PrimaryDataset=null\n'
1102     txt += 'DataTier=null\n'
1103     txt += 'ApplicationFamily=MCDataTier\n'
1104 ewv 1.170 if self.pset != None:
1105 spiga 1.42 pset = os.path.basename(job.configFilename())
1106     txt += '\n'
1107 spiga 1.95 txt += 'cp $RUNTIME_AREA/'+pset+' .\n'
1108 spiga 1.42 if (self.datasetPath): # standard job
1109 ewv 1.160 txt += 'InputFiles=${args[1]}; export InputFiles\n'
1110 ewv 1.226 if (self.useParent):
1111 spiga 1.204 txt += 'ParentFiles=${args[2]}; export ParentFiles\n'
1112     txt += 'MaxEvents=${args[3]}; export MaxEvents\n'
1113     txt += 'SkipEvents=${args[4]}; export SkipEvents\n'
1114     else:
1115     txt += 'MaxEvents=${args[2]}; export MaxEvents\n'
1116     txt += 'SkipEvents=${args[3]}; export SkipEvents\n'
1117 spiga 1.42 txt += 'echo "Inputfiles:<$InputFiles>"\n'
1118 spiga 1.204 if (self.useParent): txt += 'echo "ParentFiles:<$ParentFiles>"\n'
1119 spiga 1.42 txt += 'echo "MaxEvents:<$MaxEvents>"\n'
1120     txt += 'echo "SkipEvents:<$SkipEvents>"\n'
1121     else: # pythia like job
1122 ewv 1.160 txt += 'PreserveSeeds=' + ','.join(self.preserveSeeds) + '; export PreserveSeeds\n'
1123     txt += 'IncrementSeeds=' + ','.join(self.incrementSeeds) + '; export IncrementSeeds\n'
1124     txt += 'echo "PreserveSeeds: <$PreserveSeeds>"\n'
1125     txt += 'echo "IncrementSeeds:<$IncrementSeeds>"\n'
1126 slacapra 1.90 if (self.firstRun):
1127 ewv 1.160 txt += 'FirstRun=${args[1]}; export FirstRun\n'
1128 spiga 1.57 txt += 'echo "FirstRun: <$FirstRun>"\n'
1129 slacapra 1.90
1130 ewv 1.184 txt += 'mv -f ' + pset + ' ' + psetName + '\n'
1131 slacapra 1.1
1132    
1133 fanzago 1.163 if self.pset != None:
1134 ewv 1.184 # FUTURE: Can simply for 2_1_x and higher
1135 spiga 1.42 txt += '\n'
1136 spiga 1.197 if self.debug_wrapper==True:
1137 spiga 1.188 txt += 'echo "***** cat ' + psetName + ' *********"\n'
1138     txt += 'cat ' + psetName + '\n'
1139     txt += 'echo "****** end ' + psetName + ' ********"\n'
1140     txt += '\n'
1141 ewv 1.226 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
1142     txt += 'PSETHASH=`edmConfigHash ' + psetName + '` \n'
1143     else:
1144     txt += 'PSETHASH=`edmConfigHash < ' + psetName + '` \n'
1145 fanzago 1.94 txt += 'echo "PSETHASH = $PSETHASH" \n'
1146 fanzago 1.93 txt += '\n'
1147 gutsche 1.3 return txt
1148 slacapra 1.176
1149 fanzago 1.166 def wsUntarSoftware(self, nj=0):
1150 gutsche 1.3 """
1151     Put in the script the commands to build an executable
1152     or a library.
1153     """
1154    
1155 fanzago 1.166 txt = '\n#Written by cms_cmssw::wsUntarSoftware\n'
1156 gutsche 1.3
1157     if os.path.isfile(self.tgzNameWithPath):
1158 fanzago 1.133 txt += 'echo ">>> tar xzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+' :" \n'
1159 slacapra 1.255 txt += 'tar xzf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
1160 spiga 1.199 if self.debug_wrapper:
1161 slacapra 1.255 txt += 'tar tzvf $RUNTIME_AREA/'+os.path.basename(self.tgzNameWithPath)+'\n'
1162 spiga 1.199 txt += 'ls -Al \n'
1163 gutsche 1.3 txt += 'untar_status=$? \n'
1164     txt += 'if [ $untar_status -ne 0 ]; then \n'
1165 fanzago 1.161 txt += ' echo "ERROR ==> Untarring .tgz file failed"\n'
1166     txt += ' job_exit_code=$untar_status\n'
1167     txt += ' func_exit\n'
1168 gutsche 1.3 txt += 'else \n'
1169     txt += ' echo "Successful untar" \n'
1170     txt += 'fi \n'
1171 gutsche 1.50 txt += '\n'
1172 slacapra 1.211 txt += 'echo ">>> Include $RUNTIME_AREA in PYTHONPATH:"\n'
1173 gutsche 1.50 txt += 'if [ -z "$PYTHONPATH" ]; then\n'
1174 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/\n'
1175 gutsche 1.50 txt += 'else\n'
1176 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/:${PYTHONPATH}\n'
1177 fanzago 1.93 txt += 'echo "PYTHONPATH=$PYTHONPATH"\n'
1178 gutsche 1.50 txt += 'fi\n'
1179     txt += '\n'
1180    
1181 gutsche 1.3 pass
1182 ewv 1.131
1183 slacapra 1.1 return txt
1184 ewv 1.170
1185 fanzago 1.166 def wsBuildExe(self, nj=0):
1186     """
1187     Put in the script the commands to build an executable
1188     or a library.
1189     """
1190    
1191     txt = '\n#Written by cms_cmssw::wsBuildExe\n'
1192     txt += 'echo ">>> moving CMSSW software directories in `pwd`" \n'
1193    
1194 ewv 1.170 txt += 'rm -r lib/ module/ \n'
1195     txt += 'mv $RUNTIME_AREA/lib/ . \n'
1196     txt += 'mv $RUNTIME_AREA/module/ . \n'
1197 spiga 1.186 if self.dataExist == True:
1198     txt += 'rm -r src/ \n'
1199     txt += 'mv $RUNTIME_AREA/src/ . \n'
1200 ewv 1.182 if len(self.additional_inbox_files)>0:
1201 spiga 1.179 for file in self.additional_inbox_files:
1202 spiga 1.191 txt += 'mv $RUNTIME_AREA/'+os.path.basename(file)+' . \n'
1203 slacapra 1.214 # txt += 'mv $RUNTIME_AREA/ProdCommon/ . \n'
1204     # txt += 'mv $RUNTIME_AREA/IMProv/ . \n'
1205 ewv 1.170
1206 slacapra 1.211 txt += 'echo ">>> Include $RUNTIME_AREA in PYTHONPATH:"\n'
1207 fanzago 1.166 txt += 'if [ -z "$PYTHONPATH" ]; then\n'
1208 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/\n'
1209 fanzago 1.166 txt += 'else\n'
1210 slacapra 1.211 txt += ' export PYTHONPATH=$RUNTIME_AREA/:${PYTHONPATH}\n'
1211 fanzago 1.166 txt += 'echo "PYTHONPATH=$PYTHONPATH"\n'
1212     txt += 'fi\n'
1213     txt += '\n'
1214    
1215     return txt
1216 slacapra 1.1
1217 ewv 1.131
1218 slacapra 1.1 def executableName(self):
1219 ewv 1.192 if self.scriptExe:
1220 spiga 1.42 return "sh "
1221     else:
1222     return self.executable
1223 slacapra 1.1
1224     def executableArgs(self):
1225 ewv 1.160 # FUTURE: This function tests the CMSSW version. Can be simplified as we drop support for old versions
1226 slacapra 1.70 if self.scriptExe:#CarlosDaniele
1227 spiga 1.42 return self.scriptExe + " $NJob"
1228 fanzago 1.115 else:
1229 ewv 1.160 ex_args = ""
1230 ewv 1.171 # FUTURE: This tests the CMSSW version. Can remove code as versions deprecated
1231 ewv 1.160 # Framework job report
1232 ewv 1.184 if (self.CMSSW_major >= 1 and self.CMSSW_minor >= 5) or (self.CMSSW_major >= 2):
1233 fanzago 1.166 ex_args += " -j $RUNTIME_AREA/crab_fjr_$NJob.xml"
1234 ewv 1.184 # Type of config file
1235     if self.CMSSW_major >= 2 :
1236 ewv 1.171 ex_args += " -p pset.py"
1237 fanzago 1.115 else:
1238 ewv 1.160 ex_args += " -p pset.cfg"
1239     return ex_args
1240 slacapra 1.1
1241     def inputSandbox(self, nj):
1242     """
1243     Returns a list of filenames to be put in JDL input sandbox.
1244     """
1245     inp_box = []
1246     if os.path.isfile(self.tgzNameWithPath):
1247     inp_box.append(self.tgzNameWithPath)
1248 spiga 1.243 inp_box.append(common.work_space.jobDir() + self.scriptName)
1249 slacapra 1.1 return inp_box
1250    
1251     def outputSandbox(self, nj):
1252     """
1253     Returns a list of filenames to be put in JDL output sandbox.
1254     """
1255     out_box = []
1256    
1257     ## User Declared output files
1258 slacapra 1.54 for out in (self.output_file+self.output_file_sandbox):
1259 ewv 1.131 n_out = nj + 1
1260 slacapra 1.207 out_box.append(numberFile(out,str(n_out)))
1261 slacapra 1.1 return out_box
1262    
1263    
1264     def wsRenameOutput(self, nj):
1265     """
1266     Returns part of a job script which renames the produced files.
1267     """
1268    
1269 ewv 1.160 txt = '\n#Written by cms_cmssw::wsRenameOutput\n'
1270 fanzago 1.148 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
1271     txt += 'echo ">>> current directory content:"\n'
1272 ewv 1.226 if self.debug_wrapper:
1273 spiga 1.199 txt += 'ls -Al\n'
1274 fanzago 1.145 txt += '\n'
1275 slacapra 1.54
1276 fanzago 1.128 for fileWithSuffix in (self.output_file):
1277 slacapra 1.207 output_file_num = numberFile(fileWithSuffix, '$NJob')
1278 slacapra 1.1 txt += '\n'
1279 gutsche 1.7 txt += '# check output file\n'
1280 slacapra 1.106 txt += 'if [ -e ./'+fileWithSuffix+' ] ; then\n'
1281 ewv 1.147 if (self.copy_data == 1): # For OSG nodes, file is in $WORKING_DIR, should not be moved to $RUNTIME_AREA
1282     txt += ' mv '+fileWithSuffix+' '+output_file_num+'\n'
1283 spiga 1.209 txt += ' ln -s `pwd`/'+output_file_num+' $RUNTIME_AREA/'+fileWithSuffix+'\n'
1284 ewv 1.147 else:
1285     txt += ' mv '+fileWithSuffix+' $RUNTIME_AREA/'+output_file_num+'\n'
1286     txt += ' ln -s $RUNTIME_AREA/'+output_file_num+' $RUNTIME_AREA/'+fileWithSuffix+'\n'
1287 slacapra 1.106 txt += 'else\n'
1288 fanzago 1.161 txt += ' job_exit_code=60302\n'
1289     txt += ' echo "WARNING: Output file '+fileWithSuffix+' not found"\n'
1290 ewv 1.156 if common.scheduler.name().upper() == 'CONDOR_G':
1291 gutsche 1.7 txt += ' if [ $middleware == OSG ]; then \n'
1292     txt += ' echo "prepare dummy output file"\n'
1293     txt += ' echo "Processing of job output failed" > $RUNTIME_AREA/'+output_file_num+'\n'
1294     txt += ' fi \n'
1295 slacapra 1.1 txt += 'fi\n'
1296 slacapra 1.105 file_list = []
1297     for fileWithSuffix in (self.output_file):
1298 spiga 1.246 file_list.append(numberFile('$SOFTWARE_DIR/'+fileWithSuffix, '$NJob'))
1299 ewv 1.131
1300 spiga 1.245 txt += 'file_list="'+string.join(file_list,',')+'"\n'
1301 fanzago 1.149 txt += '\n'
1302 fanzago 1.148 txt += 'echo ">>> current directory (SOFTWARE_DIR): $SOFTWARE_DIR" \n'
1303     txt += 'echo ">>> current directory content:"\n'
1304 ewv 1.226 if self.debug_wrapper:
1305 spiga 1.199 txt += 'ls -Al\n'
1306 fanzago 1.148 txt += '\n'
1307 gutsche 1.7 txt += 'cd $RUNTIME_AREA\n'
1308 fanzago 1.133 txt += 'echo ">>> current directory (RUNTIME_AREA): $RUNTIME_AREA"\n'
1309 slacapra 1.1 return txt
1310    
1311 slacapra 1.63 def getRequirements(self, nj=[]):
1312 slacapra 1.1 """
1313 ewv 1.131 return job requirements to add to jdl files
1314 slacapra 1.1 """
1315     req = ''
1316 slacapra 1.47 if self.version:
1317 slacapra 1.10 req='Member("VO-cms-' + \
1318 slacapra 1.47 self.version + \
1319 slacapra 1.10 '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
1320 ewv 1.192 if self.executable_arch:
1321 gutsche 1.107 req+=' && Member("VO-cms-' + \
1322 slacapra 1.105 self.executable_arch + \
1323     '", other.GlueHostApplicationSoftwareRunTimeEnvironment)'
1324 gutsche 1.35
1325     req = req + ' && (other.GlueHostNetworkAdapterOutboundIP)'
1326 afanfani 1.229 if ( common.scheduler.name() == "glitecoll" ) or ( common.scheduler.name() == "glite"):
1327 afanfani 1.158 req += ' && other.GlueCEStateStatus == "Production" '
1328 gutsche 1.35
1329 slacapra 1.1 return req
1330 gutsche 1.3
1331     def configFilename(self):
1332     """ return the config filename """
1333 ewv 1.182 # FUTURE: Can remove cfg mode for CMSSW >= 2_1_x
1334 ewv 1.184 if (self.CMSSW_major >= 2 and self.CMSSW_minor >= 1) or (self.CMSSW_major >= 3):
1335 ewv 1.182 return self.name()+'.py'
1336     else:
1337     return self.name()+'.cfg'
1338 gutsche 1.3
1339     def wsSetupCMSOSGEnvironment_(self):
1340     """
1341     Returns part of a job script which is prepares
1342     the execution environment and which is common for all CMS jobs.
1343     """
1344 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupCMSOSGEnvironment_\n'
1345     txt += ' echo ">>> setup CMS OSG environment:"\n'
1346 fanzago 1.133 txt += ' echo "set SCRAM ARCH to ' + self.executable_arch + '"\n'
1347     txt += ' export SCRAM_ARCH='+self.executable_arch+'\n'
1348 fanzago 1.136 txt += ' echo "SCRAM_ARCH = $SCRAM_ARCH"\n'
1349 ewv 1.135 txt += ' if [ -f $OSG_APP/cmssoft/cms/cmsset_default.sh ] ;then\n'
1350 mkirn 1.40 txt += ' # Use $OSG_APP/cmssoft/cms/cmsset_default.sh to setup cms software\n'
1351 fanzago 1.133 txt += ' source $OSG_APP/cmssoft/cms/cmsset_default.sh '+self.version+'\n'
1352     txt += ' else\n'
1353 fanzago 1.161 txt += ' echo "ERROR ==> $OSG_APP/cmssoft/cms/cmsset_default.sh file not found"\n'
1354     txt += ' job_exit_code=10020\n'
1355     txt += ' func_exit\n'
1356 fanzago 1.133 txt += ' fi\n'
1357 gutsche 1.3 txt += '\n'
1358 fanzago 1.161 txt += ' echo "==> setup cms environment ok"\n'
1359 fanzago 1.136 txt += ' echo "SCRAM_ARCH = $SCRAM_ARCH"\n'
1360 gutsche 1.3
1361     return txt
1362 ewv 1.131
1363 gutsche 1.3 def wsSetupCMSLCGEnvironment_(self):
1364     """
1365     Returns part of a job script which is prepares
1366     the execution environment and which is common for all CMS jobs.
1367     """
1368 ewv 1.160 txt = '\n#Written by cms_cmssw::wsSetupCMSLCGEnvironment_\n'
1369     txt += ' echo ">>> setup CMS LCG environment:"\n'
1370 fanzago 1.133 txt += ' echo "set SCRAM ARCH and BUILD_ARCH to ' + self.executable_arch + ' ###"\n'
1371     txt += ' export SCRAM_ARCH='+self.executable_arch+'\n'
1372     txt += ' export BUILD_ARCH='+self.executable_arch+'\n'
1373     txt += ' if [ ! $VO_CMS_SW_DIR ] ;then\n'
1374 fanzago 1.161 txt += ' echo "ERROR ==> CMS software dir not found on WN `hostname`"\n'
1375     txt += ' job_exit_code=10031\n'
1376     txt += ' func_exit\n'
1377 fanzago 1.133 txt += ' else\n'
1378     txt += ' echo "Sourcing environment... "\n'
1379     txt += ' if [ ! -s $VO_CMS_SW_DIR/cmsset_default.sh ] ;then\n'
1380 fanzago 1.161 txt += ' echo "ERROR ==> cmsset_default.sh file not found into dir $VO_CMS_SW_DIR"\n'
1381     txt += ' job_exit_code=10020\n'
1382     txt += ' func_exit\n'
1383 fanzago 1.133 txt += ' fi\n'
1384     txt += ' echo "sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1385     txt += ' source $VO_CMS_SW_DIR/cmsset_default.sh\n'
1386     txt += ' result=$?\n'
1387     txt += ' if [ $result -ne 0 ]; then\n'
1388 fanzago 1.161 txt += ' echo "ERROR ==> problem sourcing $VO_CMS_SW_DIR/cmsset_default.sh"\n'
1389     txt += ' job_exit_code=10032\n'
1390     txt += ' func_exit\n'
1391 fanzago 1.133 txt += ' fi\n'
1392     txt += ' fi\n'
1393     txt += ' \n'
1394 fanzago 1.161 txt += ' echo "==> setup cms environment ok"\n'
1395 gutsche 1.3 return txt
1396 gutsche 1.5
1397 spiga 1.238 def wsModifyReport(self, nj):
1398 fanzago 1.93 """
1399 ewv 1.131 insert the part of the script that modifies the FrameworkJob Report
1400 fanzago 1.93 """
1401 spiga 1.238 txt = '\n#Written by cms_cmssw::wsModifyReport\n'
1402 slacapra 1.176 publish_data = int(self.cfg_params.get('USER.publish_data',0))
1403 ewv 1.131 if (publish_data == 1):
1404 ewv 1.250
1405 fanzago 1.248 processedDataset = self.cfg_params['USER.publish_data_name']
1406 spiga 1.238
1407     txt += 'if [ $StageOutExitStatus -eq 0 ]; then\n'
1408 fanzago 1.248 txt += ' FOR_LFN=$LFNBaseName\n'
1409 fanzago 1.175 txt += 'else\n'
1410     txt += ' FOR_LFN=/copy_problems/ \n'
1411     txt += ' SE=""\n'
1412     txt += ' SE_PATH=""\n'
1413     txt += 'fi\n'
1414 ewv 1.182
1415 fanzago 1.175 txt += 'echo ">>> Modify Job Report:" \n'
1416 fanzago 1.217 txt += 'chmod a+x $RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py\n'
1417 fanzago 1.248 txt += 'ProcessedDataset='+processedDataset+'\n'
1418     #txt += 'ProcessedDataset=$procDataset \n'
1419 fanzago 1.175 txt += 'echo "ProcessedDataset = $ProcessedDataset"\n'
1420     txt += 'echo "SE = $SE"\n'
1421     txt += 'echo "SE_PATH = $SE_PATH"\n'
1422     txt += 'echo "FOR_LFN = $FOR_LFN" \n'
1423     txt += 'echo "CMSSW_VERSION = $CMSSW_VERSION"\n\n'
1424 spiga 1.238 args = '$RUNTIME_AREA/crab_fjr_$NJob.xml $NJob $FOR_LFN $PrimaryDataset $DataTier ' \
1425 fanzago 1.248 '$USER-$ProcessedDataset-$PSETHASH $ApplicationFamily '+ \
1426 fanzago 1.247 ' $executable $CMSSW_VERSION $PSETHASH $SE $SE_PATH'
1427     txt += 'echo "$RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py '+str(args)+'"\n'
1428     txt += '$RUNTIME_AREA/ProdCommon/FwkJobRep/ModifyJobReport.py '+str(args)+'\n'
1429 fanzago 1.175 txt += 'modifyReport_result=$?\n'
1430     txt += 'if [ $modifyReport_result -ne 0 ]; then\n'
1431     txt += ' modifyReport_result=70500\n'
1432     txt += ' job_exit_code=$modifyReport_result\n'
1433     txt += ' echo "ModifyReportResult=$modifyReport_result" | tee -a $RUNTIME_AREA/$repo\n'
1434     txt += ' echo "WARNING: Problem with ModifyJobReport"\n'
1435     txt += 'else\n'
1436     txt += ' mv NewFrameworkJobReport.xml $RUNTIME_AREA/crab_fjr_$NJob.xml\n'
1437 spiga 1.103 txt += 'fi\n'
1438 fanzago 1.93 return txt
1439 fanzago 1.99
1440 ewv 1.192 def wsParseFJR(self):
1441 spiga 1.189 """
1442 ewv 1.192 Parse the FrameworkJobReport to obtain useful infos
1443 spiga 1.189 """
1444     txt = '\n#Written by cms_cmssw::wsParseFJR\n'
1445     txt += 'echo ">>> Parse FrameworkJobReport crab_fjr.xml"\n'
1446     txt += 'if [ -s $RUNTIME_AREA/crab_fjr_$NJob.xml ]; then\n'
1447     txt += ' if [ -s $RUNTIME_AREA/parseCrabFjr.py ]; then\n'
1448 spiga 1.197 txt += ' cmd_out=`python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --dashboard $MonitorID,$MonitorJobID '+self.debugWrap+'`\n'
1449     if self.debug_wrapper :
1450     txt += ' echo "Result of parsing the FrameworkJobReport crab_fjr.xml: $cmd_out"\n'
1451     txt += ' executable_exit_status=`python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --exitcode`\n'
1452 spiga 1.189 txt += ' if [ $executable_exit_status -eq 50115 ];then\n'
1453     txt += ' echo ">>> crab_fjr.xml contents: "\n'
1454 spiga 1.222 txt += ' cat $RUNTIME_AREA/crab_fjr_$NJob.xml\n'
1455 spiga 1.189 txt += ' echo "Wrong FrameworkJobReport --> does not contain useful info. ExitStatus: $executable_exit_status"\n'
1456 spiga 1.197 txt += ' elif [ $executable_exit_status -eq -999 ];then\n'
1457     txt += ' echo "ExitStatus from FrameworkJobReport not available. not available. Using exit code of executable from command line."\n'
1458 spiga 1.189 txt += ' else\n'
1459     txt += ' echo "Extracted ExitStatus from FrameworkJobReport parsing output: $executable_exit_status"\n'
1460     txt += ' fi\n'
1461     txt += ' else\n'
1462     txt += ' echo "CRAB python script to parse CRAB FrameworkJobReport crab_fjr.xml is not available, using exit code of executable from command line."\n'
1463     txt += ' fi\n'
1464     #### Patch to check input data reading for CMSSW16x Hopefully we-ll remove it asap
1465 spiga 1.232 txt += ' if [ $executable_exit_status -eq 0 ];then\n'
1466     txt += ' echo ">>> Executable succeded $executable_exit_status"\n'
1467 spiga 1.233 if (self.datasetPath and not (self.dataset_pu or self.useParent)) :
1468 spiga 1.189 # VERIFY PROCESSED DATA
1469     txt += ' echo ">>> Verify list of processed files:"\n'
1470 ewv 1.196 txt += ' echo $InputFiles |tr -d \'\\\\\' |tr \',\' \'\\n\'|tr -d \'"\' > input-files.txt\n'
1471 spiga 1.200 txt += ' python $RUNTIME_AREA/parseCrabFjr.py --input $RUNTIME_AREA/crab_fjr_$NJob.xml --lfn > processed-files.txt\n'
1472 spiga 1.189 txt += ' cat input-files.txt | sort | uniq > tmp.txt\n'
1473     txt += ' mv tmp.txt input-files.txt\n'
1474     txt += ' echo "cat input-files.txt"\n'
1475     txt += ' echo "----------------------"\n'
1476     txt += ' cat input-files.txt\n'
1477     txt += ' cat processed-files.txt | sort | uniq > tmp.txt\n'
1478     txt += ' mv tmp.txt processed-files.txt\n'
1479     txt += ' echo "----------------------"\n'
1480     txt += ' echo "cat processed-files.txt"\n'
1481     txt += ' echo "----------------------"\n'
1482     txt += ' cat processed-files.txt\n'
1483     txt += ' echo "----------------------"\n'
1484     txt += ' diff -q input-files.txt processed-files.txt\n'
1485     txt += ' fileverify_status=$?\n'
1486     txt += ' if [ $fileverify_status -ne 0 ]; then\n'
1487     txt += ' executable_exit_status=30001\n'
1488     txt += ' echo "ERROR ==> not all input files processed"\n'
1489     txt += ' echo " ==> list of processed files from crab_fjr.xml differs from list in pset.cfg"\n'
1490     txt += ' echo " ==> diff input-files.txt processed-files.txt"\n'
1491     txt += ' fi\n'
1492 spiga 1.232 txt += ' elif [ $executable_exit_status -ne 0 ] || [ $executable_exit_status -ne 50015 ] || [ $executable_exit_status -ne 50017 ];then\n'
1493     txt += ' echo ">>> Executable failed $executable_exit_status"\n'
1494 spiga 1.251 txt += ' echo "ExeExitCode=$executable_exit_status" | tee -a $RUNTIME_AREA/$repo\n'
1495     txt += ' echo "EXECUTABLE_EXIT_STATUS = $executable_exit_status"\n'
1496     txt += ' job_exit_code=$executable_exit_status\n'
1497 spiga 1.232 txt += ' func_exit\n'
1498     txt += ' fi\n'
1499     txt += '\n'
1500 spiga 1.189 txt += 'else\n'
1501     txt += ' echo "CRAB FrameworkJobReport crab_fjr.xml is not available, using exit code of executable from command line."\n'
1502     txt += 'fi\n'
1503     txt += '\n'
1504     txt += 'echo "ExeExitCode=$executable_exit_status" | tee -a $RUNTIME_AREA/$repo\n'
1505     txt += 'echo "EXECUTABLE_EXIT_STATUS = $executable_exit_status"\n'
1506     txt += 'job_exit_code=$executable_exit_status\n'
1507    
1508     return txt
1509    
1510 gutsche 1.5 def setParam_(self, param, value):
1511     self._params[param] = value
1512    
1513     def getParams(self):
1514     return self._params
1515 gutsche 1.8
1516 gutsche 1.35 def uniquelist(self, old):
1517     """
1518     remove duplicates from a list
1519     """
1520     nd={}
1521     for e in old:
1522     nd[e]=0
1523     return nd.keys()
1524 mcinquil 1.121
1525 spiga 1.257 def outList(self,list=False):
1526 mcinquil 1.121 """
1527     check the dimension of the output files
1528     """
1529 spiga 1.169 txt = ''
1530     txt += 'echo ">>> list of expected files on output sandbox"\n'
1531 mcinquil 1.121 listOutFiles = []
1532 ewv 1.170 stdout = 'CMSSW_$NJob.stdout'
1533 spiga 1.169 stderr = 'CMSSW_$NJob.stderr'
1534 fanzago 1.148 if (self.return_data == 1):
1535 spiga 1.157 for file in (self.output_file+self.output_file_sandbox):
1536 slacapra 1.207 listOutFiles.append(numberFile(file, '$NJob'))
1537 spiga 1.169 listOutFiles.append(stdout)
1538     listOutFiles.append(stderr)
1539 ewv 1.156 else:
1540 spiga 1.157 for file in (self.output_file_sandbox):
1541 slacapra 1.207 listOutFiles.append(numberFile(file, '$NJob'))
1542 spiga 1.169 listOutFiles.append(stdout)
1543     listOutFiles.append(stderr)
1544 fanzago 1.161 txt += 'echo "output files: '+string.join(listOutFiles,' ')+'"\n'
1545 spiga 1.157 txt += 'filesToCheck="'+string.join(listOutFiles,' ')+'"\n'
1546 spiga 1.169 txt += 'export filesToCheck\n'
1547 spiga 1.257 if list : return self.output_file
1548 ewv 1.170 return txt