CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
MatrixInjector.py
Go to the documentation of this file.
1 import sys
2 import json
3 import os
4 import copy
5 import multiprocessing
6 
8  if opt.show:
9  print 'Not injecting to wmagent in --show mode. Need to run the worklfows.'
10  sys.exit(-1)
11  if opt.wmcontrol=='init':
12  #init means it'll be in test mode
13  opt.nThreads=0
14  if opt.wmcontrol=='test':
15  #means the wf were created already, and we just dryRun it.
16  opt.dryRun=True
17  if opt.wmcontrol=='submit' and opt.nThreads==0:
18  print 'Not injecting to wmagent in -j 0 mode. Need to run the worklfows.'
19  sys.exit(-1)
20  if opt.wmcontrol=='force':
21  print "This is an expert setting, you'd better know what you're doing"
22  opt.dryRun=True
23 
24 def upload_to_couch_oneArg(arguments):
25  from modules.wma import upload_to_couch
26  (filePath,labelInCouch,user,group,where) = arguments
27  cacheId=upload_to_couch(filePath,
28  labelInCouch,
29  user,
30  group,
31  test_mode=False,
32  url=where)
33  return cacheId
34 
35 
37 
38  def __init__(self,opt,mode='init',options=''):
39  self.count=1040
40 
41  self.dqmgui=None
42  self.wmagent=None
43  for k in options.split(','):
44  if k.startswith('dqm:'):
45  self.dqmgui=k.split(':',1)[-1]
46  elif k.startswith('wma:'):
47  self.wmagent=k.split(':',1)[-1]
48 
49  self.testMode=((mode!='submit') and (mode!='force'))
50  self.version =1
51  self.keep = opt.keep
52 
53  #wagemt stuff
54  if not self.wmagent:
55  self.wmagent=os.getenv('WMAGENT_REQMGR')
56  if not self.wmagent:
57  self.wmagent = 'cmsweb.cern.ch'
58 
59  if not self.dqmgui:
60  self.dqmgui="https://cmsweb.cern.ch/dqm/relval"
61  #couch stuff
62  self.couch = 'https://'+self.wmagent+'/couchdb'
63 # self.couchDB = 'reqmgr_config_cache'
64  self.couchCache={} # so that we do not upload like crazy, and recyle cfgs
65  self.user = os.getenv('USER')
66  self.group = 'ppd'
67  self.label = 'RelValSet_'+os.getenv('CMSSW_VERSION').replace('-','')+'_v'+str(self.version)
68  self.speciallabel=''
69  if opt.label:
70  self.speciallabel= '_'+opt.label
71 
72 
73  if not os.getenv('WMCORE_ROOT'):
74  print '\n\twmclient is not setup properly. Will not be able to upload or submit requests.\n'
75  if not self.testMode:
76  print '\n\t QUIT\n'
77  sys.exit(-18)
78  else:
79  print '\n\tFound wmclient\n'
80 
81  self.defaultChain={
82  "RequestType" : "TaskChain", #this is how we handle relvals
83  "SubRequestType" : "RelVal", #this is how we handle relvals, now that TaskChain is also used for central MC production
84  "RequestPriority": 999999,
85  "Requestor": self.user, #Person responsible
86  "Group": self.group, #group for the request
87  "CMSSWVersion": os.getenv('CMSSW_VERSION'), #CMSSW Version (used for all tasks in chain)
88  "Campaign": os.getenv('CMSSW_VERSION'), # only for wmstat purpose
89  "ScramArch": os.getenv('SCRAM_ARCH'), #Scram Arch (used for all tasks in chain)
90  "ProcessingVersion": self.version, #Processing Version (used for all tasks in chain)
91  "GlobalTag": None, #Global Tag (overridden per task)
92  "CouchURL": self.couch, #URL of CouchDB containing Config Cache
93  "ConfigCacheURL": self.couch, #URL of CouchDB containing Config Cache
94  "DbsUrl": "https://cmsweb.cern.ch/dbs/prod/global/DBSReader",
95  #- Will contain all configs for all Tasks
96  #"SiteWhitelist" : ["T2_CH_CERN", "T1_US_FNAL"], #Site whitelist
97  "TaskChain" : None, #Define number of tasks in chain.
98  "nowmTasklist" : [], #a list of tasks as we put them in
99  "unmergedLFNBase" : "/store/unmerged",
100  "mergedLFNBase" : "/store/relval",
101  "dashboardActivity" : "relval",
102  "Memory" : 2400,
103  "SizePerEvent" : 1234,
104  "TimePerEvent" : 20
105  }
106 
108  "EnableHarvesting" : "True",
109  "DQMUploadUrl" : self.dqmgui,
110  "DQMConfigCacheID" : None
111  }
112 
114  "TaskName" : None, #Task Name
115  "ConfigCacheID" : None, #Generator Config id
116  "GlobalTag": None,
117  "SplittingAlgo" : "EventBased", #Splitting Algorithm
118  "EventsPerJob" : None, #Size of jobs in terms of splitting algorithm
119  "RequestNumEvents" : None, #Total number of events to generate
120  "Seeding" : "AutomaticSeeding", #Random seeding method
121  "PrimaryDataset" : None, #Primary Dataset to be created
122  "nowmIO": {},
123  "KeepOutput" : False
124  }
126  "TaskName" : "DigiHLT", #Task Name
127  "ConfigCacheID" : None, #Processing Config id
128  "GlobalTag": None,
129  "InputDataset" : None, #Input Dataset to be processed
130  "SplittingAlgo" : "LumiBased", #Splitting Algorithm
131  "LumisPerJob" : 10, #Size of jobs in terms of splitting algorithm
132  "nowmIO": {},
133  "KeepOutput" : False
134  }
135  self.defaultTask={
136  "TaskName" : None, #Task Name
137  "InputTask" : None, #Input Task Name (Task Name field of a previous Task entry)
138  "InputFromOutputModule" : None, #OutputModule name in the input task that will provide files to process
139  "ConfigCacheID" : None, #Processing Config id
140  "GlobalTag": None,
141  "SplittingAlgo" : "LumiBased", #Splitting Algorithm
142  "LumisPerJob" : 10, #Size of jobs in terms of splitting algorithm
143  "nowmIO": {},
144  "KeepOutput" : False
145  }
146 
147  self.chainDicts={}
148 
149 
150  def prepare(self,mReader, directories, mode='init'):
151  try:
152  #from Configuration.PyReleaseValidation.relval_steps import wmsplit
153  wmsplit = {}
154  wmsplit['DIGIHI']=5
155  wmsplit['RECOHI']=5
156  wmsplit['HLTD']=5
157  wmsplit['RECODreHLT']=2
158  wmsplit['DIGIPU']=4
159  wmsplit['DIGIPU1']=4
160  wmsplit['RECOPU1']=1
161  wmsplit['DIGIUP15_PU50']=1
162  wmsplit['RECOUP15_PU50']=1
163  wmsplit['DIGIUP15_PU25']=1
164  wmsplit['RECOUP15_PU25']=1
165  wmsplit['DIGIHISt3']=5
166  wmsplit['RECODSplit']=1
167  wmsplit['SingleMuPt10_ID']=1
168  wmsplit['DIGI_ID']=1
169  wmsplit['RECO_ID']=1
170  wmsplit['TTbar_ID']=1
171  wmsplit['SingleMuPt10FS_ID']=1
172  wmsplit['TTbarFS_ID']=1
173 
174  #import pprint
175  #pprint.pprint(wmsplit)
176  except:
177  print "Not set up for step splitting"
178  wmsplit={}
179 
180  acqEra=False
181  for (n,dir) in directories.items():
182  chainDict=copy.deepcopy(self.defaultChain)
183  print "inspecting",dir
184  nextHasDSInput=None
185  for (x,s) in mReader.workFlowSteps.items():
186  #x has the format (num, prefix)
187  #s has the format (num, name, commands, stepList)
188  if x[0]==n:
189  #print "found",n,s[3]
190  #chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
191  index=0
192  splitForThisWf=None
193  thisLabel=self.speciallabel
194  processStrPrefix=''
195  setPrimaryDs=None
196  for step in s[3]:
197 
198  if 'INPUT' in step or (not isinstance(s[2][index],str)):
199  nextHasDSInput=s[2][index]
200 
201  else:
202 
203  if (index==0):
204  #first step and not input -> gen part
205  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultScratch))
206  try:
207  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
208  except:
209  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
210  return -15
211 
212  chainDict['nowmTasklist'][-1]['PrimaryDataset']='RelVal'+s[1].split('+')[0]
213  if not '--relval' in s[2][index]:
214  print 'Impossible to create task from scratch without splitting information with --relval'
215  return -12
216  else:
217  arg=s[2][index].split()
218  ns=map(int,arg[arg.index('--relval')+1].split(','))
219  chainDict['nowmTasklist'][-1]['RequestNumEvents'] = ns[0]
220  chainDict['nowmTasklist'][-1]['EventsPerJob'] = ns[1]
221  if 'FASTSIM' in s[2][index] or '--fast' in s[2][index]:
222  thisLabel+='_FastSim'
223  if 'lhe' in s[2][index] in s[2][index]:
224  chainDict['nowmTasklist'][-1]['LheInputFiles'] =True
225 
226  elif nextHasDSInput:
227  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultInput))
228  try:
229  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
230  except:
231  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
232  return -15
233  chainDict['nowmTasklist'][-1]['InputDataset']=nextHasDSInput.dataSet
234  splitForThisWf=nextHasDSInput.split
235  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
236  if step in wmsplit:
237  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
238  # get the run numbers or #events
239  if len(nextHasDSInput.run):
240  chainDict['nowmTasklist'][-1]['RunWhitelist']=nextHasDSInput.run
241  #print "what is s",s[2][index]
242  if '--data' in s[2][index] and nextHasDSInput.label:
243  thisLabel+='_RelVal_%s'%nextHasDSInput.label
244  if 'filter' in chainDict['nowmTasklist'][-1]['nowmIO']:
245  print "This has an input DS and a filter sequence: very likely to be the PyQuen sample"
246  processStrPrefix='PU_'
247  setPrimaryDs = 'RelVal'+s[1].split('+')[0]
248  if setPrimaryDs:
249  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
250  nextHasDSInput=None
251  else:
252  #not first step and no inputDS
253  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultTask))
254  try:
255  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
256  except:
257  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
258  return -15
259  if splitForThisWf:
260  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
261  if step in wmsplit:
262  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
263 
264  #print step
265  chainDict['nowmTasklist'][-1]['TaskName']=step
266  if setPrimaryDs:
267  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
268  chainDict['nowmTasklist'][-1]['ConfigCacheID']='%s/%s.py'%(dir,step)
269  chainDict['nowmTasklist'][-1]['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] # copy to the proper parameter name
270  chainDict['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] #set in general to the last one of the chain
271  if 'pileup' in chainDict['nowmTasklist'][-1]['nowmIO']:
272  chainDict['nowmTasklist'][-1]['MCPileup']=chainDict['nowmTasklist'][-1]['nowmIO']['pileup']
273  if '--pileup ' in s[2][index]: # catch --pileup (scenarion) and not --pileup_ (dataset to be mixed) => works also making PRE-MIXed dataset
274  processStrPrefix='PU_' # take care of pu overlay done with GEN-SIM mixing
275  if ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('25ns') > 0 :
276  processStrPrefix='PU25ns_'
277  elif ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('50ns') > 0 :
278  processStrPrefix='PU50ns_'
279  if 'DIGIPREMIX_S2' in s[2][index] : # take care of pu overlay done with DIGI mixing of premixed events
280  if s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('25ns') > 0 :
281  processStrPrefix='PUpmx25ns_'
282  elif s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('50ns') > 0 :
283  processStrPrefix='PUpmx50ns_'
284 
285  if acqEra:
286  #chainDict['AcquisitionEra'][step]=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
287  chainDict['AcquisitionEra'][step]=chainDict['CMSSWVersion']
288  chainDict['ProcessingString'][step]=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
289  else:
290  #chainDict['nowmTasklist'][-1]['AcquisitionEra']=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
291  chainDict['nowmTasklist'][-1]['AcquisitionEra']=chainDict['CMSSWVersion']
292  chainDict['nowmTasklist'][-1]['ProcessingString']=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
293 
294  index+=1
295  #end of loop through steps
296  chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
297  if processStrPrefix or thisLabel:
298  chainDict['RequestString']+='_'+processStrPrefix+thisLabel
299 
300 
301 
302  #wrap up for this one
303  import pprint
304  #print 'wrapping up'
305  #pprint.pprint(chainDict)
306  #loop on the task list
307  for i_second in reversed(range(len(chainDict['nowmTasklist']))):
308  t_second=chainDict['nowmTasklist'][i_second]
309  #print "t_second taskname", t_second['TaskName']
310  if 'primary' in t_second['nowmIO']:
311  #print t_second['nowmIO']['primary']
312  primary=t_second['nowmIO']['primary'][0].replace('file:','')
313  for i_input in reversed(range(0,i_second)):
314  t_input=chainDict['nowmTasklist'][i_input]
315  for (om,o) in t_input['nowmIO'].items():
316  if primary in o:
317  #print "found",primary,"procuced by",om,"of",t_input['TaskName']
318  t_second['InputTask'] = t_input['TaskName']
319  t_second['InputFromOutputModule'] = om
320  #print 't_second',pprint.pformat(t_second)
321  if t_second['TaskName'].startswith('HARVEST'):
322  chainDict.update(copy.deepcopy(self.defaultHarvest))
323  chainDict['DQMConfigCacheID']=t_second['ConfigCacheID']
324  ## the info are not in the task specific dict but in the general dict
325  #t_input.update(copy.deepcopy(self.defaultHarvest))
326  #t_input['DQMConfigCacheID']=t_second['ConfigCacheID']
327  break
328 
329  ## there is in fact only one acquisition era
330  #if len(set(chainDict['AcquisitionEra'].values()))==1:
331  # print "setting only one acq"
332  if acqEra:
333  chainDict['AcquisitionEra'] = chainDict['AcquisitionEra'].values()[0]
334 
335  ## clean things up now
336  itask=0
337  if self.keep:
338  for i in self.keep:
339  if type(i)==int and i < len(chainDict['nowmTasklist']):
340  chainDict['nowmTasklist'][i]['KeepOutput']=True
341  for (i,t) in enumerate(chainDict['nowmTasklist']):
342  if t['TaskName'].startswith('HARVEST'):
343  continue
344  if not self.keep:
345  t['KeepOutput']=True
346  elif t['TaskName'] in self.keep:
347  t['KeepOutput']=True
348  t.pop('nowmIO')
349  itask+=1
350  chainDict['Task%d'%(itask)]=t
351 
352 
353  ##
354 
355 
356  ## provide the number of tasks
357  chainDict['TaskChain']=itask#len(chainDict['nowmTasklist'])
358 
359  chainDict.pop('nowmTasklist')
360  self.chainDicts[n]=chainDict
361 
362 
363  return 0
364 
365  def uploadConf(self,filePath,label,where):
366  labelInCouch=self.label+'_'+label
367  cacheName=filePath.split('/')[-1]
368  if self.testMode:
369  self.count+=1
370  print '\tFake upload of',filePath,'to couch with label',labelInCouch
371  return self.count
372  else:
373  try:
374  from modules.wma import upload_to_couch,DATABASE_NAME
375  except:
376  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
377  print '\n\t QUIT\n'
378  sys.exit(-16)
379 
380  if cacheName in self.couchCache:
381  print "Not re-uploading",filePath,"to",where,"for",label
382  cacheId=self.couchCache[cacheName]
383  else:
384  print "Loading",filePath,"to",where,"for",label
385  ## totally fork the upload to couch to prevent cross loading of process configurations
386  pool = multiprocessing.Pool(1)
387  cacheIds = pool.map( upload_to_couch_oneArg, [(filePath,labelInCouch,self.user,self.group,where)] )
388  cacheId = cacheIds[0]
389  self.couchCache[cacheName]=cacheId
390  return cacheId
391 
392  def upload(self):
393  for (n,d) in self.chainDicts.items():
394  for it in d:
395  if it.startswith("Task") and it!='TaskChain':
396  #upload
397  couchID=self.uploadConf(d[it]['ConfigCacheID'],
398  str(n)+d[it]['TaskName'],
399  d['CouchURL']
400  )
401  print d[it]['ConfigCacheID']," uploaded to couchDB for",str(n),"with ID",couchID
402  d[it]['ConfigCacheID']=couchID
403  if it =='DQMConfigCacheID':
404  couchID=self.uploadConf(d['DQMConfigCacheID'],
405  str(n)+'harvesting',
406  d['CouchURL']
407  )
408  print d['DQMConfigCacheID'],"uploaded to couchDB for",str(n),"with ID",couchID
409  d['DQMConfigCacheID']=couchID
410 
411 
412  def submit(self):
413  try:
414  from modules.wma import makeRequest,approveRequest
415  from wmcontrol import random_sleep
416  print '\n\tFound wmcontrol\n'
417  except:
418  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
419  if not self.testMode:
420  print '\n\t QUIT\n'
421  sys.exit(-17)
422 
423  import pprint
424  for (n,d) in self.chainDicts.items():
425  if self.testMode:
426  print "Only viewing request",n
427  print pprint.pprint(d)
428  else:
429  #submit to wmagent each dict
430  print "For eyes before submitting",n
431  print pprint.pprint(d)
432  print "Submitting",n,"..........."
433  workFlow=makeRequest(self.wmagent,d,encodeDict=True)
434  approveRequest(self.wmagent,workFlow)
435  print "...........",n,"submitted"
436  random_sleep()
437 
438 
439 
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:7
list object
Definition: dbtoconf.py:77
def performInjectionOptionTest
def upload_to_couch_oneArg
double split
Definition: MVATrainer.cc:139