CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/src/Utilities/ReleaseScripts/scripts/addOnTests.py

Go to the documentation of this file.
00001 #! /usr/bin/env python
00002 
00003 import os
00004 import time
00005 import sys
00006 import re
00007 import random
00008 from threading import Thread
00009 
00010 scriptPath = os.path.dirname( os.path.abspath(sys.argv[0]) )
00011 print "scriptPath:", scriptPath
00012 if scriptPath not in sys.path:
00013     sys.path.append(scriptPath)
00014 
00015         
00016 class testit(Thread):
00017     def __init__(self,dirName, commandList):
00018         Thread.__init__(self)
00019         self.dirName = dirName
00020         self.commandList = commandList
00021         self.status=-1
00022         self.report=''
00023         self.nfail=[]
00024         self.npass=[]
00025 
00026         return
00027     
00028     def run(self):
00029 
00030         startime='date %s' %time.asctime()
00031         exitCodes = []
00032 
00033         startDir = os.getcwd()
00034         
00035         for command in self.commandList:
00036 
00037             if not os.path.exists(self.dirName):
00038                 os.makedirs(self.dirName)
00039 
00040             commandbase = command.replace(' ','_').replace('/','_')
00041             logfile='%s.log' % commandbase[:150].replace("'",'').replace('../','')
00042             
00043             if os.path.exists( os.path.join(os.environ['CMS_PATH'],'cmsset_default.sh') ) :
00044                 executable = 'source $CMS_PATH/cmsset_default.sh; eval `scram run -sh`;'
00045             else:
00046                 executable = 'source $CMS_PATH/sw/cmsset_default.sh; eval `scram run -sh`;'
00047             # only if needed! executable += 'export FRONTIER_FORCERELOAD=long;' # force reload of db
00048             executable += 'cd '+self.dirName+';'
00049             executable += '%s > %s 2>&1' %(command, logfile)
00050 
00051             ret = os.system(executable)
00052             exitCodes.append( ret )
00053 
00054         endtime='date %s' %time.asctime()
00055         tottime='%s-%s'%(endtime,startime)
00056     
00057         for i in range(len(self.commandList)):
00058             command = self.commandList[i]
00059             exitcode = exitCodes[i]
00060             if exitcode != 0:
00061                 log='%s : FAILED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
00062                 self.report+='%s\n'%log
00063                 self.nfail.append(1)
00064                 self.npass.append(0)
00065             else:
00066                 log='%s : PASSED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
00067                 self.report+='%s\n'%log
00068                 self.nfail.append(0)
00069                 self.npass.append(1)
00070 
00071         os.chdir(startDir)
00072         
00073         return
00074 
00075 class StandardTester(object):
00076 
00077     def __init__(self, nThrMax=4):
00078 
00079         self.threadList = []
00080         self.maxThreads = nThrMax
00081 
00082         return
00083 
00084     def activeThreads(self):
00085 
00086         nActive = 0
00087         for t in self.threadList:
00088             if t.isAlive() : nActive += 1
00089 
00090         return nActive
00091 
00092     def prepare(self):
00093 
00094         cmd = 'ln -s /afs/cern.ch/user/a/andreasp/public/IBTests/read*.py .'
00095         try:
00096             os.system(cmd)
00097         except:
00098             pass
00099 
00100 
00101         tstPkgs = { 'FastSimulation' : [ 'Configuration' ],
00102                     'HLTrigger'      : [ 'Configuration' ],
00103                     'PhysicsTools'   : [ 'PatAlgos'      ],
00104                   }
00105 
00106         #-ap: make sure the actual package is there, not just the subsystem ...
00107         # and set symlinks accordingly ...
00108         pkgPath = os.environ['CMSSW_BASE'] + '/src/'
00109         relPath = '$CMSSW_RELEASE_BASE/src/'
00110         cmd = ''
00111         for tstSys in tstPkgs:
00112           if not os.path.exists(pkgPath + tstSys):
00113              cmd  = 'ln -s ' + relPath + tstSys + ' .;'
00114              try:
00115                 print 'setting up symlink for ' + tstSys + ' using ' + cmd
00116                 os.system(cmd)
00117              except:
00118                 pass
00119           else:
00120             for tstPkg in tstPkgs[tstSys]:
00121               if not os.path.exists(pkgPath + tstSys + "/" + tstPkg):
00122                  cmd  = 'mkdir -p ' + tstSys + '; ln -s ' + relPath + tstSys + '/' + tstPkg + ' ' + tstSys +';'
00123               else:
00124                  cmd  = 'mkdir -p ' + tstSys + '; ln -s ' + pkgPath + tstSys + '/' + tstPkg + ' ' + tstSys +';'
00125               try:
00126                 print 'setting up symlink for ' + tstSys + '/' + tstPkg + ' using ' + cmd
00127                 os.system(cmd)
00128               except:
00129                 pass
00130 
00131         return
00132 
00133 
00134     def runTests(self):
00135 
00136         # make sure we have a way to set the environment in the threads ...
00137         if not os.environ.has_key('CMS_PATH'):
00138             cmsPath = '/afs/cern.ch/cms'
00139             print "setting default for CMS_PATH to", cmsPath
00140             os.environ['CMS_PATH'] = cmsPath
00141 
00142         lines = { 'read312RV' : ['cmsRun ../read312RV_cfg.py'], 
00143                   'fastsim1' : ['cmsRun ../FastSimulation/Configuration/test/IntegrationTestFake_cfg.py'],
00144                   'fastsim2' : ['cmsRun ../FastSimulation/Configuration/test/IntegrationTest_cfg.py'],
00145                   #'fastsim3' : ['cmsRun ../FastSimulation/Configuration/test/ExampleWithHLT_1E31_cfg.py'],
00146                   'fastsim4' : ['cmsRun ../FastSimulation/Configuration/test/IntegrationTestWithHLT_cfg.py'],
00147                   'pat1'     : ['cmsRun ../PhysicsTools/PatAlgos/test/IntegrationTest_cfg.py'],
00148                 }
00149 
00150         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',
00151                       'cmsRun ../HLTrigger/Configuration/test/OnLine_HLT_GRun.py' ], 
00152                      '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',
00153                       'cmsRun ../HLTrigger/Configuration/test/OnLine_HLT_HIon.py'],
00154                      'hlt3' : ['cmsRun ../HLTrigger/Configuration/test/OnData_HLT_GRun.py'],
00155                      'hlt4' : ['cmsRun ../HLTrigger/Configuration/test/OnData_HLT_HIon.py'],
00156                      }
00157 
00158         commands={}
00159 
00160         actDir = os.getcwd()
00161 
00162         if not os.path.exists('addOnTests'):
00163             os.makedirs('addOnTests')
00164         os.chdir('addOnTests')
00165 
00166         self.prepare()
00167 
00168         for dirName, command in lines.items():
00169                 commands[dirName] = command
00170                 # print 'Will do: '+command
00171 
00172         for dirName, commandList in hltTests.items():
00173             cmds = commandList
00174             commands[dirName] = cmds
00175 
00176         nfail=0
00177         npass=0
00178         report=''
00179         
00180         print 'Running in %s thread(s)' % self.maxThreads
00181         
00182         for dirName, command in commands.items():
00183 
00184             # make sure we don't run more than the allowed number of threads:
00185             while self.activeThreads() >= self.maxThreads:
00186                 time.sleep(10)
00187                 continue
00188             
00189             print 'Preparing to run %s' % str(command)
00190             current = testit(dirName, command)
00191             self.threadList.append(current)
00192             current.start()
00193             time.sleep(random.randint(1,5)) # try to avoid race cond by sleeping random amount of time [1,5] sec 
00194             
00195         # wait until all threads are finished
00196         while self.activeThreads() > 0:
00197             time.sleep(5)
00198             
00199         # all threads are done now, check status ...
00200         for pingle in self.threadList:
00201             pingle.join()
00202             for f in pingle.nfail: nfail  += f
00203             for p in pingle.npass: npass  += p
00204             report += pingle.report
00205             print pingle.report
00206             sys.stdout.flush()
00207             
00208         reportSumm = '\n %s tests passed, %s failed \n' %(npass,nfail)
00209         print reportSumm
00210         
00211         runall_report_name='runall-report.log'
00212         runall_report=open(runall_report_name,'w')
00213         runall_report.write(report+reportSumm)
00214         runall_report.close()
00215 
00216         # get the logs to the logs dir:
00217         print '==> in :', os.getcwd()
00218         print '    going to copy log files to logs dir ...'
00219         if not os.path.exists('logs'):
00220             os.makedirs('logs')
00221         for dirName in commands.keys():
00222             cmd = "for L in `ls "+dirName+"/*.log`; do cp $L logs/cmsDriver-`dirname $L`_`basename $L` ; done"
00223             print "going to ",cmd
00224             os.system(cmd)
00225 
00226         import pickle
00227         pickle.dump(commands, open('logs/addOnTests.pkl', 'w') )
00228 
00229         os.chdir(actDir)
00230         
00231         return
00232 
00233     def upload(self, tgtDir):
00234 
00235         print "in ", os.getcwd()
00236 
00237         # wait until all threads are finished
00238         while self.activeThreads() > 0:
00239             time.sleep(5)
00240 
00241         if not os.path.exists(tgtDir):
00242             os.makedirs(tgtDir)
00243         
00244         cmd = 'tar cf - addOnTests.log addOnTests/logs | (cd '+tgtDir+' ; tar xf - ) '
00245         try:
00246             print 'executing: ',cmd
00247             ret = os.system(cmd)
00248             if ret != 0:
00249                 print "ERROR uploading logs:", ret, cmd
00250         except Exception, e:
00251             print "EXCEPTION while uploading addOnTest-logs : ", str(e)
00252             
00253         return
00254 
00255                 
00256 def main(argv) :
00257 
00258     import getopt
00259     
00260     try:
00261         opts, args = getopt.getopt(argv, "j:", ["nproc=", 'uploadDir=', 'noRun'])
00262     except getopt.GetoptError, e:
00263         print "unknown option", str(e)
00264         sys.exit(2)
00265         
00266 # check command line parameter
00267 
00268     np=4 # default: four threads
00269 
00270     uploadDir = None
00271     runTests  = True
00272     for opt, arg in opts :
00273         if opt in ('-j', "--nproc" ):
00274             np=int(arg)
00275         if opt in ("--uploadDir", ):
00276             uploadDir = arg
00277         if opt in ('--noRun', ):
00278             runTests = False
00279 
00280     tester = StandardTester(np)
00281     if runTests:
00282         tester.runTests()
00283     if uploadDir:
00284         tester.upload(uploadDir)
00285     
00286 
00287 if __name__ == '__main__' :
00288     main(sys.argv[1:])