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" : 0.1
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  if len( [step for step in s[3] if "HARVESTGEN" in step] )>0:
195  chainDict['TimePerEvent']=0.01
196  thisLabel=thisLabel+"_gen"
197  processStrPrefix=''
198  setPrimaryDs=None
199  for step in s[3]:
200 
201  if 'INPUT' in step or (not isinstance(s[2][index],str)):
202  nextHasDSInput=s[2][index]
203 
204  else:
205 
206  if (index==0):
207  #first step and not input -> gen part
208  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultScratch))
209  try:
210  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
211  except:
212  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
213  return -15
214 
215  chainDict['nowmTasklist'][-1]['PrimaryDataset']='RelVal'+s[1].split('+')[0]
216  if not '--relval' in s[2][index]:
217  print 'Impossible to create task from scratch without splitting information with --relval'
218  return -12
219  else:
220  arg=s[2][index].split()
221  ns=map(int,arg[arg.index('--relval')+1].split(','))
222  chainDict['nowmTasklist'][-1]['RequestNumEvents'] = ns[0]
223  chainDict['nowmTasklist'][-1]['EventsPerJob'] = ns[1]
224  if 'FASTSIM' in s[2][index] or '--fast' in s[2][index]:
225  thisLabel+='_FastSim'
226  if 'lhe' in s[2][index] in s[2][index]:
227  chainDict['nowmTasklist'][-1]['LheInputFiles'] =True
228 
229  elif nextHasDSInput:
230  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultInput))
231  try:
232  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
233  except:
234  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
235  return -15
236  chainDict['nowmTasklist'][-1]['InputDataset']=nextHasDSInput.dataSet
237  splitForThisWf=nextHasDSInput.split
238  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
239  if step in wmsplit:
240  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
241  # get the run numbers or #events
242  if len(nextHasDSInput.run):
243  chainDict['nowmTasklist'][-1]['RunWhitelist']=nextHasDSInput.run
244  #print "what is s",s[2][index]
245  if '--data' in s[2][index] and nextHasDSInput.label:
246  thisLabel+='_RelVal_%s'%nextHasDSInput.label
247  if 'filter' in chainDict['nowmTasklist'][-1]['nowmIO']:
248  print "This has an input DS and a filter sequence: very likely to be the PyQuen sample"
249  processStrPrefix='PU_'
250  setPrimaryDs = 'RelVal'+s[1].split('+')[0]
251  if setPrimaryDs:
252  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
253  nextHasDSInput=None
254  else:
255  #not first step and no inputDS
256  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultTask))
257  try:
258  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
259  except:
260  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
261  return -15
262  if splitForThisWf:
263  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
264  if step in wmsplit:
265  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
266 
267  #print step
268  chainDict['nowmTasklist'][-1]['TaskName']=step
269  if setPrimaryDs:
270  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
271  chainDict['nowmTasklist'][-1]['ConfigCacheID']='%s/%s.py'%(dir,step)
272  chainDict['nowmTasklist'][-1]['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] # copy to the proper parameter name
273  chainDict['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] #set in general to the last one of the chain
274  if 'pileup' in chainDict['nowmTasklist'][-1]['nowmIO']:
275  chainDict['nowmTasklist'][-1]['MCPileup']=chainDict['nowmTasklist'][-1]['nowmIO']['pileup']
276  if '--pileup ' in s[2][index]: # catch --pileup (scenarion) and not --pileup_ (dataset to be mixed) => works also making PRE-MIXed dataset
277  processStrPrefix='PU_' # take care of pu overlay done with GEN-SIM mixing
278  if ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('25ns') > 0 :
279  processStrPrefix='PU25ns_'
280  elif ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('50ns') > 0 :
281  processStrPrefix='PU50ns_'
282  if 'DIGIPREMIX_S2' in s[2][index] : # take care of pu overlay done with DIGI mixing of premixed events
283  if s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('25ns') > 0 :
284  processStrPrefix='PUpmx25ns_'
285  elif s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('50ns') > 0 :
286  processStrPrefix='PUpmx50ns_'
287 
288  if acqEra:
289  #chainDict['AcquisitionEra'][step]=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
290  chainDict['AcquisitionEra'][step]=chainDict['CMSSWVersion']
291  chainDict['ProcessingString'][step]=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
292  else:
293  #chainDict['nowmTasklist'][-1]['AcquisitionEra']=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
294  chainDict['nowmTasklist'][-1]['AcquisitionEra']=chainDict['CMSSWVersion']
295  chainDict['nowmTasklist'][-1]['ProcessingString']=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
296 
297  index+=1
298  #end of loop through steps
299  chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
300  if processStrPrefix or thisLabel:
301  chainDict['RequestString']+='_'+processStrPrefix+thisLabel
302 
303 
304 
305  #wrap up for this one
306  import pprint
307  #print 'wrapping up'
308  #pprint.pprint(chainDict)
309  #loop on the task list
310  for i_second in reversed(range(len(chainDict['nowmTasklist']))):
311  t_second=chainDict['nowmTasklist'][i_second]
312  #print "t_second taskname", t_second['TaskName']
313  if 'primary' in t_second['nowmIO']:
314  #print t_second['nowmIO']['primary']
315  primary=t_second['nowmIO']['primary'][0].replace('file:','')
316  for i_input in reversed(range(0,i_second)):
317  t_input=chainDict['nowmTasklist'][i_input]
318  for (om,o) in t_input['nowmIO'].items():
319  if primary in o:
320  #print "found",primary,"procuced by",om,"of",t_input['TaskName']
321  t_second['InputTask'] = t_input['TaskName']
322  t_second['InputFromOutputModule'] = om
323  #print 't_second',pprint.pformat(t_second)
324  if t_second['TaskName'].startswith('HARVEST'):
325  chainDict.update(copy.deepcopy(self.defaultHarvest))
326  chainDict['DQMConfigCacheID']=t_second['ConfigCacheID']
327  ## the info are not in the task specific dict but in the general dict
328  #t_input.update(copy.deepcopy(self.defaultHarvest))
329  #t_input['DQMConfigCacheID']=t_second['ConfigCacheID']
330  break
331 
332  ## there is in fact only one acquisition era
333  #if len(set(chainDict['AcquisitionEra'].values()))==1:
334  # print "setting only one acq"
335  if acqEra:
336  chainDict['AcquisitionEra'] = chainDict['AcquisitionEra'].values()[0]
337 
338  ## clean things up now
339  itask=0
340  if self.keep:
341  for i in self.keep:
342  if type(i)==int and i < len(chainDict['nowmTasklist']):
343  chainDict['nowmTasklist'][i]['KeepOutput']=True
344  for (i,t) in enumerate(chainDict['nowmTasklist']):
345  if t['TaskName'].startswith('HARVEST'):
346  continue
347  if not self.keep:
348  t['KeepOutput']=True
349  elif t['TaskName'] in self.keep:
350  t['KeepOutput']=True
351  t.pop('nowmIO')
352  itask+=1
353  chainDict['Task%d'%(itask)]=t
354 
355 
356  ##
357 
358 
359  ## provide the number of tasks
360  chainDict['TaskChain']=itask#len(chainDict['nowmTasklist'])
361 
362  chainDict.pop('nowmTasklist')
363  self.chainDicts[n]=chainDict
364 
365 
366  return 0
367 
368  def uploadConf(self,filePath,label,where):
369  labelInCouch=self.label+'_'+label
370  cacheName=filePath.split('/')[-1]
371  if self.testMode:
372  self.count+=1
373  print '\tFake upload of',filePath,'to couch with label',labelInCouch
374  return self.count
375  else:
376  try:
377  from modules.wma import upload_to_couch,DATABASE_NAME
378  except:
379  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
380  print '\n\t QUIT\n'
381  sys.exit(-16)
382 
383  if cacheName in self.couchCache:
384  print "Not re-uploading",filePath,"to",where,"for",label
385  cacheId=self.couchCache[cacheName]
386  else:
387  print "Loading",filePath,"to",where,"for",label
388  ## totally fork the upload to couch to prevent cross loading of process configurations
389  pool = multiprocessing.Pool(1)
390  cacheIds = pool.map( upload_to_couch_oneArg, [(filePath,labelInCouch,self.user,self.group,where)] )
391  cacheId = cacheIds[0]
392  self.couchCache[cacheName]=cacheId
393  return cacheId
394 
395  def upload(self):
396  for (n,d) in self.chainDicts.items():
397  for it in d:
398  if it.startswith("Task") and it!='TaskChain':
399  #upload
400  couchID=self.uploadConf(d[it]['ConfigCacheID'],
401  str(n)+d[it]['TaskName'],
402  d['CouchURL']
403  )
404  print d[it]['ConfigCacheID']," uploaded to couchDB for",str(n),"with ID",couchID
405  d[it]['ConfigCacheID']=couchID
406  if it =='DQMConfigCacheID':
407  couchID=self.uploadConf(d['DQMConfigCacheID'],
408  str(n)+'harvesting',
409  d['CouchURL']
410  )
411  print d['DQMConfigCacheID'],"uploaded to couchDB for",str(n),"with ID",couchID
412  d['DQMConfigCacheID']=couchID
413 
414 
415  def submit(self):
416  try:
417  from modules.wma import makeRequest,approveRequest
418  from wmcontrol import random_sleep
419  print '\n\tFound wmcontrol\n'
420  except:
421  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
422  if not self.testMode:
423  print '\n\t QUIT\n'
424  sys.exit(-17)
425 
426  import pprint
427  for (n,d) in self.chainDicts.items():
428  if self.testMode:
429  print "Only viewing request",n
430  print pprint.pprint(d)
431  else:
432  #submit to wmagent each dict
433  print "For eyes before submitting",n
434  print pprint.pprint(d)
435  print "Submitting",n,"..........."
436  workFlow=makeRequest(self.wmagent,d,encodeDict=True)
437  approveRequest(self.wmagent,workFlow)
438  print "...........",n,"submitted"
439  random_sleep()
440 
441 
442 
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