base.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. # Copyright (c) 2016, Intel Corporation.
  2. #
  3. # This program is free software; you can redistribute it and/or modify it
  4. # under the terms and conditions of the GNU General Public License,
  5. # version 2, as published by the Free Software Foundation.
  6. #
  7. # This program is distributed in the hope it will be useful, but WITHOUT
  8. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  9. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  10. # more details.
  11. #
  12. """Build performance test base classes and functionality"""
  13. import glob
  14. import logging
  15. import os
  16. import re
  17. import shutil
  18. import socket
  19. import tempfile
  20. import time
  21. import traceback
  22. import unittest
  23. from datetime import datetime, timedelta
  24. from functools import partial
  25. import oe.path
  26. from oeqa.utils.commands import CommandError, runCmd, get_bb_vars
  27. from oeqa.utils.git import GitError, GitRepo
  28. # Get logger for this module
  29. log = logging.getLogger('build-perf')
  30. # Our own version of runCmd which does not raise AssertErrors which would cause
  31. # errors to interpreted as failures
  32. runCmd2 = partial(runCmd, assert_error=False)
  33. class KernelDropCaches(object):
  34. """Container of the functions for dropping kernel caches"""
  35. sudo_passwd = None
  36. @classmethod
  37. def check(cls):
  38. """Check permssions for dropping kernel caches"""
  39. from getpass import getpass
  40. from locale import getdefaultlocale
  41. cmd = ['sudo', '-k', '-n', 'tee', '/proc/sys/vm/drop_caches']
  42. ret = runCmd2(cmd, ignore_status=True, data=b'0')
  43. if ret.output.startswith('sudo:'):
  44. pass_str = getpass(
  45. "\nThe script requires sudo access to drop caches between "
  46. "builds (echo 3 > /proc/sys/vm/drop_caches).\n"
  47. "Please enter your sudo password: ")
  48. cls.sudo_passwd = bytes(pass_str, getdefaultlocale()[1])
  49. @classmethod
  50. def drop(cls):
  51. """Drop kernel caches"""
  52. cmd = ['sudo', '-k']
  53. if cls.sudo_passwd:
  54. cmd.append('-S')
  55. input_data = cls.sudo_passwd + b'\n'
  56. else:
  57. cmd.append('-n')
  58. input_data = b''
  59. cmd += ['tee', '/proc/sys/vm/drop_caches']
  60. input_data += b'3'
  61. runCmd2(cmd, data=input_data)
  62. def time_cmd(cmd, **kwargs):
  63. """TIme a command"""
  64. with tempfile.NamedTemporaryFile(mode='w+') as tmpf:
  65. timecmd = ['/usr/bin/time', '-v', '-o', tmpf.name]
  66. if isinstance(cmd, str):
  67. timecmd = ' '.join(timecmd) + ' '
  68. timecmd += cmd
  69. # TODO: 'ignore_status' could/should be removed when globalres.log is
  70. # deprecated. The function would just raise an exception, instead
  71. ret = runCmd2(timecmd, ignore_status=True, **kwargs)
  72. timedata = tmpf.file.read()
  73. return ret, timedata
  74. class BuildPerfTestResult(unittest.TextTestResult):
  75. """Runner class for executing the individual tests"""
  76. # List of test cases to run
  77. test_run_queue = []
  78. def __init__(self, out_dir, *args, **kwargs):
  79. super(BuildPerfTestResult, self).__init__(*args, **kwargs)
  80. self.out_dir = out_dir
  81. # Get Git parameters
  82. try:
  83. self.repo = GitRepo('.')
  84. except GitError:
  85. self.repo = None
  86. self.git_commit, self.git_commit_count, self.git_branch = \
  87. self.get_git_revision()
  88. self.hostname = socket.gethostname()
  89. self.start_time = self.elapsed_time = None
  90. self.successes = []
  91. log.info("Using Git branch:commit %s:%s (%s)", self.git_branch,
  92. self.git_commit, self.git_commit_count)
  93. def get_git_revision(self):
  94. """Get git branch and commit under testing"""
  95. commit = os.getenv('OE_BUILDPERFTEST_GIT_COMMIT')
  96. commit_cnt = os.getenv('OE_BUILDPERFTEST_GIT_COMMIT_COUNT')
  97. branch = os.getenv('OE_BUILDPERFTEST_GIT_BRANCH')
  98. if not self.repo and (not commit or not commit_cnt or not branch):
  99. log.info("The current working directory doesn't seem to be a Git "
  100. "repository clone. You can specify branch and commit "
  101. "displayed in test results with OE_BUILDPERFTEST_GIT_BRANCH, "
  102. "OE_BUILDPERFTEST_GIT_COMMIT and "
  103. "OE_BUILDPERFTEST_GIT_COMMIT_COUNT environment variables")
  104. else:
  105. if not commit:
  106. commit = self.repo.rev_parse('HEAD^0')
  107. commit_cnt = self.repo.run_cmd(['rev-list', '--count', 'HEAD^0'])
  108. if not branch:
  109. branch = self.repo.get_current_branch()
  110. if not branch:
  111. log.debug('Currently on detached HEAD')
  112. return str(commit), str(commit_cnt), str(branch)
  113. def addSuccess(self, test):
  114. """Record results from successful tests"""
  115. super(BuildPerfTestResult, self).addSuccess(test)
  116. self.successes.append((test, None))
  117. def startTest(self, test):
  118. """Pre-test hook"""
  119. test.out_dir = self.out_dir
  120. log.info("Executing test %s: %s", test.name, test.shortDescription())
  121. self.stream.write(datetime.now().strftime("[%Y-%m-%d %H:%M:%S] "))
  122. super(BuildPerfTestResult, self).startTest(test)
  123. def startTestRun(self):
  124. """Pre-run hook"""
  125. self.start_time = datetime.utcnow()
  126. def stopTestRun(self):
  127. """Pre-run hook"""
  128. self.elapsed_time = datetime.utcnow() - self.start_time
  129. def all_results(self):
  130. result_map = {'SUCCESS': self.successes,
  131. 'FAIL': self.failures,
  132. 'ERROR': self.errors,
  133. 'EXP_FAIL': self.expectedFailures,
  134. 'UNEXP_SUCCESS': self.unexpectedSuccesses}
  135. for status, tests in result_map.items():
  136. for test in tests:
  137. yield (status, test)
  138. def update_globalres_file(self, filename):
  139. """Write results to globalres csv file"""
  140. # Map test names to time and size columns in globalres
  141. # The tuples represent index and length of times and sizes
  142. # respectively
  143. gr_map = {'test1': ((0, 1), (8, 1)),
  144. 'test12': ((1, 1), (None, None)),
  145. 'test13': ((2, 1), (9, 1)),
  146. 'test2': ((3, 1), (None, None)),
  147. 'test3': ((4, 3), (None, None)),
  148. 'test4': ((7, 1), (10, 2))}
  149. if self.repo:
  150. git_tag_rev = self.repo.run_cmd(['describe', self.git_commit])
  151. else:
  152. git_tag_rev = self.git_commit
  153. values = ['0'] * 12
  154. for status, (test, msg) in self.all_results():
  155. if status not in ['SUCCESS', 'FAILURE', 'EXP_SUCCESS']:
  156. continue
  157. (t_ind, t_len), (s_ind, s_len) = gr_map[test.name]
  158. if t_ind is not None:
  159. values[t_ind:t_ind + t_len] = test.times
  160. if s_ind is not None:
  161. values[s_ind:s_ind + s_len] = test.sizes
  162. log.debug("Writing globalres log to %s", filename)
  163. with open(filename, 'a') as fobj:
  164. fobj.write('{},{}:{},{},'.format(self.hostname,
  165. self.git_branch,
  166. self.git_commit,
  167. git_tag_rev))
  168. fobj.write(','.join(values) + '\n')
  169. def git_commit_results(self, repo_path, branch=None, tag=None):
  170. """Commit results into a Git repository"""
  171. repo = GitRepo(repo_path, is_topdir=True)
  172. if not branch:
  173. branch = self.git_branch
  174. else:
  175. # Replace keywords
  176. branch = branch.format(git_branch=self.git_branch,
  177. tester_host=self.hostname)
  178. log.info("Committing test results into %s %s", repo_path, branch)
  179. tmp_index = os.path.join(repo_path, '.git', 'index.oe-build-perf')
  180. try:
  181. # Create new commit object from the new results
  182. env_update = {'GIT_INDEX_FILE': tmp_index,
  183. 'GIT_WORK_TREE': self.out_dir}
  184. repo.run_cmd('add .', env_update)
  185. tree = repo.run_cmd('write-tree', env_update)
  186. parent = repo.rev_parse(branch)
  187. msg = "Results of {}:{}\n".format(self.git_branch, self.git_commit)
  188. git_cmd = ['commit-tree', tree, '-m', msg]
  189. if parent:
  190. git_cmd += ['-p', parent]
  191. commit = repo.run_cmd(git_cmd, env_update)
  192. # Update branch head
  193. git_cmd = ['update-ref', 'refs/heads/' + branch, commit]
  194. if parent:
  195. git_cmd.append(parent)
  196. repo.run_cmd(git_cmd)
  197. # Update current HEAD, if we're on branch 'branch'
  198. if repo.get_current_branch() == branch:
  199. log.info("Updating %s HEAD to latest commit", repo_path)
  200. repo.run_cmd('reset --hard')
  201. # Create (annotated) tag
  202. if tag:
  203. # Find tags matching the pattern
  204. tag_keywords = dict(git_branch=self.git_branch,
  205. git_commit=self.git_commit,
  206. git_commit_count=self.git_commit_count,
  207. tester_host=self.hostname,
  208. tag_num='[0-9]{1,5}')
  209. tag_re = re.compile(tag.format(**tag_keywords) + '$')
  210. tag_keywords['tag_num'] = 0
  211. for existing_tag in repo.run_cmd('tag').splitlines():
  212. if tag_re.match(existing_tag):
  213. tag_keywords['tag_num'] += 1
  214. tag = tag.format(**tag_keywords)
  215. msg = "Test run #{} of {}:{}\n".format(tag_keywords['tag_num'],
  216. self.git_branch,
  217. self.git_commit)
  218. repo.run_cmd(['tag', '-a', '-m', msg, tag, commit])
  219. finally:
  220. if os.path.exists(tmp_index):
  221. os.unlink(tmp_index)
  222. class BuildPerfTestCase(unittest.TestCase):
  223. """Base class for build performance tests"""
  224. SYSRES = 'sysres'
  225. DISKUSAGE = 'diskusage'
  226. def __init__(self, *args, **kwargs):
  227. super(BuildPerfTestCase, self).__init__(*args, **kwargs)
  228. self.name = self._testMethodName
  229. self.out_dir = None
  230. self.start_time = None
  231. self.elapsed_time = None
  232. self.measurements = []
  233. self.bb_vars = get_bb_vars()
  234. # TODO: remove 'times' and 'sizes' arrays when globalres support is
  235. # removed
  236. self.times = []
  237. self.sizes = []
  238. def run(self, *args, **kwargs):
  239. """Run test"""
  240. self.start_time = datetime.now()
  241. super(BuildPerfTestCase, self).run(*args, **kwargs)
  242. self.elapsed_time = datetime.now() - self.start_time
  243. def log_cmd_output(self, cmd):
  244. """Run a command and log it's output"""
  245. cmd_str = cmd if isinstance(cmd, str) else ' '.join(cmd)
  246. log.info("Logging command: %s", cmd_str)
  247. cmd_log = os.path.join(self.out_dir, 'commands.log')
  248. try:
  249. with open(cmd_log, 'a') as fobj:
  250. runCmd2(cmd, stdout=fobj)
  251. except CommandError as err:
  252. log.error("Command failed: %s", err.retcode)
  253. raise
  254. def measure_cmd_resources(self, cmd, name, legend):
  255. """Measure system resource usage of a command"""
  256. def str_time_to_timedelta(strtime):
  257. """Convert time strig from the time utility to timedelta"""
  258. split = strtime.split(':')
  259. hours = int(split[0]) if len(split) > 2 else 0
  260. mins = int(split[-2])
  261. try:
  262. secs, frac = split[-1].split('.')
  263. except:
  264. secs = split[-1]
  265. frac = '0'
  266. secs = int(secs)
  267. microsecs = int(float('0.' + frac) * pow(10, 6))
  268. return timedelta(0, hours*3600 + mins*60 + secs, microsecs)
  269. cmd_str = cmd if isinstance(cmd, str) else ' '.join(cmd)
  270. log.info("Timing command: %s", cmd_str)
  271. cmd_log = os.path.join(self.out_dir, 'commands.log')
  272. with open(cmd_log, 'a') as fobj:
  273. ret, timedata = time_cmd(cmd, stdout=fobj)
  274. if ret.status:
  275. log.error("Time will be reported as 0. Command failed: %s",
  276. ret.status)
  277. etime = timedelta(0)
  278. self._failed = True
  279. else:
  280. match = re.search(r'.*wall clock.*: (?P<etime>.*)\n', timedata)
  281. etime = str_time_to_timedelta(match.group('etime'))
  282. measurement = {'type': self.SYSRES,
  283. 'name': name,
  284. 'legend': legend}
  285. measurement['values'] = {'elapsed_time': etime}
  286. self.measurements.append(measurement)
  287. e_sec = etime.total_seconds()
  288. nlogs = len(glob.glob(self.out_dir + '/results.log*'))
  289. results_log = os.path.join(self.out_dir,
  290. 'results.log.{}'.format(nlogs + 1))
  291. with open(results_log, 'w') as fobj:
  292. fobj.write(timedata)
  293. # Append to 'times' array for globalres log
  294. self.times.append('{:d}:{:02d}:{:.2f}'.format(int(e_sec / 3600),
  295. int((e_sec % 3600) / 60),
  296. e_sec % 60))
  297. def measure_disk_usage(self, path, name, legend):
  298. """Estimate disk usage of a file or directory"""
  299. # TODO: 'ignore_status' could/should be removed when globalres.log is
  300. # deprecated. The function would just raise an exception, instead
  301. ret = runCmd2(['du', '-s', path], ignore_status=True)
  302. if ret.status:
  303. log.error("du failed, disk usage will be reported as 0")
  304. size = 0
  305. self._failed = True
  306. else:
  307. size = int(ret.output.split()[0])
  308. log.debug("Size of %s path is %s", path, size)
  309. measurement = {'type': self.DISKUSAGE,
  310. 'name': name,
  311. 'legend': legend}
  312. measurement['values'] = {'size': size}
  313. self.measurements.append(measurement)
  314. # Append to 'sizes' array for globalres log
  315. self.sizes.append(str(size))
  316. def save_buildstats(self):
  317. """Save buildstats"""
  318. shutil.move(self.bb_vars['BUILDSTATS_BASE'],
  319. os.path.join(self.out_dir, 'buildstats-' + self.name))
  320. def rm_tmp(self):
  321. """Cleanup temporary/intermediate files and directories"""
  322. log.debug("Removing temporary and cache files")
  323. for name in ['bitbake.lock', 'conf/sanity_info',
  324. self.bb_vars['TMPDIR']]:
  325. oe.path.remove(name, recurse=True)
  326. def rm_sstate(self):
  327. """Remove sstate directory"""
  328. log.debug("Removing sstate-cache")
  329. oe.path.remove(self.bb_vars['SSTATE_DIR'], recurse=True)
  330. def rm_cache(self):
  331. """Drop bitbake caches"""
  332. oe.path.remove(self.bb_vars['PERSISTENT_DIR'], recurse=True)
  333. @staticmethod
  334. def sync():
  335. """Sync and drop kernel caches"""
  336. log.debug("Syncing and dropping kernel caches""")
  337. KernelDropCaches.drop()
  338. os.sync()
  339. # Wait a bit for all the dirty blocks to be written onto disk
  340. time.sleep(3)
  341. class BuildPerfTestLoader(unittest.TestLoader):
  342. """Test loader for build performance tests"""
  343. sortTestMethodsUsing = None
  344. class BuildPerfTestRunner(unittest.TextTestRunner):
  345. """Test loader for build performance tests"""
  346. sortTestMethodsUsing = None
  347. def __init__(self, out_dir, *args, **kwargs):
  348. super(BuildPerfTestRunner, self).__init__(*args, **kwargs)
  349. self.out_dir = out_dir
  350. def _makeResult(self):
  351. return BuildPerfTestResult(self.out_dir, self.stream, self.descriptions,
  352. self.verbosity)