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 
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" : opt.nThreads,
108  "Memory" : 3000,
109  "SizePerEvent" : 1234,
110  "TimePerEvent" : 0.1
111  }
112 
114  "EnableHarvesting" : "True",
115  "DQMUploadUrl" : self.dqmgui,
116  "DQMConfigCacheID" : None
117  }
118 
120  "TaskName" : None, #Task Name
121  "ConfigCacheID" : None, #Generator Config id
122  "GlobalTag": None,
123  "SplittingAlgo" : "EventBased", #Splitting Algorithm
124  "EventsPerJob" : None, #Size of jobs in terms of splitting algorithm
125  "RequestNumEvents" : None, #Total number of events to generate
126  "Seeding" : "AutomaticSeeding", #Random seeding method
127  "PrimaryDataset" : None, #Primary Dataset to be created
128  "nowmIO": {},
129  "KeepOutput" : False
130  }
132  "TaskName" : "DigiHLT", #Task Name
133  "ConfigCacheID" : None, #Processing Config id
134  "GlobalTag": None,
135  "InputDataset" : None, #Input Dataset to be processed
136  "SplittingAlgo" : "LumiBased", #Splitting Algorithm
137  "LumisPerJob" : 10, #Size of jobs in terms of splitting algorithm
138  "nowmIO": {},
139  "KeepOutput" : False
140  }
141  self.defaultTask={
142  "TaskName" : None, #Task Name
143  "InputTask" : None, #Input Task Name (Task Name field of a previous Task entry)
144  "InputFromOutputModule" : None, #OutputModule name in the input task that will provide files to process
145  "ConfigCacheID" : None, #Processing Config id
146  "GlobalTag": None,
147  "SplittingAlgo" : "LumiBased", #Splitting Algorithm
148  "LumisPerJob" : 10, #Size of jobs in terms of splitting algorithm
149  "nowmIO": {},
150  "KeepOutput" : False
151  }
152 
153  self.chainDicts={}
154 
155 
156  def prepare(self,mReader, directories, mode='init'):
157  try:
158  #from Configuration.PyReleaseValidation.relval_steps import wmsplit
159  wmsplit = {}
160  wmsplit['DIGIHI']=5
161  wmsplit['RECOHI']=5
162  wmsplit['HLTD']=5
163  wmsplit['RECODreHLT']=2
164  wmsplit['DIGIPU']=4
165  wmsplit['DIGIPU1']=4
166  wmsplit['RECOPU1']=1
167  wmsplit['DIGIUP15_PU50']=1
168  wmsplit['RECOUP15_PU50']=1
169  wmsplit['DIGIUP15_PU25']=1
170  wmsplit['RECOUP15_PU25']=1
171  wmsplit['DIGIHIMIX']=5
172  wmsplit['RECOHIMIX']=5
173  wmsplit['RECODSplit']=1
174  wmsplit['SingleMuPt10_UP15_ID']=1
175  wmsplit['DIGIUP15_ID']=1
176  wmsplit['RECOUP15_ID']=1
177  wmsplit['TTbar_13_ID']=1
178  wmsplit['SingleMuPt10FS_ID']=1
179  wmsplit['TTbarFS_ID']=1
180  wmsplit['RECODR2_50nsreHLT']=1
181  wmsplit['RECODR2_25nsreHLT']=1
182  wmsplit['HLTDR2_50ns']=3
183  wmsplit['HLTDR2_25ns']=3
184  wmsplit['Hadronizer']=1
185 
186  #import pprint
187  #pprint.pprint(wmsplit)
188  except:
189  print "Not set up for step splitting"
190  wmsplit={}
191 
192  acqEra=False
193  for (n,dir) in directories.items():
194  chainDict=copy.deepcopy(self.defaultChain)
195  print "inspecting",dir
196  nextHasDSInput=None
197  for (x,s) in mReader.workFlowSteps.items():
198  #x has the format (num, prefix)
199  #s has the format (num, name, commands, stepList)
200  if x[0]==n:
201  #print "found",n,s[3]
202  #chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
203  index=0
204  splitForThisWf=None
205  thisLabel=self.speciallabel
206  #if 'HARVESTGEN' in s[3]:
207  if len( [step for step in s[3] if "HARVESTGEN" in step] )>0:
208  chainDict['TimePerEvent']=0.01
209  thisLabel=thisLabel+"_gen"
210  processStrPrefix=''
211  setPrimaryDs=None
212  for step in s[3]:
213 
214  if 'INPUT' in step or (not isinstance(s[2][index],str)):
215  nextHasDSInput=s[2][index]
216 
217  else:
218 
219  if (index==0):
220  #first step and not input -> gen part
221  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultScratch))
222  try:
223  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
224  except:
225  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
226  return -15
227 
228  chainDict['nowmTasklist'][-1]['PrimaryDataset']='RelVal'+s[1].split('+')[0]
229  if not '--relval' in s[2][index]:
230  print 'Impossible to create task from scratch without splitting information with --relval'
231  return -12
232  else:
233  arg=s[2][index].split()
234  ns=map(int,arg[arg.index('--relval')+1].split(','))
235  chainDict['nowmTasklist'][-1]['RequestNumEvents'] = ns[0]
236  chainDict['nowmTasklist'][-1]['EventsPerJob'] = ns[1]
237  if 'FASTSIM' in s[2][index] or '--fast' in s[2][index]:
238  thisLabel+='_FastSim'
239  if 'lhe' in s[2][index] in s[2][index]:
240  chainDict['nowmTasklist'][-1]['LheInputFiles'] =True
241 
242  elif nextHasDSInput:
243  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultInput))
244  try:
245  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
246  except:
247  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
248  return -15
249  chainDict['nowmTasklist'][-1]['InputDataset']=nextHasDSInput.dataSet
250  splitForThisWf=nextHasDSInput.split
251  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
252  if step in wmsplit:
253  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
254  # get the run numbers or #events
255  if len(nextHasDSInput.run):
256  chainDict['nowmTasklist'][-1]['RunWhitelist']=nextHasDSInput.run
257  if len(nextHasDSInput.ls):
258  chainDict['nowmTasklist'][-1]['LumiList']=nextHasDSInput.ls
259  #print "what is s",s[2][index]
260  if '--data' in s[2][index] and nextHasDSInput.label:
261  thisLabel+='_RelVal_%s'%nextHasDSInput.label
262  if 'filter' in chainDict['nowmTasklist'][-1]['nowmIO']:
263  print "This has an input DS and a filter sequence: very likely to be the PyQuen sample"
264  processStrPrefix='PU_'
265  setPrimaryDs = 'RelVal'+s[1].split('+')[0]
266  if setPrimaryDs:
267  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
268  nextHasDSInput=None
269  else:
270  #not first step and no inputDS
271  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultTask))
272  try:
273  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
274  except:
275  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
276  return -15
277  if splitForThisWf:
278  chainDict['nowmTasklist'][-1]['LumisPerJob']=splitForThisWf
279  if step in wmsplit:
280  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit[step]
281 
282  # change LumisPerJob for Hadronizer steps.
283  if 'Hadronizer' in step:
284  chainDict['nowmTasklist'][-1]['LumisPerJob']=wmsplit['Hadronizer']
285 
286  #print step
287  chainDict['nowmTasklist'][-1]['TaskName']=step
288  if setPrimaryDs:
289  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
290  chainDict['nowmTasklist'][-1]['ConfigCacheID']='%s/%s.py'%(dir,step)
291  chainDict['nowmTasklist'][-1]['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] # copy to the proper parameter name
292  chainDict['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] #set in general to the last one of the chain
293  if 'pileup' in chainDict['nowmTasklist'][-1]['nowmIO']:
294  chainDict['nowmTasklist'][-1]['MCPileup']=chainDict['nowmTasklist'][-1]['nowmIO']['pileup']
295  if '--pileup ' in s[2][index]: # catch --pileup (scenarion) and not --pileup_ (dataset to be mixed) => works also making PRE-MIXed dataset
296  processStrPrefix='PU_' # take care of pu overlay done with GEN-SIM mixing
297  if ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('25ns') > 0 :
298  processStrPrefix='PU25ns_'
299  elif ( s[2][index].split()[ s[2][index].split().index('--pileup')+1 ] ).find('50ns') > 0 :
300  processStrPrefix='PU50ns_'
301  if 'DIGIPREMIX_S2' in s[2][index] : # take care of pu overlay done with DIGI mixing of premixed events
302  if s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('25ns') > 0 :
303  processStrPrefix='PUpmx25ns_'
304  elif s[2][index].split()[ s[2][index].split().index('--pileup_input')+1 ].find('50ns') > 0 :
305  processStrPrefix='PUpmx50ns_'
306 
307  if acqEra:
308  #chainDict['AcquisitionEra'][step]=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
309  chainDict['AcquisitionEra'][step]=chainDict['CMSSWVersion']
310  chainDict['ProcessingString'][step]=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
311  else:
312  #chainDict['nowmTasklist'][-1]['AcquisitionEra']=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
313  chainDict['nowmTasklist'][-1]['AcquisitionEra']=chainDict['CMSSWVersion']
314  chainDict['nowmTasklist'][-1]['ProcessingString']=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
315 
316  index+=1
317  #end of loop through steps
318  chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
319  if processStrPrefix or thisLabel:
320  chainDict['RequestString']+='_'+processStrPrefix+thisLabel
321 
322 
323 
324  #wrap up for this one
325  import pprint
326  #print 'wrapping up'
327  #pprint.pprint(chainDict)
328  #loop on the task list
329  for i_second in reversed(range(len(chainDict['nowmTasklist']))):
330  t_second=chainDict['nowmTasklist'][i_second]
331  #print "t_second taskname", t_second['TaskName']
332  if 'primary' in t_second['nowmIO']:
333  #print t_second['nowmIO']['primary']
334  primary=t_second['nowmIO']['primary'][0].replace('file:','')
335  for i_input in reversed(range(0,i_second)):
336  t_input=chainDict['nowmTasklist'][i_input]
337  for (om,o) in t_input['nowmIO'].items():
338  if primary in o:
339  #print "found",primary,"procuced by",om,"of",t_input['TaskName']
340  t_second['InputTask'] = t_input['TaskName']
341  t_second['InputFromOutputModule'] = om
342  #print 't_second',pprint.pformat(t_second)
343  if t_second['TaskName'].startswith('HARVEST'):
344  chainDict.update(copy.deepcopy(self.defaultHarvest))
345  chainDict['DQMConfigCacheID']=t_second['ConfigCacheID']
346  ## the info are not in the task specific dict but in the general dict
347  #t_input.update(copy.deepcopy(self.defaultHarvest))
348  #t_input['DQMConfigCacheID']=t_second['ConfigCacheID']
349  break
350 
351  ## there is in fact only one acquisition era
352  #if len(set(chainDict['AcquisitionEra'].values()))==1:
353  # print "setting only one acq"
354  if acqEra:
355  chainDict['AcquisitionEra'] = chainDict['AcquisitionEra'].values()[0]
356 
357  ## clean things up now
358  itask=0
359  if self.keep:
360  for i in self.keep:
361  if type(i)==int and i < len(chainDict['nowmTasklist']):
362  chainDict['nowmTasklist'][i]['KeepOutput']=True
363  for (i,t) in enumerate(chainDict['nowmTasklist']):
364  if t['TaskName'].startswith('HARVEST'):
365  continue
366  if not self.keep:
367  t['KeepOutput']=True
368  elif t['TaskName'] in self.keep:
369  t['KeepOutput']=True
370  t.pop('nowmIO')
371  itask+=1
372  chainDict['Task%d'%(itask)]=t
373 
374 
375  ##
376 
377 
378  ## provide the number of tasks
379  chainDict['TaskChain']=itask#len(chainDict['nowmTasklist'])
380 
381  chainDict.pop('nowmTasklist')
382  self.chainDicts[n]=chainDict
383 
384 
385  return 0
386 
387  def uploadConf(self,filePath,label,where):
388  labelInCouch=self.label+'_'+label
389  cacheName=filePath.split('/')[-1]
390  if self.testMode:
391  self.count+=1
392  print '\tFake upload of',filePath,'to couch with label',labelInCouch
393  return self.count
394  else:
395  try:
396  from modules.wma import upload_to_couch,DATABASE_NAME
397  except:
398  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
399  print '\n\t QUIT\n'
400  sys.exit(-16)
401 
402  if cacheName in self.couchCache:
403  print "Not re-uploading",filePath,"to",where,"for",label
404  cacheId=self.couchCache[cacheName]
405  else:
406  print "Loading",filePath,"to",where,"for",label
407  ## totally fork the upload to couch to prevent cross loading of process configurations
408  pool = multiprocessing.Pool(1)
409  cacheIds = pool.map( upload_to_couch_oneArg, [(filePath,labelInCouch,self.user,self.group,where)] )
410  cacheId = cacheIds[0]
411  self.couchCache[cacheName]=cacheId
412  return cacheId
413 
414  def upload(self):
415  for (n,d) in self.chainDicts.items():
416  for it in d:
417  if it.startswith("Task") and it!='TaskChain':
418  #upload
419  couchID=self.uploadConf(d[it]['ConfigCacheID'],
420  str(n)+d[it]['TaskName'],
421  d['CouchURL']
422  )
423  print d[it]['ConfigCacheID']," uploaded to couchDB for",str(n),"with ID",couchID
424  d[it]['ConfigCacheID']=couchID
425  if it =='DQMConfigCacheID':
426  couchID=self.uploadConf(d['DQMConfigCacheID'],
427  str(n)+'harvesting',
428  d['CouchURL']
429  )
430  print d['DQMConfigCacheID'],"uploaded to couchDB for",str(n),"with ID",couchID
431  d['DQMConfigCacheID']=couchID
432 
433 
434  def submit(self):
435  try:
436  from modules.wma import makeRequest,approveRequest
437  from wmcontrol import random_sleep
438  print '\n\tFound wmcontrol\n'
439  except:
440  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
441  if not self.testMode:
442  print '\n\t QUIT\n'
443  sys.exit(-17)
444 
445  import pprint
446  for (n,d) in self.chainDicts.items():
447  if self.testMode:
448  print "Only viewing request",n
449  print pprint.pprint(d)
450  else:
451  #submit to wmagent each dict
452  print "For eyes before submitting",n
453  print pprint.pprint(d)
454  print "Submitting",n,"..........."
455  workFlow=makeRequest(self.wmagent,d,encodeDict=True)
456  approveRequest(self.wmagent,workFlow)
457  print "...........",n,"submitted"
458  random_sleep()
459 
460 
461 
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