CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_4_5_patch3/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 if scriptPath not in sys.path:
00012     sys.path.append(scriptPath)
00013 
00014         
00015 class testit(Thread):
00016     def __init__(self,dirName, commandList):
00017         Thread.__init__(self)
00018         self.dirName = dirName
00019         self.commandList = commandList
00020         self.status=-1
00021         self.report=''
00022         self.nfail=[]
00023         self.npass=[]
00024 
00025         return
00026     
00027     def run(self):
00028 
00029         startime='date %s' %time.asctime()
00030         exitCodes = []
00031 
00032         for command in self.commandList:
00033 
00034             if not os.path.exists(self.dirName):
00035                 os.makedirs(self.dirName)
00036 
00037             commandbase = command.replace(' ','_').replace('/','_')
00038             logfile='%s.log' % commandbase[:150].replace("'",'').replace('../','')
00039             
00040             executable = 'cd '+self.dirName+'; '+command+' > '+logfile+' 2>&1'
00041 
00042             ret = os.system(executable)
00043             exitCodes.append( ret )
00044 
00045         endtime='date %s' %time.asctime()
00046         tottime='%s-%s'%(endtime,startime)
00047     
00048         for i in range(len(self.commandList)):
00049             command = self.commandList[i]
00050             exitcode = exitCodes[i]
00051             if exitcode != 0:
00052                 log='%s : FAILED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
00053                 self.report+='%s\n'%log
00054                 self.nfail.append(1)
00055                 self.npass.append(0)
00056             else:
00057                 log='%s : PASSED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
00058                 self.report+='%s\n'%log
00059                 self.nfail.append(0)
00060                 self.npass.append(1)
00061 
00062         return
00063 
00064 class StandardTester(object):
00065 
00066     def __init__(self, nThrMax=4):
00067 
00068         self.threadList = []
00069         self.maxThreads = nThrMax
00070         self.prepare()
00071 
00072         return
00073 
00074     def activeThreads(self):
00075 
00076         nActive = 0
00077         for t in self.threadList:
00078             if t.isAlive() : nActive += 1
00079 
00080         return nActive
00081 
00082     def prepare(self):
00083     
00084         self.devPath = os.environ['LOCALRT'] + '/src/'
00085         self.relPath = self.devPath
00086         if os.environ.has_key('CMSSW_RELEASE_BASE') and (os.environ['CMSSW_RELEASE_BASE'] != ""): self.relPath = os.environ['CMSSW_RELEASE_BASE'] + '/src/'
00087 
00088         lines = { 'read312RV' : ['cmsRun '+self.file2Path('Utilities/ReleaseScripts/scripts/read312RV_cfg.py')], 
00089                   'fastsim1'  : ['cmsRun '+self.file2Path('FastSimulation/Configuration/test/IntegrationTestFake_cfg.py')],
00090                   'fastsim2'  : ['cmsRun '+self.file2Path('FastSimulation/Configuration/test/IntegrationTest_cfg.py')],
00091                   #'fastsim3'  : ['cmsRun '+self.file2Path('FastSimulation/Configuration/test/ExampleWithHLT_1E31_cfg.py')],
00092                   'fastsim4'  : ['cmsRun '+self.file2Path('FastSimulation/Configuration/test/IntegrationTestWithHLT_cfg.py')],
00093                   'pat1'      : ['cmsRun '+self.file2Path('PhysicsTools/PatAlgos/test/IntegrationTest_cfg.py')],
00094                 }
00095 
00096         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',
00097                                'cmsRun '+self.file2Path('HLTrigger/Configuration/test/OnLine_HLT_GRun.py')], 
00098                      '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',
00099                                'cmsRun '+self.file2Path('HLTrigger/Configuration/test/OnLine_HLT_HIon.py')],
00100                      'hlt3' : ['cmsRun '+self.file2Path('HLTrigger/Configuration/test/OnData_HLT_GRun.py')],
00101                      'hlt4' : ['cmsRun '+self.file2Path('HLTrigger/Configuration/test/OnData_HLT_HIon.py')],
00102                      }
00103 
00104         self.commands={}
00105         for dirName, command in lines.items():
00106             self.commands[dirName] = command
00107 
00108         for dirName, commandList in hltTests.items():
00109             self.commands[dirName] = commandList
00110         return
00111         
00112     def dumpTest(self):
00113         print ",".join(self.commands.keys())
00114         return
00115 
00116     def file2Path(self,rFile):
00117 
00118         fullPath = self.relPath + rFile
00119         if os.path.exists(self.devPath + rFile): fullPath = self.devPath + rFile
00120         return fullPath
00121 
00122     def runTests(self, testList = None):
00123 
00124         actDir = os.getcwd()
00125 
00126         if not os.path.exists('addOnTests'):
00127             os.makedirs('addOnTests')
00128         os.chdir('addOnTests')
00129 
00130         nfail=0
00131         npass=0
00132         report=''
00133         
00134         print 'Running in %s thread(s)' % self.maxThreads
00135         
00136         for dirName, command in self.commands.items():
00137 
00138             if testList and not dirName in testList:
00139                 del self.commands[dirName]
00140                 continue
00141 
00142             # make sure we don't run more than the allowed number of threads:
00143             while self.activeThreads() >= self.maxThreads:
00144                 time.sleep(10)
00145                 continue
00146             
00147             print 'Preparing to run %s' % str(command)
00148             current = testit(dirName, command)
00149             self.threadList.append(current)
00150             current.start()
00151             time.sleep(random.randint(1,5)) # try to avoid race cond by sleeping random amount of time [1,5] sec 
00152             
00153         # wait until all threads are finished
00154         while self.activeThreads() > 0:
00155             time.sleep(5)
00156             
00157         # all threads are done now, check status ...
00158         for pingle in self.threadList:
00159             pingle.join()
00160             for f in pingle.nfail: nfail  += f
00161             for p in pingle.npass: npass  += p
00162             report += pingle.report
00163             print pingle.report
00164             sys.stdout.flush()
00165             
00166         reportSumm = '\n %s tests passed, %s failed \n' %(npass,nfail)
00167         print reportSumm
00168         
00169         runall_report_name='runall-report.log'
00170         runall_report=open(runall_report_name,'w')
00171         runall_report.write(report+reportSumm)
00172         runall_report.close()
00173 
00174         # get the logs to the logs dir:
00175         print '==> in :', os.getcwd()
00176         print '    going to copy log files to logs dir ...'
00177         if not os.path.exists('logs'):
00178             os.makedirs('logs')
00179         for dirName in self.commands:
00180             cmd = "for L in `ls "+dirName+"/*.log`; do cp $L logs/cmsDriver-`dirname $L`_`basename $L` ; done"
00181             print "going to ",cmd
00182             os.system(cmd)
00183 
00184         import pickle
00185         pickle.dump(self.commands, open('logs/addOnTests.pkl', 'w') )
00186 
00187         os.chdir(actDir)
00188         
00189         return
00190 
00191     def upload(self, tgtDir):
00192 
00193         print "in ", os.getcwd()
00194 
00195         if not os.path.exists(tgtDir):
00196             os.makedirs(tgtDir)
00197         
00198         cmd = 'tar cf - addOnTests.log addOnTests/logs | (cd '+tgtDir+' ; tar xf - ) '
00199         try:
00200             print 'executing: ',cmd
00201             ret = os.system(cmd)
00202             if ret != 0:
00203                 print "ERROR uploading logs:", ret, cmd
00204         except Exception, e:
00205             print "EXCEPTION while uploading addOnTest-logs : ", str(e)
00206             
00207         return
00208 
00209                 
00210 def main(argv) :
00211 
00212     import getopt
00213     
00214     try:
00215         opts, args = getopt.getopt(argv, "dj:t:", ["nproc=", 'uploadDir=', 'tests=','noRun','dump'])
00216     except getopt.GetoptError, e:
00217         print "unknown option", str(e)
00218         sys.exit(2)
00219         
00220     np        = 4
00221     uploadDir = None
00222     runTests  = True
00223     testList  = None
00224     dump      = False
00225     for opt, arg in opts :
00226         if opt in ('-j', "--nproc" ):
00227             np=int(arg)
00228         if opt in ("--uploadDir", ):
00229             uploadDir = arg
00230         if opt in ('--noRun', ):
00231             runTests = False
00232         if opt in ('-d','--dump', ):
00233             dump = True
00234         if opt in ('-t','--tests', ):
00235             testList = arg.split(",")
00236 
00237     tester = StandardTester(np)
00238     if dump:
00239         tester.dumpTest()
00240     else:
00241         if runTests:
00242             tester.runTests(testList)
00243         if uploadDir:
00244             tester.upload(uploadDir)
00245     return
00246     
00247 if __name__ == '__main__' :
00248     main(sys.argv[1:])