ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/cms_cmssw.py
Revision: 1.264
Committed: Tue Dec 16 14:23:07 2008 UTC (16 years, 4 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
Changes since 1.263: +6 -0 lines
Log Message:
Raise exception if no location is found for any blocks

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