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  "AcquisitionEra": {}, #Acq Era
84  "ProcessingString": {}, # processing string to label the dataset
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": "http://cmsdbsprod.cern.ch/cms_dbs_prod_global/servlet/DBSServlet",
95  #"CouchDBName": self.couchDB, #Name of Couch Database containing config cache
96  #- Will contain all configs for all Tasks
97  "SiteWhitelist" : ["T2_CH_CERN", "T1_US_FNAL"], #Site whitelist
98  "TaskChain" : None, #Define number of tasks in chain.
99  "nowmTasklist" : [], #a list of tasks as we put them in
100  "unmergedLFNBase" : "/store/unmerged",
101  "mergedLFNBase" : "/store/relval",
102  "dashboardActivity" : "relval",
103  "Memory" : 2400,
104  "SizePerEvent" : 1234,
105  "TimePerEvent" : 20
106  }
107 
109  "EnableDQMHarvest" : 1,
110  "DQMUploadUrl" : self.dqmgui,
111  "DQMConfigCacheID" : None
112  }
113 
115  "TaskName" : None, #Task Name
116  "ConfigCacheID" : None, #Generator Config id
117  "GlobalTag": None,
118  "SplittingAlgorithm" : "EventBased", #Splitting Algorithm
119  "SplittingArguments" : {"events_per_job" : None}, #Size of jobs in terms of splitting algorithm
120  "RequestNumEvents" : None, #Total number of events to generate
121  "Seeding" : "AutomaticSeeding", #Random seeding method
122  "PrimaryDataset" : None, #Primary Dataset to be created
123  "nowmIO": {},
124  "KeepOutput" : False
125  }
127  "TaskName" : "DigiHLT", #Task Name
128  "ConfigCacheID" : None, #Processing Config id
129  "GlobalTag": None,
130  "InputDataset" : None, #Input Dataset to be processed
131  "SplittingAlgorithm" : "LumiBased", #Splitting Algorithm
132  "SplittingArguments" : {"lumis_per_job" : 10}, #Size of jobs in terms of splitting algorithm
133  "nowmIO": {},
134  "KeepOutput" : False
135  }
136  self.defaultTask={
137  "TaskName" : None, #Task Name
138  "InputTask" : None, #Input Task Name (Task Name field of a previous Task entry)
139  "InputFromOutputModule" : None, #OutputModule name in the input task that will provide files to process
140  "ConfigCacheID" : None, #Processing Config id
141  "GlobalTag": None,
142  "SplittingAlgorithm" : "LumiBased", #Splitting Algorithm
143  "SplittingArguments" : {"lumis_per_job" : 10}, #Size of jobs in terms of splitting algorithm
144  "nowmIO": {},
145  "KeepOutput" : False
146  }
147 
148  self.chainDicts={}
149 
150 
151  def prepare(self,mReader, directories, mode='init'):
152  try:
153  #from Configuration.PyReleaseValidation.relval_steps import wmsplit
154  wmsplit = {}
155  wmsplit['DIGIHI']=5
156  wmsplit['RECOHI']=5
157  wmsplit['HLTD']=5
158  wmsplit['RECODreHLT']=2
159  wmsplit['DIGIPU']=4
160  wmsplit['DIGIPU1']=4
161  wmsplit['RECOPU1']=1
162  wmsplit['DIGIHISt3']=5
163  wmsplit['RECOHISt4']=5
164  wmsplit['SingleMuPt10_ID']=1
165  wmsplit['DIGI_ID']=1
166  wmsplit['RECO_ID']=1
167  wmsplit['TTbar_ID']=1
168  wmsplit['SingleMuPt10FS_ID']=1
169  wmsplit['TTbarFS_ID']=1
170 
171  #import pprint
172  #pprint.pprint(wmsplit)
173  except:
174  print "Not set up for step splitting"
175  wmsplit={}
176 
177  acqEra=False
178  for (n,dir) in directories.items():
179  chainDict=copy.deepcopy(self.defaultChain)
180  print "inspecting",dir
181  nextHasDSInput=None
182  for (x,s) in mReader.workFlowSteps.items():
183  #x has the format (num, prefix)
184  #s has the format (num, name, commands, stepList)
185  if x[0]==n:
186  #print "found",n,s[3]
187  #chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
188  index=0
189  splitForThisWf=None
190  thisLabel=self.speciallabel
191  processStrPrefix=''
192  setPrimaryDs=None
193  for step in s[3]:
194 
195  if 'INPUT' in step or (not isinstance(s[2][index],str)):
196  nextHasDSInput=s[2][index]
197 
198  else:
199 
200  if (index==0):
201  #first step and not input -> gen part
202  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultScratch))
203  try:
204  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
205  except:
206  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
207  return -15
208 
209  chainDict['nowmTasklist'][-1]['PrimaryDataset']='RelVal'+s[1].split('+')[0]
210  if not '--relval' in s[2][index]:
211  print 'Impossible to create task from scratch without splitting information with --relval'
212  return -12
213  else:
214  arg=s[2][index].split()
215  ns=map(int,arg[arg.index('--relval')+1].split(','))
216  chainDict['nowmTasklist'][-1]['RequestNumEvents'] = ns[0]
217  chainDict['nowmTasklist'][-1]['SplittingArguments']['events_per_job'] = ns[1]
218  if 'FASTSIM' in s[2][index] or '--fast' in s[2][index]:
219  thisLabel+='_FastSim'
220 
221  elif nextHasDSInput:
222  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultInput))
223  try:
224  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
225  except:
226  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
227  return -15
228  chainDict['nowmTasklist'][-1]['InputDataset']=nextHasDSInput.dataSet
229  splitForThisWf=nextHasDSInput.split
230  chainDict['nowmTasklist'][-1]['SplittingArguments']['lumis_per_job']=splitForThisWf
231  if step in wmsplit:
232  chainDict['nowmTasklist'][-1]['SplittingArguments']['lumis_per_job']=wmsplit[step]
233  # get the run numbers or #events
234  if len(nextHasDSInput.run):
235  chainDict['nowmTasklist'][-1]['RunWhitelist']=nextHasDSInput.run
236  #print "what is s",s[2][index]
237  if '--data' in s[2][index] and nextHasDSInput.label:
238  thisLabel+='_RelVal_%s'%nextHasDSInput.label
239  if 'filter' in chainDict['nowmTasklist'][-1]['nowmIO']:
240  print "This has an input DS and a filter sequence: very likely to be the PyQuen sample"
241  processStrPrefix='PU_'
242  setPrimaryDs = 'RelVal'+s[1].split('+')[0]
243  if setPrimaryDs:
244  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
245  nextHasDSInput=None
246  else:
247  #not first step and no inputDS
248  chainDict['nowmTasklist'].append(copy.deepcopy(self.defaultTask))
249  try:
250  chainDict['nowmTasklist'][-1]['nowmIO']=json.loads(open('%s/%s.io'%(dir,step)).read())
251  except:
252  print "Failed to find",'%s/%s.io'%(dir,step),".The workflows were probably not run on cfg not created"
253  return -15
254  if splitForThisWf:
255  chainDict['nowmTasklist'][-1]['SplittingArguments']['lumis_per_job']=splitForThisWf
256  if step in wmsplit:
257  chainDict['nowmTasklist'][-1]['SplittingArguments']['lumis_per_job']=wmsplit[step]
258 
259  #print step
260  chainDict['nowmTasklist'][-1]['TaskName']=step
261  if setPrimaryDs:
262  chainDict['nowmTasklist'][-1]['PrimaryDataset']=setPrimaryDs
263  chainDict['nowmTasklist'][-1]['ConfigCacheID']='%s/%s.py'%(dir,step)
264  chainDict['nowmTasklist'][-1]['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] # copy to the proper parameter name
265  chainDict['GlobalTag']=chainDict['nowmTasklist'][-1]['nowmIO']['GT'] #set in general to the last one of the chain
266  if 'pileup' in chainDict['nowmTasklist'][-1]['nowmIO']:
267  chainDict['nowmTasklist'][-1]['MCPileup']=chainDict['nowmTasklist'][-1]['nowmIO']['pileup']
268  if '--pileup' in s[2][index]:
269  processStrPrefix='PU_'
270 
271  if acqEra:
272  #chainDict['AcquisitionEra'][step]=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
273  chainDict['AcquisitionEra'][step]=chainDict['CMSSWVersion']
274  chainDict['ProcessingString'][step]=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
275  else:
276  #chainDict['nowmTasklist'][-1]['AcquisitionEra']=(chainDict['CMSSWVersion']+'-PU_'+chainDict['nowmTasklist'][-1]['GlobalTag']).replace('::All','')+thisLabel
277  chainDict['nowmTasklist'][-1]['AcquisitionEra']=chainDict['CMSSWVersion']
278  chainDict['nowmTasklist'][-1]['ProcessingString']=processStrPrefix+chainDict['nowmTasklist'][-1]['GlobalTag'].replace('::All','')+thisLabel
279 
280  index+=1
281  #end of loop through steps
282  chainDict['RequestString']='RV'+chainDict['CMSSWVersion']+s[1].split('+')[0]
283  if processStrPrefix or thisLabel:
284  chainDict['RequestString']+='_'+processStrPrefix+thisLabel
285 
286 
287 
288  #wrap up for this one
289  import pprint
290  #print 'wrapping up'
291  #pprint.pprint(chainDict)
292  #loop on the task list
293  for i_second in reversed(range(len(chainDict['nowmTasklist']))):
294  t_second=chainDict['nowmTasklist'][i_second]
295  #print "t_second taskname", t_second['TaskName']
296  if 'primary' in t_second['nowmIO']:
297  #print t_second['nowmIO']['primary']
298  primary=t_second['nowmIO']['primary'][0].replace('file:','')
299  for i_input in reversed(range(0,i_second)):
300  t_input=chainDict['nowmTasklist'][i_input]
301  for (om,o) in t_input['nowmIO'].items():
302  if primary in o:
303  #print "found",primary,"procuced by",om,"of",t_input['TaskName']
304  t_second['InputTask'] = t_input['TaskName']
305  t_second['InputFromOutputModule'] = om
306  #print 't_second',pprint.pformat(t_second)
307  if t_second['TaskName'].startswith('HARVEST'):
308  chainDict.update(copy.deepcopy(self.defaultHarvest))
309  chainDict['DQMConfigCacheID']=t_second['ConfigCacheID']
310  ## the info are not in the task specific dict but in the general dict
311  #t_input.update(copy.deepcopy(self.defaultHarvest))
312  #t_input['DQMConfigCacheID']=t_second['ConfigCacheID']
313  break
314 
315  ## there is in fact only one acquisition era
316  #if len(set(chainDict['AcquisitionEra'].values()))==1:
317  # print "setting only one acq"
318  if acqEra:
319  chainDict['AcquisitionEra'] = chainDict['AcquisitionEra'].values()[0]
320 
321  ## clean things up now
322  itask=0
323  if self.keep:
324  for i in self.keep:
325  if type(i)==int and i < len(chainDict['nowmTasklist']):
326  chainDict['nowmTasklist'][i]['KeepOutput']=True
327  for (i,t) in enumerate(chainDict['nowmTasklist']):
328  if t['TaskName'].startswith('HARVEST'):
329  continue
330  if not self.keep:
331  t['KeepOutput']=True
332  elif t['TaskName'] in self.keep:
333  t['KeepOutput']=True
334  t.pop('nowmIO')
335  itask+=1
336  chainDict['Task%d'%(itask)]=t
337 
338 
339  ##
340 
341 
342  ## provide the number of tasks
343  chainDict['TaskChain']=itask#len(chainDict['nowmTasklist'])
344 
345  chainDict.pop('nowmTasklist')
346  self.chainDicts[n]=chainDict
347 
348 
349  return 0
350 
351  def uploadConf(self,filePath,label,where):
352  labelInCouch=self.label+'_'+label
353  cacheName=filePath.split('/')[-1]
354  if self.testMode:
355  self.count+=1
356  print '\tFake upload of',filePath,'to couch with label',labelInCouch
357  return self.count
358  else:
359  try:
360  from modules.wma import upload_to_couch,DATABASE_NAME
361  except:
362  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
363  print '\n\t QUIT\n'
364  sys.exit(-16)
365 
366  if cacheName in self.couchCache:
367  print "Not re-uploading",filePath,"to",where,"for",label
368  cacheId=self.couchCache[cacheName]
369  else:
370  print "Loading",filePath,"to",where,"for",label
371  ## totally fork the upload to couch to prevent cross loading of process configurations
372  pool = multiprocessing.Pool(1)
373  cacheIds = pool.map( upload_to_couch_oneArg, [(filePath,labelInCouch,self.user,self.group,where)] )
374  cacheId = cacheIds[0]
375  self.couchCache[cacheName]=cacheId
376  return cacheId
377 
378  def upload(self):
379  for (n,d) in self.chainDicts.items():
380  for it in d:
381  if it.startswith("Task") and it!='TaskChain':
382  #upload
383  couchID=self.uploadConf(d[it]['ConfigCacheID'],
384  str(n)+d[it]['TaskName'],
385  d['CouchURL']
386  )
387  print d[it]['ConfigCacheID']," uploaded to couchDB for",str(n),"with ID",couchID
388  d[it]['ConfigCacheID']=couchID
389  if it =='DQMConfigCacheID':
390  couchID=self.uploadConf(d['DQMConfigCacheID'],
391  str(n)+'harvesting',
392  d['CouchURL']
393  )
394  print d['DQMConfigCacheID'],"uploaded to couchDB for",str(n),"with ID",couchID
395  d['DQMConfigCacheID']=couchID
396 
397 
398  def submit(self):
399  try:
400  from modules.wma import makeRequest,approveRequest
401  from wmcontrol import random_sleep
402  print '\n\tFound wmcontrol\n'
403  except:
404  print '\n\tUnable to find wmcontrol modules. Please include it in your python path\n'
405  if not self.testMode:
406  print '\n\t QUIT\n'
407  sys.exit(-17)
408 
409  import pprint
410  for (n,d) in self.chainDicts.items():
411  if self.testMode:
412  print "Only viewing request",n
413  print pprint.pprint(d)
414  else:
415  #submit to wmagent each dict
416  print "For eyes before submitting",n
417  print pprint.pprint(d)
418  print "Submitting",n,"..........."
419  workFlow=makeRequest(self.wmagent,d,encodeDict=True)
420  approveRequest(self.wmagent,workFlow)
421  print "...........",n,"submitted"
422  random_sleep()
423 
424 
425 
def replace
Definition: linker.py:10
dictionary map
Definition: Association.py:205
list object
Definition: dbtoconf.py:77
def performInjectionOptionTest
def upload_to_couch_oneArg
double split
Definition: MVATrainer.cc:139