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,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,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,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  if testList:
149  self.commands = {d:c for d,c in self.commands.items() if d in testList}
150  for dirName, command in self.commands.items():
151 
152  # make sure we don't run more than the allowed number of threads:
153  while self.activeThreads() >= self.maxThreads:
154  time.sleep(10)
155  continue
156 
157  print('Preparing to run %s' % str(command))
158  current = testit(dirName, command)
159  self.threadList.append(current)
160  current.start()
161  time.sleep(random.randint(1,5)) # try to avoid race cond by sleeping random amount of time [1,5] sec
162 
163  # wait until all threads are finished
164  while self.activeThreads() > 0:
165  time.sleep(5)
166 
167  # all threads are done now, check status ...
168  for pingle in self.threadList:
169  pingle.join()
170  for f in pingle.nfail: nfail += f
171  for p in pingle.npass: npass += p
172  report += pingle.report
173  print(pingle.report)
174  sys.stdout.flush()
175 
176  reportSumm = '\n %s tests passed, %s failed \n' %(npass,nfail)
177  print(reportSumm)
178 
179  runall_report_name='runall-report.log'
180  runall_report=open(runall_report_name,'w')
181  runall_report.write(report+reportSumm)
182  runall_report.close()
183 
184  # get the logs to the logs dir:
185  print('==> in :', os.getcwd())
186  print(' going to copy log files to logs dir ...')
187  if not os.path.exists('logs'):
188  os.makedirs('logs')
189  for dirName in self.commands:
190  cmd = "for L in `ls "+dirName+"/*.log`; do cp $L logs/cmsDriver-`dirname $L`_`basename $L` ; done"
191  print("going to ",cmd)
192  os.system(cmd)
193 
194  import pickle
195  pickle.dump(self.commands, open('logs/addOnTests.pkl', 'wb'), protocol=2)
196 
197  os.chdir(actDir)
198 
199  return
200 
201  def upload(self, tgtDir):
202 
203  print("in ", os.getcwd())
204 
205  if not os.path.exists(tgtDir):
206  os.makedirs(tgtDir)
207 
208  cmd = 'tar cf - addOnTests.log addOnTests/logs | (cd '+tgtDir+' ; tar xf - ) '
209  try:
210  print('executing: ',cmd)
211  ret = os.system(cmd)
212  if ret != 0:
213  print("ERROR uploading logs:", ret, cmd)
214  except Exception as e:
215  print("EXCEPTION while uploading addOnTest-logs : ", str(e))
216 
217  return
218 
219 
220 def main(argv) :
221 
222  import getopt
223 
224  try:
225  opts, args = getopt.getopt(argv, "dj:t:", ["nproc=", 'uploadDir=', 'tests=','noRun','dump'])
226  except getopt.GetoptError as e:
227  print("unknown option", str(e))
228  sys.exit(2)
229 
230  np = 4
231  uploadDir = None
232  runTests = True
233  testList = None
234  dump = False
235  for opt, arg in opts :
236  if opt in ('-j', "--nproc" ):
237  np=int(arg)
238  if opt in ("--uploadDir", ):
239  uploadDir = arg
240  if opt in ('--noRun', ):
241  runTests = False
242  if opt in ('-d','--dump', ):
243  dump = True
244  if opt in ('-t','--tests', ):
245  testList = arg.split(",")
246 
247  tester = StandardTester(np)
248  if dump:
249  tester.dumpTest()
250  else:
251  if runTests:
252  tester.runTests(testList)
253  if uploadDir:
254  tester.upload(uploadDir)
255  return
256 
257 if __name__ == '__main__' :
258  main(sys.argv[1:])
def file2Path(self, rFile)
Definition: addOnTests.py:128
def upload(self, tgtDir)
Definition: addOnTests.py:201
def replace(string, replacements)
def main(argv)
Definition: addOnTests.py:220
def __init__(self, dirName, commandList)
Definition: addOnTests.py:18
def __init__(self, nThrMax=4)
Definition: addOnTests.py:68
def runTests(self, testList=None)
Definition: addOnTests.py:134
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
Definition: main.py:1
#define str(s)
def run(self)
Definition: addOnTests.py:29