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.nProcs=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.nProcs==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 
36 class MatrixInjector(object):
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  if not opt.testbed :
58  self.wmagent = 'cmsweb.cern.ch'
59  self.DbsUrl = "https://"+self.wmagent+"/dbs/prod/global/DBSReader"
60  else :
61  self.wmagent = 'cmsweb-testbed.cern.ch'
62  self.DbsUrl = "https://"+self.wmagent+"/dbs/int/global/DBSReader"
63 
64  if not self.dqmgui:
65  self.dqmgui="https://cmsweb.cern.ch/dqm/relval"
66  #couch stuff
67  self.couch = 'https://'+self.wmagent+'/couchdb'
68 # self.couchDB = 'reqmgr_config_cache'
69  self.couchCache={} # so that we do not upload like crazy, and recyle cfgs
70  self.user = os.getenv('USER')
71  self.group = 'ppd'
72  self.label = 'RelValSet_'+os.getenv('CMSSW_VERSION').replace('-','')+'_v'+str(self.version)
73  self.speciallabel=''
74  if opt.label:
75  self.speciallabel= '_'+opt.label
76 
77 
78  if not os.getenv('WMCORE_ROOT'):
79  print '\n\twmclient is not setup properly. Will not be able to upload or submit requests.\n'
80  if not self.testMode:
81  print '\n\t QUIT\n'
82  sys.exit(-18)
83  else:
84  print '\n\tFound wmclient\n'
85 
86  self.defaultChain={
87  "RequestType" : "TaskChain", #this is how we handle relvals
88  "SubRequestType" : "RelVal", #this is how we handle relvals, now that TaskChain is also used for central MC production
89  "RequestPriority": 500000,
90  "Requestor": self.user, #Person responsible
91  "Group": self.group, #group for the request
92  "CMSSWVersion": os.getenv('CMSSW_VERSION'), #CMSSW Version (used for all tasks in chain)
93  "Campaign": os.getenv('CMSSW_VERSION'), # only for wmstat purpose
94  "ScramArch": os.getenv('SCRAM_ARCH'), #Scram Arch (used for all tasks in chain)
95  "ProcessingVersion": self.version, #Processing Version (used for all tasks in chain)
96  "GlobalTag": None, #Global Tag (overridden per task)
97  "CouchURL": self.couch, #URL of CouchDB containing Config Cache
98  "ConfigCacheURL": self.couch, #URL of CouchDB containing Config Cache
99  "DbsUrl": self.DbsUrl,
100  #- Will contain all configs for all Tasks
101  #"SiteWhitelist" : ["T2_CH_CERN", "T1_US_FNAL"], #Site whitelist
102  "TaskChain" : None, #Define number of tasks in chain.
103  "nowmTasklist" : [], #a list of tasks as we put them in
104  "unmergedLFNBase" : "/store/unmerged",
105  "mergedLFNBase" : "/store/relval",
106  "dashboardActivity" : "relval",
107  "Multicore" : 1, # do not set multicore for the whole chain
108  "Memory" : 3000,
109  "SizePerEvent" : 1234,
110  "TimePerEvent" : 0.1
111  }
112 
114  "EnableHarvesting" : "True",
115  "DQMUploadUrl" : self.dqmgui,
116  "DQMConfigCacheID" : None,
117  "Multicore" : 1 # hardcode Multicore to be 1 for Harvest
118  }
119 
121  "TaskName" : None, #Task Name
122  "ConfigCacheID" : None, #Generator Config id
123  "GlobalTag": None,
124  "SplittingAlgo" : "EventBased", #Splitting Algorithm
125  "EventsPerJob" : None, #Size of jobs in terms of splitting algorithm
126  "RequestNumEvents" : None, #Total number of events to generate
127  "Seeding" : "AutomaticSeeding", #Random seeding method
128  "PrimaryDataset" : None, #Primary Dataset to be created
129  "nowmIO": {},
130  "Multicore" : opt.nThreads, # this is the per-taskchain Multicore; it's the default assigned to a task if it has no value specified
131  "KeepOutput" : False
132  }
134  "TaskName" : "DigiHLT", #Task Name
135  "ConfigCacheID" : None, #Processing Config id
136  "GlobalTag": None,
137  "InputDataset" : None, #Input Dataset to be processed
138  "SplittingAlgo" : "LumiBased", #Splitting Algorithm
139  "LumisPerJob" : 10, #Size of jobs in terms of splitting algorithm
140  "nowmIO": {},
141  "Multicore" : opt.nThreads, # this is the per-taskchain Multicore; it's the default assigned to a task if it has no value specified
142  "KeepOutput" : False
143  }
144  self.defaultTask={
145  "TaskName" : None, #Task Name
146  "InputTask" : None, #Input Task Name (Task Name field of a previous Task entry)
147  "InputFromOutputModule" : None, #OutputModule name in the input task that will provide files to process
148  "ConfigCacheID" : None, #Processing Config id
149  "GlobalTag": None,
150  "SplittingAlgo" : "LumiBased", #Splitting Algorithm
151  "LumisPerJob" : 10, #Size of jobs in terms of splitting algorithm
152  "nowmIO": {},
153  "Multicore" : opt.nThreads, # this is the per-taskchain Multicore; it's the default assigned to a task if it has no value specified
154  "KeepOutput" : False
155  }
156 
157  self.chainDicts={}
158 
159 
160  def prepare(self,mReader, directories, mode='init'):
161  try:
162  #from Configuration.PyReleaseValidation.relval_steps import wmsplit
163  wmsplit = {}
164  wmsplit['DIGIHI']=5
165  wmsplit['RECOHI']=5
166  wmsplit['HLTD']=5
167  wmsplit['RECODreHLT']=2
168  wmsplit['DIGIPU']=4
169  wmsplit['DIGIPU1']=4
170  wmsplit['RECOPU1']=1
171  wmsplit['DIGIUP15_PU50']=1
172  wmsplit['RECOUP15_PU50']=1
173  wmsplit['DIGIUP15_PU25']=1
174  wmsplit['RECOUP15_PU25']=1
175  wmsplit['DIGIUP15_PU25HS']=1
176  wmsplit['RECOUP15_PU25HS']=1
177  wmsplit['DIGIHIMIX']=5
178  wmsplit['RECOHIMIX']=5
179  wmsplit['RECODSplit']=1
180  wmsplit['SingleMuPt10_UP15_ID']=1
181  wmsplit['DIGIUP15_ID']=1
182  wmsplit['RECOUP15_ID']=1
183  wmsplit['TTbar_13_ID']=1
184  wmsplit['SingleMuPt10FS_ID']=1
185  wmsplit['TTbarFS_ID']=1
186  wmsplit['RECODR2_50nsreHLT']=1
187  wmsplit['RECODR2_25nsreHLT']=1
188  wmsplit['HLTDR2_50ns']=1
189  wmsplit['HLTDR2_25ns']=1
190  wmsplit['Hadronizer']=1
191  wmsplit['DIGIUP15']=5
192  wmsplit['RECOUP15']=5
193  wmsplit['RECOAODUP15']=5
194  wmsplit['DBLMINIAODMCUP15NODQM']=5
195 
196 
197  #import pprint
198  #pprint.pprint(wmsplit)
199  except:
200  print "Not set up for step splitting"
201  wmsplit={}
202 
203  acqEra=False
204  for (n,dir) in directories.items():
205  chainDict=copy.deepcopy(self.defaultChain)
206  print "inspecting",dir
207  nextHasDSInput=None
208  for (x,s) in mReader.workFlowSteps.items():
209  #x has the format (num, prefix)
210  #s has the format (num, name, commands, stepList)
211  if x[0]==n:
212  #print "found",n,s[3]
213  #chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
214  index=0
215  splitForThisWf=None
216  thisLabel=self.speciallabel
217  #if 'HARVESTGEN' in s[3]:
218  if len( [step for step in s[3] if "HARVESTGEN" in step] )>0:
219  chainDict['TimePerEvent']=0.01
220  thisLabel=thisLabel+"_gen"
221  # for double miniAOD test
222  if len( [step for step in s[3] if "DBLMINIAODMCUP15NODQM" in step] )>0:
223  thisLabel=thisLabel+"_dblMiniAOD"
224  processStrPrefix=''
225  setPrimaryDs=None
226  for step in s[3]:
227 
228  if 'INPUT' in step or (not isinstance(s[2][index],str)):
229  nextHasDSInput=s[2][index]
230 
231  else:
232 
233  if (index==0):
234  #first step and not input -> gen part
235  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultScratch))
236  try:
237  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
238  except:
239  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
240  return -15
241 
242  chainDict['nowmTasklist'][-1]['PrimaryDataset']='RelVal'+s[1].split('+')[0]
243  if not '--relval' in s[2][index]:
244  print 'Impossible to create task from scratch without splitting information with --relval'
245  return -12
246  else:
247  arg=s[2][index].split()
248  ns=map(int,arg[arg.index('--relval')+1].split(','))
249  chainDict['nowmTasklist'][-1]['RequestNumEvents'] = ns[0]
250  chainDict['nowmTasklist'][-1]['EventsPerJob'] = ns[1]
251  if 'FASTSIM' in s[2][index] or '--fast' in s[2][index]:
252  thisLabel+='_FastSim'
253  if 'lhe' in s[2][index] in s[2][index]:
254  chainDict['nowmTasklist'][-1]['LheInputFiles'] =True
255 
256  elif nextHasDSInput:
257  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultInput))
258  try:
259  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
260  except:
261  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
262  return -15
263  chainDict['nowmTasklist'][-1]['InputDataset']=nextHasDSInput.dataSet
264  splitForThisWf=nextHasDSInput.split
265  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
266  if step in wmsplit:
267  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
268  # get the run numbers or #events
269  if len(nextHasDSInput.run):
270  chainDict['nowmTasklist'][-1]['RunWhitelist']=nextHasDSInput.run
271  if len(nextHasDSInput.ls):
272  chainDict['nowmTasklist'][-1]['LumiList']=nextHasDSInput.ls
273  #print "what is s",s[2][index]
274  if '--data' in s[2][index] and nextHasDSInput.label:
275  thisLabel+='_RelVal_%s'%nextHasDSInput.label
276  if 'filter' in chainDict['nowmTasklist'][-1]['nowmIO']:
277  print "This has an input DS and a filter sequence: very likely to be the PyQuen sample"
278  processStrPrefix='PU_'
279  setPrimaryDs = 'RelVal'+s[1].split('+')[0]
280  if setPrimaryDs:
281  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
282  nextHasDSInput=None
283  else:
284  #not first step and no inputDS
285  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultTask))
286  try:
287  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
288  except:
289  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
290  return -15
291  if splitForThisWf:
292  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
293  if step in wmsplit:
294  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
295 
296  # change LumisPerJob for Hadronizer steps.
297  if 'Hadronizer' in step:
298  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit['Hadronizer']
299 
300  #print step
301  chainDict['nowmTasklist'][-1]['TaskName']=step
302  if setPrimaryDs:
303  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
304  chainDict['nowmTasklist'][-1]['ConfigCacheID']='%s/%s.py'%(dir,step)
305  chainDict['nowmTasklist'][-1]['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] # copy to the proper parameter name
306  chainDict['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] #set in general to the last one of the chain
307  if 'pileup' in chainDict['nowmTasklist'][-1]['nowmIO']:
308  chainDict['nowmTasklist'][-1]['MCPileup']=chainDict['nowmTasklist'][-1]['nowmIO']['pileup']
309  if '--pileup ' in s[2][index]: # catch --pileup (scenarion) and not --pileup_ (dataset to be mixed) => works also making PRE-MIXed dataset
310  processStrPrefix='PU_' # take care of pu overlay done with GEN-SIM mixing
311  if ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('25ns') > 0 :
312  processStrPrefix='PU25ns_'
313  elif ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('50ns') > 0 :
314  processStrPrefix='PU50ns_'
315  if 'DIGIPREMIX_S2' in s[2][index] : # take care of pu overlay done with DIGI mixing of premixed events
316  if s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('25ns') > 0 :
317  processStrPrefix='PUpmx25ns_'
318  elif s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('50ns') > 0 :
319  processStrPrefix='PUpmx50ns_'
320 
321  if acqEra:
322  #chainDict['AcquisitionEra'][step]=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
323  chainDict['AcquisitionEra'][step]=chainDict['CMSSWVersion']
324  chainDict['ProcessingString'][step]=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
325  else:
326  #chainDict['nowmTasklist'][-1]['AcquisitionEra']=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
327  chainDict['nowmTasklist'][-1]['AcquisitionEra']=chainDict['CMSSWVersion']
328  chainDict['nowmTasklist'][-1]['ProcessingString']=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
329 
330  # specify different ProcessingString for double miniAOD dataset
331  if ('DBLMINIAODMCUP15NODQM' in step):
332  chainDict['nowmTasklist'][-1]['ProcessingString']=chainDict['nowmTasklist'][-1]['ProcessingString']+'_miniAOD'
333 
334  if( chainDict['nowmTasklist'][-1]['Multicore'] ):
335  # the scaling factor of 1.2GB / thread is empirical and measured on a SECOND round of tests with PU samples
336  # the number of threads is NO LONGER assumed to be the same for all tasks
337  # https://hypernews.cern.ch/HyperNews/CMS/get/edmFramework/3509/1/1/1.html
338  # now change to 1.5GB / additional thread according to discussion:
339  # https://hypernews.cern.ch/HyperNews/CMS/get/relval/4817/1/1.html
340  chainDict['nowmTasklist'][-1]['Memory'] = 3000 + int( chainDict['nowmTasklist'][-1]['Multicore'] -1 )*1500
341 
342  index+=1
343  #end of loop through steps
344  chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
345  if processStrPrefix or thisLabel:
346  chainDict['RequestString']+='_'+processStrPrefix+thisLabel
347 
348 
349 
350  #wrap up for this one
351  import pprint
352  #print 'wrapping up'
353  #pprint.pprint(chainDict)
354  #loop on the task list
355  for i_second in reversed(range(len(chainDict['nowmTasklist']))):
356  t_second=chainDict['nowmTasklist'][i_second]
357  #print "t_second taskname", t_second['TaskName']
358  if 'primary' in t_second['nowmIO']:
359  #print t_second['nowmIO']['primary']
360  primary=t_second['nowmIO']['primary'][0].replace('file:','')
361  for i_input in reversed(range(0,i_second)):
362  t_input=chainDict['nowmTasklist'][i_input]
363  for (om,o) in t_input['nowmIO'].items():
364  if primary in o:
365  #print "found",primary,"procuced by",om,"of",t_input['TaskName']
366  t_second['InputTask'] = t_input['TaskName']
367  t_second['InputFromOutputModule'] = om
368  #print 't_second',pprint.pformat(t_second)
369  if t_second['TaskName'].startswith('HARVEST'):
370  chainDict.update(copy.deepcopy(self.defaultHarvest))
371  chainDict['DQMConfigCacheID']=t_second['ConfigCacheID']
372  ## the info are not in the task specific dict but in the general dict
373  #t_input.update(copy.deepcopy(self.defaultHarvest))
374  #t_input['DQMConfigCacheID']=t_second['ConfigCacheID']
375  break
376 
377  ## there is in fact only one acquisition era
378  #if len(set(chainDict['AcquisitionEra'].values()))==1:
379  # print "setting only one acq"
380  if acqEra:
381  chainDict['AcquisitionEra'] = chainDict['AcquisitionEra'].values()[0]
382 
383  ## clean things up now
384  itask=0
385  if self.keep:
386  for i in self.keep:
387  if type(i)==int and i < len(chainDict['nowmTasklist']):
388  chainDict['nowmTasklist'][i]['KeepOutput']=True
389  for (i,t) in enumerate(chainDict['nowmTasklist']):
390  if t['TaskName'].startswith('HARVEST'):
391  continue
392  if not self.keep:
393  t['KeepOutput']=True
394  elif t['TaskName'] in self.keep:
395  t['KeepOutput']=True
396  t.pop('nowmIO')
397  itask+=1
398  chainDict['Task%d'%(itask)]=t
399 
400 
401  ##
402 
403 
404  ## provide the number of tasks
405  chainDict['TaskChain']=itask#len(chainDict['nowmTasklist'])
406 
407  chainDict.pop('nowmTasklist')
408  self.chainDicts[n]=chainDict
409 
410 
411  return 0
412 
413  def uploadConf(self,filePath,label,where):
414  labelInCouch=self.label+'_'+label
415  cacheName=filePath.split('/')[-1]
416  if self.testMode:
417  self.count+=1
418  print '\tFake upload of',filePath,'to couch with label',labelInCouch
419  return self.count
420  else:
421  try:
422  from modules.wma import upload_to_couch,DATABASE_NAME
423  except:
424  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
425  print '\n\t QUIT\n'
426  sys.exit(-16)
427 
428  if cacheName in self.couchCache:
429  print "Not re-uploading",filePath,"to",where,"for",label
430  cacheId=self.couchCache[cacheName]
431  else:
432  print "Loading",filePath,"to",where,"for",label
433  ## totally fork the upload to couch to prevent cross loading of process configurations
434  pool = multiprocessing.Pool(1)
435  cacheIds = pool.map( upload_to_couch_oneArg, [(filePath,labelInCouch,self.user,self.group,where)] )
436  cacheId = cacheIds[0]
437  self.couchCache[cacheName]=cacheId
438  return cacheId
439 
440  def upload(self):
441  for (n,d) in self.chainDicts.items():
442  for it in d:
443  if it.startswith("Task") and it!='TaskChain':
444  #upload
445  couchID=self.uploadConf(d[it]['ConfigCacheID'],
446  str(n)+d[it]['TaskName'],
447  d['CouchURL']
448  )
449  print d[it]['ConfigCacheID']," uploaded to couchDB for",str(n),"with ID",couchID
450  d[it]['ConfigCacheID']=couchID
451  if it =='DQMConfigCacheID':
452  couchID=self.uploadConf(d['DQMConfigCacheID'],
453  str(n)+'harvesting',
454  d['CouchURL']
455  )
456  print d['DQMConfigCacheID'],"uploaded to couchDB for",str(n),"with ID",couchID
457  d['DQMConfigCacheID']=couchID
458 
459 
460  def submit(self):
461  try:
462  from modules.wma import makeRequest,approveRequest
463  from wmcontrol import random_sleep
464  print '\n\tFound wmcontrol\n'
465  except:
466  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
467  if not self.testMode:
468  print '\n\t QUIT\n'
469  sys.exit(-17)
470 
471  import pprint
472  for (n,d) in self.chainDicts.items():
473  if self.testMode:
474  print "Only viewing request",n
475  print pprint.pprint(d)
476  else:
477  #submit to wmagent each dict
478  print "For eyes before submitting",n
479  print pprint.pprint(d)
480  print "Submitting",n,"..........."
481  workFlow=makeRequest(self.wmagent,d,encodeDict=True)
482  approveRequest(self.wmagent,workFlow)
483  print "...........",n,"submitted"
484  random_sleep()
485 
486 
487 
boost::dynamic_bitset append(const boost::dynamic_bitset<> &bs1, const boost::dynamic_bitset<> &bs2)
this method takes two bitsets bs1 and bs2 and returns result of bs2 appended to the end of bs1 ...
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:7
def performInjectionOptionTest
if(dp >Float(M_PI)) dp-
def upload_to_couch_oneArg
double split
Definition: MVATrainer.cc:139