CMS 3D CMS Logo

addOnTests.py
Go to the documentation of this file.
1 #! /usr/bin/env python3
2 
3 from __future__ import print_function
4 from builtins import range
5 import os
6 import time
7 import sys
8 import re
9 import random
10 from threading import Thread
11 
12 scriptPath = os.path.dirname( os.path.abspath(sys.argv[0]) )
13 if scriptPath not in sys.path:
14  sys.path.append(scriptPath)
15 
16 
17 class testit(Thread):
18  def __init__(self,dirName, commandList):
19  Thread.__init__(self)
20  self.dirName = dirName
21  self.commandList = commandList
22  self.status=-1
23  self.report=''
24  self.nfail=[]
25  self.npass=[]
26 
27  return
28 
29  def run(self):
30 
31  startime='date %s' %time.asctime()
32  exitCodes = []
33 
34  for command in self.commandList:
35 
36  if not os.path.exists(self.dirName):
37  os.makedirs(self.dirName)
38 
39  commandbase = command.replace(' ','_').replace('/','_')
40  logfile='%s.log' % commandbase[:150].replace("'",'').replace('"','').replace('../','')
41 
42  executable = 'cd '+self.dirName+'; '+command+' > '+logfile+' 2>&1'
43 
44  ret = os.system(executable)
45  exitCodes.append( ret )
46 
47  endtime='date %s' %time.asctime()
48  tottime='%s-%s'%(endtime,startime)
49 
50  for i in range(len(self.commandList)):
51  command = self.commandList[i]
52  exitcode = exitCodes[i]
53  if exitcode != 0:
54  log='%s : FAILED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
55  self.report+='%s\n'%log
56  self.nfail.append(1)
57  self.npass.append(0)
58  else:
59  log='%s : PASSED - time: %s s - exit: %s\n' %(command,tottime,exitcode)
60  self.report+='%s\n'%log
61  self.nfail.append(0)
62  self.npass.append(1)
63 
64  return
65 
67 
68  def __init__(self, nThrMax=4):
69 
70  self.threadList = []
71  self.maxThreads = nThrMax
72  self.prepare()
73 
74  return
75 
76  def activeThreads(self):
77 
78  nActive = 0
79  for t in self.threadList:
80  if t.is_alive() : nActive += 1
81 
82  return nActive
83 
84  def prepare(self):
85 
86  self.devPath = os.environ['LOCALRT'] + '/src/'
87  self.relPath = self.devPath
88  if 'CMSSW_RELEASE_BASE' in os.environ and (os.environ['CMSSW_RELEASE_BASE'] != ""): self.relPath = os.environ['CMSSW_RELEASE_BASE'] + '/src/'
89 
90  lines = { 'read312RV' : ['cmsRun '+self.file2Path('Utilities/ReleaseScripts/scripts/read312RV_cfg.py')],
91  'fastsim' : ["cmsDriver.py TTbar_8TeV_TuneCUETP8M1_cfi --conditions auto:run1_mc --fast -n 100 --eventcontent AODSIM,DQM --relval 100000,1000 -s GEN,SIM,RECOBEFMIX,DIGI:pdigi_valid,L1,DIGI2RAW,L1Reco,RECO,EI,VALIDATION --customise=HLTrigger/Configuration/CustomConfigs.L1THLT --datatier GEN-SIM-DIGI-RECO,DQMIO --beamspot Realistic8TeVCollision"],
92  'fastsim1' : ["cmsDriver.py TTbar_13TeV_TuneCUETP8M1_cfi --conditions auto:run2_mc_l1stage1 --fast -n 100 --eventcontent AODSIM,DQM --relval 100000,1000 -s GEN,SIM,RECOBEFMIX,DIGI:pdigi_valid,L1,DIGI2RAW,L1Reco,RECO,EI,VALIDATION --customise=HLTrigger/Configuration/CustomConfigs.L1THLT --datatier GEN-SIM-DIGI-RECO,DQMIO --beamspot NominalCollision2015 --era Run2_25ns"],
93  'fastsim2' : ["cmsDriver.py TTbar_13TeV_TuneCUETP8M1_cfi --conditions auto:run2_mc --fast -n 100 --eventcontent AODSIM,DQM --relval 100000,1000 -s GEN,SIM,RECOBEFMIX,DIGI:pdigi_valid,L1,DIGI2RAW,L1Reco,RECO,EI,VALIDATION --customise=HLTrigger/Configuration/CustomConfigs.L1THLT --datatier GEN-SIM-DIGI-RECO,DQMIO --beamspot NominalCollision2015 --era Run2_2016"],
94  'pat1' : ['cmsRun '+self.file2Path('PhysicsTools/PatAlgos/test/IntegrationTest_cfg.py')],
95  }
96 
97  hltTests = {}
98  hltFlag_data = ' realData=True globalTag=@ inputFiles=@ '
99  hltFlag_mc = ' realData=False globalTag=@ inputFiles=@ '
100  from Configuration.HLT.addOnTestsHLT import addOnTestsHLT
101  hltTestsToAdd = addOnTestsHLT()
102  for key in hltTestsToAdd:
103  if '_data_' in key:
104  hltTests[key] = [hltTestsToAdd[key][0],
105  'cmsRun '+self.file2Path(hltTestsToAdd[key][1])+hltFlag_data,
106  hltTestsToAdd[key][2]]
107  elif '_mc_' in key:
108  hltTests[key] = [hltTestsToAdd[key][0],
109  'cmsRun '+self.file2Path(hltTestsToAdd[key][1])+hltFlag_mc,
110  hltTestsToAdd[key][2]]
111  else:
112  hltTests[key] = [hltTestsToAdd[key][0],
113  'cmsRun '+self.file2Path(hltTestsToAdd[key][1]),
114  hltTestsToAdd[key][2]]
115 
116  self.commands={}
117  for dirName, command in lines.items():
118  self.commands[dirName] = command
119 
120  for dirName, commandList in hltTests.items():
121  self.commands[dirName] = commandList
122  return
123 
124  def dumpTest(self):
125  print(",".join(self.commands.keys()))
126  return
127 
128  def file2Path(self,rFile):
129 
130  fullPath = self.relPath + rFile
131  if os.path.exists(self.devPath + rFile): fullPath = self.devPath + rFile
132  return fullPath
133 
134  def runTests(self, testList = None):
135 
136  actDir = os.getcwd()
137 
138  if not os.path.exists('addOnTests'):
139  os.makedirs('addOnTests')
140  os.chdir('addOnTests')
141 
142  nfail=0
143  npass=0
144  report=''
145 
146  print('Running in %s thread(s)' % self.maxThreads)
147 
148  for dirName, command in self.commands.items():
149 
150  if testList and not dirName in testList:
151  del self.commands[dirName]
152  continue
153 
154  # make sure we don't run more than the allowed number of threads:
155  while self.activeThreads() >= self.maxThreads:
156  time.sleep(10)
157  continue
158 
159  print('Preparing to run %s' % str(command))
160  current = testit(dirName, command)
161  self.threadList.append(current)
162  current.start()
163  time.sleep(random.randint(1,5)) # try to avoid race cond by sleeping random amount of time [1,5] sec
164 
165  # wait until all threads are finished
166  while self.activeThreads() > 0:
167  time.sleep(5)
168 
169  # all threads are done now, check status ...
170  for pingle in self.threadList:
171  pingle.join()
172  for f in pingle.nfail: nfail += f
173  for p in pingle.npass: npass += p
174  report += pingle.report
175  print(pingle.report)
176  sys.stdout.flush()
177 
178  reportSumm = '\n %s tests passed, %s failed \n' %(npass,nfail)
179  print(reportSumm)
180 
181  runall_report_name='runall-report.log'
182  runall_report=open(runall_report_name,'w')
183  runall_report.write(report+reportSumm)
184  runall_report.close()
185 
186  # get the logs to the logs dir:
187  print('==> in :', os.getcwd())
188  print(' going to copy log files to logs dir ...')
189  if not os.path.exists('logs'):
190  os.makedirs('logs')
191  for dirName in self.commands:
192  cmd = "for L in `ls "+dirName+"/*.log`; do cp $L logs/cmsDriver-`dirname $L`_`basename $L` ; done"
193  print("going to ",cmd)
194  os.system(cmd)
195 
196  import pickle
197  pickle.dump(self.commands, open('logs/addOnTests.pkl', 'wb'), protocol=2)
198 
199  os.chdir(actDir)
200 
201  return
202 
203  def upload(self, tgtDir):
204 
205  print("in ", os.getcwd())
206 
207  if not os.path.exists(tgtDir):
208  os.makedirs(tgtDir)
209 
210  cmd = 'tar cf - addOnTests.log addOnTests/logs | (cd '+tgtDir+' ; tar xf - ) '
211  try:
212  print('executing: ',cmd)
213  ret = os.system(cmd)
214  if ret != 0:
215  print("ERROR uploading logs:", ret, cmd)
216  except Exception as e:
217  print("EXCEPTION while uploading addOnTest-logs : ", str(e))
218 
219  return
220 
221 
222 def main(argv) :
223 
224  import getopt
225 
226  try:
227  opts, args = getopt.getopt(argv, "dj:t:", ["nproc=", 'uploadDir=', 'tests=','noRun','dump'])
228  except getopt.GetoptError as e:
229  print("unknown option", str(e))
230  sys.exit(2)
231 
232  np = 4
233  uploadDir = None
234  runTests = True
235  testList = None
236  dump = False
237  for opt, arg in opts :
238  if opt in ('-j', "--nproc" ):
239  np=int(arg)
240  if opt in ("--uploadDir", ):
241  uploadDir = arg
242  if opt in ('--noRun', ):
243  runTests = False
244  if opt in ('-d','--dump', ):
245  dump = True
246  if opt in ('-t','--tests', ):
247  testList = arg.split(",")
248 
249  tester = StandardTester(np)
250  if dump:
251  tester.dumpTest()
252  else:
253  if runTests:
254  tester.runTests(testList)
255  if uploadDir:
256  tester.upload(uploadDir)
257  return
258 
259 if __name__ == '__main__' :
260  main(sys.argv[1:])
addOnTests.StandardTester.threadList
threadList
Definition: addOnTests.py:70
FastTimerService_cff.range
range
Definition: FastTimerService_cff.py:34
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
addOnTests.StandardTester.relPath
relPath
Definition: addOnTests.py:87
addOnTests.testit.__init__
def __init__(self, dirName, commandList)
Definition: addOnTests.py:18
addOnTests.StandardTester.runTests
def runTests(self, testList=None)
Definition: addOnTests.py:134
addOnTests.testit.report
report
Definition: addOnTests.py:23
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
addOnTests.testit.status
status
Definition: addOnTests.py:22
addOnTests.testit.npass
npass
Definition: addOnTests.py:25
addOnTests.StandardTester.activeThreads
def activeThreads(self)
Definition: addOnTests.py:76
addOnTests.StandardTester.maxThreads
maxThreads
Definition: addOnTests.py:71
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
addOnTests.testit
Definition: addOnTests.py:17
addOnTests.StandardTester
Definition: addOnTests.py:66
addOnTests.testit.dirName
dirName
Definition: addOnTests.py:20
mps_monitormerge.items
list items
Definition: mps_monitormerge.py:29
addOnTests.main
def main(argv)
Definition: addOnTests.py:222
str
#define str(s)
Definition: TestProcessor.cc:53
addOnTests.StandardTester.devPath
devPath
Definition: addOnTests.py:86
addOnTests.StandardTester.file2Path
def file2Path(self, rFile)
Definition: addOnTests.py:128
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
addOnTests.StandardTester.commands
commands
Definition: addOnTests.py:116
addOnTests.StandardTester.dumpTest
def dumpTest(self)
Definition: addOnTests.py:124
mps_setup.append
append
Definition: mps_setup.py:85
createfilelist.int
int
Definition: createfilelist.py:10
addOnTests.testit.nfail
nfail
Definition: addOnTests.py:24
main
Definition: main.py:1
addOnTests.StandardTester.__init__
def __init__(self, nThrMax=4)
Definition: addOnTests.py:68
addOnTests.StandardTester.upload
def upload(self, tgtDir)
Definition: addOnTests.py:203
addOnTests.testit.commandList
commandList
Definition: addOnTests.py:21
addOnTestsHLT
Definition: addOnTestsHLT.py:1
addOnTests.testit.run
def run(self)
Definition: addOnTests.py:29
python.rootplot.root2matplotlib.replace
def replace(string, replacements)
Definition: root2matplotlib.py:444
addOnTests.StandardTester.prepare
def prepare(self)
Definition: addOnTests.py:84