CMS 3D CMS Logo

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