CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
addOnTests.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 import os
4 import time
5 import sys
6 import re
7 import random
8 from threading import Thread
9 
10 scriptPath = os.path.dirname( os.path.abspath(sys.argv[0]) )
11 print "scriptPath:", scriptPath
12 if scriptPath not in sys.path:
13  sys.path.append(scriptPath)
14 
15 
16 class testit(Thread):
17  def __init__(self,dirName, commandList):
18  Thread.__init__(self)
19  self.dirName = dirName
20  self.commandList = commandList
21  self.status=-1
22  self.report=''
23  self.nfail=[]
24  self.npass=[]
25 
26  return
27 
28  def run(self):
29 
30  startime='date %s' %time.asctime()
31  exitCodes = []
32 
33  startDir = os.getcwd()
34 
35  for command in self.commandList:
36 
37  if not os.path.exists(self.dirName):
38  os.makedirs(self.dirName)
39 
40  commandbase = command.replace(' ','_').replace('/','_')
41  logfile='%s.log' % commandbase[:150].replace("'",'').replace('../','')
42 
43  if os.path.exists( os.path.join(os.environ['CMS_PATH'],'cmsset_default.sh') ) :
44  executable = 'source $CMS_PATH/cmsset_default.sh; eval `scram run -sh`;'
45  else:
46  executable = 'source $CMS_PATH/sw/cmsset_default.sh; eval `scram run -sh`;'
47  # only if needed! executable += 'export FRONTIER_FORCERELOAD=long;' # force reload of db
48  executable += 'cd '+self.dirName+';'
49  executable += '%s > %s 2>&1' %(command, logfile)
50 
51  ret = os.system(executable)
52  exitCodes.append( ret )
53 
54  endtime='date %s' %time.asctime()
55  tottime='%s-%s'%(endtime,startime)
56 
57  for i in range(len(self.commandList)):
58  command = self.commandList[i]
59  exitcode = exitCodes[i]
60  if exitcode != 0:
61  log='%s : FAILED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
62  self.report+='%s\n'%log
63  self.nfail.append(1)
64  self.npass.append(0)
65  else:
66  log='%s : PASSED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
67  self.report+='%s\n'%log
68  self.nfail.append(0)
69  self.npass.append(1)
70 
71  os.chdir(startDir)
72 
73  return
74 
76 
77  def __init__(self, nThrMax=4):
78 
79  self.threadList = []
80  self.maxThreads = nThrMax
81 
82  return
83 
84  def activeThreads(self):
85 
86  nActive = 0
87  for t in self.threadList:
88  if t.isAlive() : nActive += 1
89 
90  return nActive
91 
92  def prepare(self):
93 
94  cmd = 'ln -s /afs/cern.ch/user/a/andreasp/public/IBTests/read*.py .'
95  try:
96  os.system(cmd)
97  except:
98  pass
99 
100 
101  tstPkgs = { 'FastSimulation' : [ 'Configuration' ],
102  'HLTrigger' : [ 'Configuration' ],
103  'PhysicsTools' : [ 'PatAlgos' ],
104  }
105 
106  #-ap: make sure the actual package is there, not just the subsystem ...
107  # and set symlinks accordingly ...
108  pkgPath = os.environ['CMSSW_BASE'] + '/src/'
109  relPath = '$CMSSW_RELEASE_BASE/src/'
110  cmd = ''
111  for tstSys in tstPkgs:
112  if not os.path.exists(pkgPath + tstSys):
113  cmd = 'ln -s ' + relPath + tstSys + ' .;'
114  try:
115  print 'setting up symlink for ' + tstSys + ' using ' + cmd
116  os.system(cmd)
117  except:
118  pass
119  else:
120  for tstPkg in tstPkgs[tstSys]:
121  if not os.path.exists(pkgPath + tstSys + "/" + tstPkg):
122  cmd = 'mkdir -p ' + tstSys + '; ln -s ' + relPath + tstSys + '/' + tstPkg + ' ' + tstSys +';'
123  else:
124  cmd = 'mkdir -p ' + tstSys + '; ln -s ' + pkgPath + tstSys + '/' + tstPkg + ' ' + tstSys +';'
125  try:
126  print 'setting up symlink for ' + tstSys + '/' + tstPkg + ' using ' + cmd
127  os.system(cmd)
128  except:
129  pass
130 
131  return
132 
133 
134  def runTests(self):
135 
136  # make sure we have a way to set the environment in the threads ...
137  if not os.environ.has_key('CMS_PATH'):
138  cmsPath = '/afs/cern.ch/cms'
139  print "setting default for CMS_PATH to", cmsPath
140  os.environ['CMS_PATH'] = cmsPath
141 
142  lines = { 'read312RV' : ['cmsRun ../read312RV_cfg.py'],
143  'fastsim1' : ['cmsRun ../FastSimulation/Configuration/test/IntegrationTestFake_cfg.py'],
144  'fastsim2' : ['cmsRun ../FastSimulation/Configuration/test/IntegrationTest_cfg.py'],
145  #'fastsim3' : ['cmsRun ../FastSimulation/Configuration/test/ExampleWithHLT_1E31_cfg.py'],
146  'fastsim4' : ['cmsRun ../FastSimulation/Configuration/test/IntegrationTestWithHLT_cfg.py'],
147  'pat1' : ['cmsRun ../PhysicsTools/PatAlgos/test/IntegrationTest_cfg.py'],
148  }
149 
150  hltTests = { 'hlt1' : ['cmsDriver.py TTbar_Tauola.cfi -s GEN,SIM,DIGI,L1,DIGI2RAW -n 10 --conditions auto:startup --relval 9000,50 --datatier "GEN-SIM-RAW" --eventcontent RAW --fileout file:RelVal_DigiL1Raw_GRun.root',
151  'cmsRun ../HLTrigger/Configuration/test/OnLine_HLT_GRun.py' ],
152  'hlt2' : ['cmsDriver.py TTbar_Tauola.cfi -s GEN,SIM,DIGI,L1,DIGI2RAW -n 10 --conditions auto:starthi --relval 9000,50 --datatier "GEN-SIM-RAW" --eventcontent RAW --fileout file:RelVal_DigiL1Raw_HIon.root',
153  'cmsRun ../HLTrigger/Configuration/test/OnLine_HLT_HIon.py'],
154  'hlt3' : ['cmsRun ../HLTrigger/Configuration/test/OnData_HLT_GRun.py'],
155  'hlt4' : ['cmsRun ../HLTrigger/Configuration/test/OnData_HLT_HIon.py'],
156  }
157 
158  commands={}
159 
160  actDir = os.getcwd()
161 
162  if not os.path.exists('addOnTests'):
163  os.makedirs('addOnTests')
164  os.chdir('addOnTests')
165 
166  self.prepare()
167 
168  for dirName, command in lines.items():
169  commands[dirName] = command
170  # print 'Will do: '+command
171 
172  for dirName, commandList in hltTests.items():
173  cmds = commandList
174  commands[dirName] = cmds
175 
176  nfail=0
177  npass=0
178  report=''
179 
180  print 'Running in %s thread(s)' % self.maxThreads
181 
182  for dirName, command in commands.items():
183 
184  # make sure we don't run more than the allowed number of threads:
185  while self.activeThreads() >= self.maxThreads:
186  time.sleep(10)
187  continue
188 
189  print 'Preparing to run %s' % str(command)
190  current = testit(dirName, command)
191  self.threadList.append(current)
192  current.start()
193  time.sleep(random.randint(1,5)) # try to avoid race cond by sleeping random amount of time [1,5] sec
194 
195  # wait until all threads are finished
196  while self.activeThreads() > 0:
197  time.sleep(5)
198 
199  # all threads are done now, check status ...
200  for pingle in self.threadList:
201  pingle.join()
202  for f in pingle.nfail: nfail += f
203  for p in pingle.npass: npass += p
204  report += pingle.report
205  print pingle.report
206  sys.stdout.flush()
207 
208  reportSumm = '\n %s tests passed, %s failed \n' %(npass,nfail)
209  print reportSumm
210 
211  runall_report_name='runall-report.log'
212  runall_report=open(runall_report_name,'w')
213  runall_report.write(report+reportSumm)
214  runall_report.close()
215 
216  # get the logs to the logs dir:
217  print '==> in :', os.getcwd()
218  print ' going to copy log files to logs dir ...'
219  if not os.path.exists('logs'):
220  os.makedirs('logs')
221  for dirName in commands.keys():
222  cmd = "for L in `ls "+dirName+"/*.log`; do cp $L logs/cmsDriver-`dirname $L`_`basename $L` ; done"
223  print "going to ",cmd
224  os.system(cmd)
225 
226  import pickle
227  pickle.dump(commands, open('logs/addOnTests.pkl', 'w') )
228 
229  os.chdir(actDir)
230 
231  return
232 
233  def upload(self, tgtDir):
234 
235  print "in ", os.getcwd()
236 
237  # wait until all threads are finished
238  while self.activeThreads() > 0:
239  time.sleep(5)
240 
241  if not os.path.exists(tgtDir):
242  os.makedirs(tgtDir)
243 
244  cmd = 'tar cf - addOnTests.log addOnTests/logs | (cd '+tgtDir+' ; tar xf - ) '
245  try:
246  print 'executing: ',cmd
247  ret = os.system(cmd)
248  if ret != 0:
249  print "ERROR uploading logs:", ret, cmd
250  except Exception, e:
251  print "EXCEPTION while uploading addOnTest-logs : ", str(e)
252 
253  return
254 
255 
256 def main(argv) :
257 
258  import getopt
259 
260  try:
261  opts, args = getopt.getopt(argv, "j:", ["nproc=", 'uploadDir=', 'noRun'])
262  except getopt.GetoptError, e:
263  print "unknown option", str(e)
264  sys.exit(2)
265 
266 # check command line parameter
267 
268  np=4 # default: four threads
269 
270  uploadDir = None
271  runTests = True
272  for opt, arg in opts :
273  if opt in ('-j', "--nproc" ):
274  np=int(arg)
275  if opt in ("--uploadDir", ):
276  uploadDir = arg
277  if opt in ('--noRun', ):
278  runTests = False
279 
280  tester = StandardTester(np)
281  if runTests:
282  tester.runTests()
283  if uploadDir:
284  tester.upload(uploadDir)
285 
286 
287 if __name__ == '__main__' :
288  main(sys.argv[1:])
list object
Definition: dbtoconf.py:77